use width_search::{GoalCount, SearchResult, WidthProblem, bfws, iterated_width, siw};
const FLOOR: &[&str] = &[
"###########",
"#R....#..A#",
"#.###.#.###",
"#a..#...#B#",
"#b..###.#.#",
"#c........#",
"#####.###C#",
" #######",
];
#[derive(Clone, Copy, Debug)]
enum Action {
Move(isize, isize),
Pick(usize),
Drop,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Place {
Cell(usize),
Carried,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct State {
robot: usize,
parcels: Vec<Place>,
}
struct Warehouse {
cells: Vec<Vec<u8>>,
width: usize,
start: State,
shelves: Vec<usize>,
}
impl Warehouse {
fn parse(floor: &[&str]) -> Self {
let cells: Vec<Vec<u8>> = floor.iter().map(|r| r.bytes().collect()).collect();
let width = cells.iter().map(Vec::len).max().unwrap_or(0);
let find = |c: u8| {
cells
.iter()
.enumerate()
.find_map(|(y, row)| row.iter().position(|&b| b == c).map(|x| y * width + x))
};
let robot = find(b'R').expect("the floor has a robot");
let mut parcels = Vec::new();
let mut shelves = Vec::new();
for letter in b'a'..=b'z' {
let Some(cell) = find(letter) else { break };
parcels.push(Place::Cell(cell));
shelves.push(find(letter.to_ascii_uppercase()).expect("every parcel has a shelf"));
}
Self {
cells,
width,
start: State { robot, parcels },
shelves,
}
}
fn is_free(&self, index: usize) -> bool {
let (x, y) = (index % self.width, index / self.width);
self.cells
.get(y)
.and_then(|r| r.get(x))
.is_some_and(|&c| c != b'#' && c != b' ')
}
fn num_cells(&self) -> usize {
self.cells.len() * self.width
}
fn id(index: usize) -> u32 {
u32::try_from(index).expect("fewer than 2^32 features")
}
}
impl WidthProblem for Warehouse {
type State = State;
type Action = Action;
fn initial_state(&self) -> State {
self.start.clone()
}
fn successors(&self, s: &State, out: &mut Vec<(Action, State)>) {
for (dx, dy) in [(0, -1), (0, 1), (-1, 0), (1, 0)] {
let (x, y) = (s.robot % self.width, s.robot / self.width);
let (Some(x), Some(y)) = (x.checked_add_signed(dx), y.checked_add_signed(dy)) else {
continue;
};
let target = y * self.width + x;
if x < self.width && self.is_free(target) {
out.push((
Action::Move(dx, dy),
State {
robot: target,
..s.clone()
},
));
}
}
let carrying = s.parcels.iter().position(|&p| p == Place::Carried);
match carrying {
Some(i) => {
let mut next = s.clone();
next.parcels[i] = Place::Cell(s.robot);
out.push((Action::Drop, next));
}
None => {
for (i, &p) in s.parcels.iter().enumerate() {
if p == Place::Cell(s.robot) {
let mut next = s.clone();
next.parcels[i] = Place::Carried;
out.push((Action::Pick(i), next));
}
}
}
}
}
fn features(&self, s: &State, out: &mut Vec<u32>) {
let cells = self.num_cells();
out.push(Self::id(s.robot));
for (i, p) in s.parcels.iter().enumerate() {
let offset = cells + i * (cells + 1);
let place = match p {
Place::Cell(c) => *c,
Place::Carried => cells,
};
out.push(Self::id(offset + place));
}
}
fn num_features(&self) -> usize {
self.num_cells() * (1 + self.shelves.len()) + self.shelves.len()
}
fn is_goal(&self, s: &State) -> bool {
self.unsatisfied_goals(s) == 0
}
}
impl GoalCount for Warehouse {
fn unsatisfied_goals(&self, s: &State) -> usize {
s.parcels
.iter()
.zip(&self.shelves)
.filter(|&(p, &shelf)| *p != Place::Cell(shelf))
.count()
}
}
fn report(name: &str, r: &SearchResult<Action>) {
let plan = r
.plan
.as_ref()
.map_or("no plan".to_string(), |p| format!("{} steps", p.len()));
println!("{name:<22} {plan:>10} {:>10} expanded", r.expanded);
}
fn render(plan: &[Action]) -> String {
plan.iter()
.map(|a| match *a {
Action::Move(0, -1) => '^',
Action::Move(0, _) => 'v',
Action::Move(-1, _) => '<',
Action::Move(..) => '>',
Action::Pick(i) => char::from(b'a' + u8::try_from(i).expect("few parcels")),
Action::Drop => '.',
})
.collect()
}
fn main() {
let warehouse = Warehouse::parse(FLOOR);
println!("{} parcels to shelve\n", warehouse.shelves.len());
let (_, r) = iterated_width(&warehouse, 2);
report("IW(1), IW(2)", &r);
report("SIW, max width 2", &siw(&warehouse, 2));
let r = bfws(&warehouse, 2);
report("BFWS(<w_#g, #g>), k=2", &r);
println!(
"\nBFWS plan: {}",
render(&r.plan.expect("BFWS is complete"))
);
}