summary refs log tree commit diff
path: root/23/src/main.rs
blob: 636337cbeb2cea74c2e07df3904f4d5a7214de49 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
use advent_lib::prelude::*;

use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::cmp::Reverse;


#[derive(Debug,Clone,Copy,Eq,PartialEq,Hash)]
enum Amphipod {
  A,
  B,
  C,
  D,
}

#[derive(Debug,Clone,Eq,PartialEq)]
enum Place {
  Room(usize),
  Hallway(usize),
}

#[derive(Debug,Clone,Eq,PartialEq)]
struct Parameters {
  room_size: usize,
}

#[derive(Debug,Clone,Eq)]
struct State {
  expense_so_far: usize,
  hallway: Vec<Option<Amphipod>>,
  rooms: Vec<Vec<Amphipod>>,
  last_destination: Option<Place>,
}

#[derive(Debug,Clone,Eq,PartialEq,Hash)]
struct StaticState {
  hallway: Vec<Option<Amphipod>>,
  rooms: Vec<Vec<Amphipod>>,
}

impl Ord for State {
  fn cmp(&self, other: &Self) -> std::cmp::Ordering {
    Reverse(&self.expense_so_far).cmp(&Reverse(&other.expense_so_far))
  }
}

impl PartialOrd for State {
  fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
    Some(Reverse(&self.expense_so_far).cmp(&Reverse(&other.expense_so_far)))
  }
}

impl PartialEq for State {
  fn eq(&self, other: &Self) -> bool {
    self.expense_so_far == other.expense_so_far
  }
}


fn main() -> Result<()> {
  let mut args = std::env::args();
  if args.len() != 2 {
    eprintln!("Usage: advent input");
  }
  let _ = args.next();
  let filename = args.next().unwrap();

  let input = advent_lib::read_lines_file(&filename)?;

  let mut hallway = Vec::new();
  for _ in 0 .. 11 {
    hallway.push(None);
  }

  let mut rooms = Vec::new();
  for i in 0 .. 4 {
    let mut room = Vec::new();
    let x = 3 + 2 * i;
    for j in 0 .. 2 {
      let y = 3 - j;
      let c = input[y].chars().nth(x).unwrap();
      let amphipod = match c {
        'A' => Amphipod::A,
        'B' => Amphipod::B,
        'C' => Amphipod::C,
        'D' => Amphipod::D,
        _ => { panic!("Unexpected character."); }
      };
      room.push(amphipod);
    }
    rooms.push(room);
  }

  let initial_state = State {
    expense_so_far: 0,
    hallway,
    rooms,
    last_destination: None,
  };

  let expense = find_steps(&Parameters { room_size: 2 }, &initial_state);
  println!("{}", expense);

  let mut harder_rooms = Vec::new();
  for i in 0 .. 4 {
    let mut harder_room = Vec::new();
    harder_room.push(initial_state.rooms[i][0]);
    match i {
      0 => {
        harder_room.push(Amphipod::D);
        harder_room.push(Amphipod::D);
      }
      1 => {
        harder_room.push(Amphipod::B);
        harder_room.push(Amphipod::C);
      }
      2 => {
        harder_room.push(Amphipod::A);
        harder_room.push(Amphipod::B);
      }
      3 => {
        harder_room.push(Amphipod::C);
        harder_room.push(Amphipod::A);
      }
      _ => { }
    }
    harder_room.push(initial_state.rooms[i][1]);
    harder_rooms.push(harder_room);
  }
  let harder_initial_state = State {
    expense_so_far: 0,
    hallway: initial_state.hallway.clone(),
    rooms: harder_rooms,
    last_destination: None,
  };

  let harder_expense = find_steps(&Parameters { room_size: 4 },
    &harder_initial_state);
  println!("{}", harder_expense);

  Ok(())
}


fn find_steps(parameters: &Parameters, initial_state: &State) -> usize {
  let mut exploration_queue = BinaryHeap::new();
  exploration_queue.push(initial_state.clone());

  let mut visited_states = HashMap::new();

  //let mut i = 0;
  loop {
    let state = match exploration_queue.pop() {
      None => { panic!("insoluble"); }
      Some(state) => { state }
    };

    if is_solved(parameters, &state) {
      return state.expense_so_far;
    }

    let static_state = StaticState {
      hallway: state.hallway.clone(),
      rooms: state.rooms.clone(),
    };

    match visited_states.get(&static_state) {
      None => { }
      Some(_) => { continue; }
    }

    visited_states.insert(static_state, state.expense_so_far);

    //i += 1;
    //if (parameters.room_size == 4) && (i % 10000 == 0) {
    //  println!("iteration {}, cost {}", i, state.expense_so_far);
    //  debug_state(parameters, &state);
    //}

    // This is where we would call is_unsolvable() if it worked.

    // All moves that start in a room.
    for start_room in 0 .. 4 {
      if state.rooms[start_room].len() > 0 {
        let start_room_occupancy = state.rooms[start_room].len();
        let amphipod = state.rooms[start_room][start_room_occupancy-1];
        let distance = 1 + parameters.room_size - start_room_occupancy;

        // Don't consider moves that begin at the most recent destination.
        match state.last_destination {
          Some(Place::Room(last_room)) => {
            if start_room == last_room {
              continue;
            }
          }
          _ => { }
        }

        // It only makes sense to move an amphipod out of their destination
        // room if there are amphipods that don't want to be there below
        // them.
        if amphipod_destination_room(&amphipod) == start_room {
          let mut should_skip = true;
          for i in 0 .. start_room_occupancy {
            let occupant = state.rooms[start_room][i];
            if occupant != amphipod {
              should_skip = false;
              break;
            }
          }
          if should_skip {
            continue;
          }
        }

        {
          // All *leftward* moves that start in a room.
          let mut hallway = hallway_left_of_room(start_room);
          let mut distance = distance + 1;

          loop {
            if state.hallway[hallway].is_some() {
              break;
            }

            // At each step along the hallway, enqueue a search state that
            // has the amphipod stopped at that location.
            enqueue_move_to_hallway(&state, &amphipod, Place::Room(start_room),
                hallway, distance, &mut exploration_queue, &visited_states);

            match adjacent_room_left_of_hallway(hallway) {
              None => { },
              Some(end_room) => {
                enqueue_move_to_room(parameters, &state, &amphipod,
                  Place::Room(start_room), end_room, distance,
                  &mut exploration_queue, &visited_states);
              }
            }

            match hallway_left_of_hallway(hallway) {
              None => { break; },
              Some(new_hallway) => {
                distance += hallway - new_hallway;
                hallway = new_hallway;
              }
            }
          }
        }

        {
          // All *rightward* moves that start in a room.
          let mut hallway = hallway_right_of_room(start_room);
          let mut distance = distance + 1;

          loop {
            if state.hallway[hallway].is_some() {
              break;
            }

            // At each step along the hallway, enqueue a search state that
            // has the amphipod stopped at that location.
            enqueue_move_to_hallway(&state, &amphipod, Place::Room(start_room),
                hallway, distance, &mut exploration_queue, &visited_states);

            match adjacent_room_right_of_hallway(hallway) {
              None => { },
              Some(end_room) => {
                enqueue_move_to_room(parameters, &state, &amphipod,
                  Place::Room(start_room), end_room, distance,
                  &mut exploration_queue, &visited_states);
              }
            }

            match hallway_right_of_hallway(hallway) {
              None => { break; },
              Some(new_hallway) => {
                distance += new_hallway - hallway;
                hallway = new_hallway;
              }
            }
          }
        }
      }
    }

    // All moves that start in a hallway.
    for start_hallway in 0 .. 11 {
      // Don't consider moves that begin at the most recent destination.
      match state.last_destination {
        Some(Place::Hallway(last_hallway)) => {
          if start_hallway == last_hallway {
            continue;
          }
        }
        _ => { }
      }

      match state.hallway[start_hallway] {
        None => { }
        Some(amphipod) => {
          let distance = 0;

          {
            // All *leftward* moves that start in a hallway.
            let mut hallway = start_hallway;
            let mut distance = distance;

            loop {
              match adjacent_room_left_of_hallway(hallway) {
                None => { },
                Some(end_room) => {
                  enqueue_move_to_room(parameters, &state, &amphipod,
                    Place::Hallway(start_hallway), end_room, distance,
                    &mut exploration_queue, &visited_states);
                }
              }

              match hallway_left_of_hallway(hallway) {
                None => { break; },
                Some(new_hallway) => {
                  if state.hallway[new_hallway].is_some() {
                    break;
                  }

                  distance += hallway - new_hallway;
                  hallway = new_hallway;
                }
              }
            }
          }

          {
            // All *rightward* moves that start in a hallway.
            let mut hallway = start_hallway;
            let mut distance = distance;

            loop {
              match adjacent_room_right_of_hallway(hallway) {
                None => { },
                Some(end_room) => {
                  enqueue_move_to_room(parameters, &state, &amphipod,
                    Place::Hallway(start_hallway), end_room, distance,
                    &mut exploration_queue, &visited_states);
                }
              }

              match hallway_right_of_hallway(hallway) {
                None => { break; },
                Some(new_hallway) => {
                  if state.hallway[new_hallway].is_some() {
                    break;
                  }

                  distance += new_hallway - hallway;
                  hallway = new_hallway;
                }
              }
            }
          }
        }
      }
    }
  }
}


fn enqueue_move_to_room(parameters: &Parameters, state: &State,
    amphipod: &Amphipod, start: Place, end_room: usize, distance: usize,
    exploration_queue: &mut BinaryHeap<State>,
    visited_states: &HashMap<StaticState,usize>)
{
  if room_is_viable_destination(parameters, state, amphipod, end_room) {
    let end_room_occupancy = state.rooms[end_room].len();
    let mut new_state = state.clone();

    match start {
      Place::Hallway(start_hallway) => {
        new_state.hallway[start_hallway] = None;
      }
      Place::Room(start_room) => {
        let _ = new_state.rooms[start_room].pop();
      }
    }

    new_state.rooms[end_room].push(*amphipod);
    let distance = distance + 1 + parameters.room_size - end_room_occupancy;
    new_state.expense_so_far += amphipod_expense(&amphipod, distance);
    new_state.last_destination = Some(Place::Room(end_room));

    enqueue_state(new_state, exploration_queue, visited_states);
  }
}


fn enqueue_move_to_hallway(state: &State, amphipod: &Amphipod, start: Place,
    end_hallway: usize, distance: usize,
    exploration_queue: &mut BinaryHeap<State>,
    visited_states: &HashMap<StaticState,usize>)
{
  let mut new_state = state.clone();
  match start {
    Place::Room(start_room) => {
      let _ = new_state.rooms[start_room].pop();
    }
    _ => { }
  }
  new_state.hallway[end_hallway] = Some(*amphipod);
  new_state.expense_so_far += amphipod_expense(&amphipod, distance);
  new_state.last_destination = Some(Place::Hallway(end_hallway));

  enqueue_state(new_state, exploration_queue, visited_states);
}


fn enqueue_state(state: State, exploration_queue: &mut BinaryHeap<State>,
    visited_states: &HashMap<StaticState,usize>)
{
  let should_enqueue = match visited_states.get(&StaticState {
    hallway: state.hallway.clone(),
    rooms: state.rooms.clone(),
  }) {
    None => { true }
    Some(already_tried_expense) => {
      state.expense_so_far < *already_tried_expense
    }
  };

  if should_enqueue {
    exploration_queue.push(state);
  }
}


fn room_is_viable_destination(parameters: &Parameters, state: &State,
    amphipod: &Amphipod, end_room: usize)
  -> bool
{
  let end_room_occupancy = state.rooms[end_room].len();

  if end_room_occupancy == parameters.room_size {
    return false;
  }

  if amphipod_destination_room(&amphipod) != end_room {
    return false;
  }

  for existing_occupant in &state.rooms[end_room] {
    if amphipod != existing_occupant {
      return false;
    }
  }

  true
}


fn is_solved(parameters: &Parameters, state: &State) -> bool {
  for hallway in 0 .. 11 {
    if state.hallway[hallway].is_some() {
      return false;
    }
  }

  for room in 0 .. 4 {
    let occupants = &state.rooms[room];
    if occupants.len() != parameters.room_size {
      return false;
    }
    for occupant in occupants {
      if amphipod_destination_room(occupant) != room {
        return false;
      }
    }
  }

  true
}


#[allow(dead_code)]
// This function does not work - it returns true in cases that are still
// solvable. It is retained as a salve to my ego.
fn is_unsolvable(state: &State) -> bool {
  // Consider pieces which are in rooms other than their destinations. There
  // are certain scenarios in which we can prove that these pieces can never
  // reach their destinations.
  for start_room in 0 .. 4 {
    for occupant in &state.rooms[start_room] {
      let end_room = amphipod_destination_room(occupant);

      // Break this into two cases, one in which we search left and an
      // almost-identical one in which we search right.
      if start_room > end_room {
        // First, check whether there is an available stash space to the
        // right. If there is, we can't prove anything useful, so keep
        // searching.
        let stash_hallway = hallway_right_of_room(start_room);
        match state.hallway[stash_hallway] {
          None => {
            continue;
          },
          Some(_) => { },
        }

        // Now that we know there is no stash space, check whether we and an
        // amphipod in the hallway will block each other.
        let mut hallway = hallway_left_of_room(start_room);
        loop {
          match state.hallway[hallway] {
            None => { },
            Some(blocker) => {
              if amphipod_destination_room(&blocker) == start_room {
                return true;
              }
            }
          }

          match adjacent_room_left_of_hallway(hallway) {
            None => { },
            Some(intermediate_room) => {
              if intermediate_room == end_room {
                break;
              }
            }
          }

          match hallway_left_of_hallway(hallway) {
            None => {
              break;
            },
            Some(new_hallway) => {
              hallway = new_hallway;
            }
          }
        }
      } else if start_room < end_room {
        // First, check whether there is an available stash space to the
        // left. If there is, we can't prove anything useful, so keep
        // searching.
        let stash_hallway = hallway_left_of_room(start_room);
        match state.hallway[stash_hallway] {
          None => {
            continue;
          },
          Some(_) => { },
        }

        // Now that we know there is no stash space, check whether we and an
        // amphipod in the hallway will block each other.
        let mut hallway = hallway_right_of_room(start_room);
        loop {
          match state.hallway[hallway] {
            None => { },
            Some(blocker) => {
              if amphipod_destination_room(&blocker) == start_room {
                return true;
              }
            }
          }

          match adjacent_room_right_of_hallway(hallway) {
            None => { }
            Some(intermediate_room) => {
              if intermediate_room == end_room {
                break;
              }
            }
          }

          match hallway_right_of_hallway(hallway) {
            None => {
              break;
            },
            Some(new_hallway) => {
              hallway = new_hallway;
            }
          }
        }
      }
    }
  }

  // Consider pieces which are in the hallway. There are certain cases in
  // which these pieces can never reach their destinations.
  for start_hallway in 0 .. 11 {
    match state.hallway[start_hallway] {
      None => { }
      Some(amphipod) => {
        let end_room = amphipod_destination_room(&amphipod);

        if is_room_left_of_hallway(end_room, start_hallway) {
          // This amphipod must move left to reach its destination.
          let mut hallway = start_hallway;

          loop {
            match adjacent_room_left_of_hallway(hallway) {
              None => { },
              Some(new_room) => {
                if new_room == end_room {
                  break;
                }
              }
            }

            match hallway_left_of_hallway(hallway) {
              None => {
                break;
              }
              Some(new_hallway) => {
                match state.hallway[new_hallway] {
                  None => { }
                  Some(blocker) => {
                    // If the blocker needs to go somewhere that's on the
                    // far side of the start point, the configuration is
                    // unsolvable.
                    let blocker_destination =
                      amphipod_destination_room(&blocker);
                    if is_room_right_of_hallway(
                        blocker_destination, start_hallway)
                    {
                      return true;
                    }
                  }
                }

                hallway = new_hallway;
              }
            }
          }
        } else {
          // This amphipod must move right to reach its destination.
          let mut hallway = start_hallway;

          loop {
            match adjacent_room_right_of_hallway(hallway) {
              None => { },
              Some(new_room) => {
                if new_room == end_room {
                  break;
                }
              }
            }

            match hallway_right_of_hallway(hallway) {
              None => {
                break;
              }
              Some(new_hallway) => {
                match state.hallway[new_hallway] {
                  None => { }
                  Some(blocker) => {
                    // If the blocker needs to go somewhere that's on the
                    // far side of the start point, the configuration is
                    // unsolvable.
                    let blocker_destination =
                      amphipod_destination_room(&blocker);
                    if is_room_left_of_hallway(
                        blocker_destination, start_hallway)
                    {
                      return true;
                    }
                  }
                }

                hallway = new_hallway;
              }
            }
          }
        }
      }
    }
  }

  false
}


fn amphipod_expense(amphipod: &Amphipod, distance: usize) -> usize {
  distance * match amphipod {
    Amphipod::A => 1,
    Amphipod::B => 10,
    Amphipod::C => 100,
    Amphipod::D => 1000,
  }
}


fn hallway_left_of_room(room_index: usize) -> usize {
  1 + room_index * 2
}

fn hallway_right_of_room(room_index: usize) -> usize {
  3 + room_index * 2
}

fn hallway_left_of_hallway(hallway_index: usize) -> Option<usize> {
  if hallway_index == 0 {
    None
  } else if hallway_index == 1 {
    Some(0)
  } else if hallway_index == 3 {
    Some(1)
  } else if hallway_index == 5 {
    Some(3)
  } else if hallway_index == 7 {
    Some(5)
  } else if hallway_index == 9 {
    Some(7)
  } else if hallway_index == 10 {
    Some(9)
  } else {
    panic!("Invalid hallway index {}", hallway_index);
  }
}

fn hallway_right_of_hallway(hallway_index: usize) -> Option<usize> {
  if hallway_index == 0 {
    Some(1)
  } else if hallway_index == 1 {
    Some(3)
  } else if hallway_index == 3 {
    Some(5)
  } else if hallway_index == 5 {
    Some(7)
  } else if hallway_index == 7 {
    Some(9)
  } else if hallway_index == 9 {
    Some(10)
  } else if hallway_index == 10 {
    None
  } else {
    panic!("Invalid hallway index {}", hallway_index);
  }
}

fn adjacent_room_right_of_hallway(hallway_index: usize) -> Option<usize> {
  if hallway_index == 1 {
    Some(0)
  } else if hallway_index == 3 {
    Some(1)
  } else if hallway_index == 5 {
    Some(2)
  } else if hallway_index == 7 {
    Some(3)
  } else {
    None
  }
}

fn adjacent_room_left_of_hallway(hallway_index: usize) -> Option<usize> {
  if hallway_index == 9 {
    Some(3)
  } else if hallway_index == 7 {
    Some(2)
  } else if hallway_index == 5 {
    Some(1)
  } else if hallway_index == 3 {
    Some(0)
  } else {
    None
  }
}

fn is_room_left_of_hallway(room_index: usize, hallway_index: usize) -> bool {
  hallway_right_of_room(room_index) <= hallway_index
}

fn is_room_right_of_hallway(room_index: usize, hallway_index: usize) -> bool {
  hallway_left_of_room(room_index) >= hallway_index
}


fn amphipod_destination_room(amphipod: &Amphipod) -> usize {
  match amphipod {
    Amphipod::A => 0,
    Amphipod::B => 1,
    Amphipod::C => 2,
    Amphipod::D => 3,
  }
}


#[allow(dead_code)]
fn debug_state(parameters: &Parameters, state: &State) {
  println!("#############");

  print!("#");
  for hallway in 0 .. 11 {
    match state.hallway[hallway] {
      None => { print!("."); }
      Some(amphipod) => { debug_amphipod(&amphipod); }
    }
  }
  println!("#");

  print!("###");
  for room in 0 .. 4 {
    if state.rooms[room].len() == parameters.room_size {
      debug_amphipod(&state.rooms[room][parameters.room_size - 1]);
    } else {
      print!(".");
    }
    print!("#");
  }
  println!("##");

  for i in 0 .. parameters.room_size - 1 {
    print!("  #");
    for room in 0 .. 4 {
      let index = parameters.room_size - 2 - i;
      if state.rooms[room].len() >= index + 1 {
        debug_amphipod(&state.rooms[room][index]);
      } else {
        print!(".");
      }
      print!("#");
    }
    println!("");
  }

  println!("  #########");

  println!("");
}


#[allow(dead_code)]
fn debug_amphipod(amphipod: &Amphipod) {
  match amphipod {
    Amphipod::A => { print!("A"); }
    Amphipod::B => { print!("B"); }
    Amphipod::C => { print!("C"); }
    Amphipod::D => { print!("D"); }
  }
}