summary refs log tree commit diff
path: root/23/src/main.rs
blob: 797afa7a7a5505afb5a655eb446cd852a9fc6f82 (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
use advent_lib::prelude::*;

use std::convert::TryFrom;
use std::rc::Rc;
use std::cell::RefCell;


mod cup_structure {
  use std::rc::Rc;
  use std::cell::RefCell;

  pub struct Cup {
    label: usize,
    numeric_prev: Option<Rc<RefCell<Cup>>>,
    prev: Option<Rc<RefCell<Cup>>>,
    next: Option<Rc<RefCell<Cup>>>,
  }

  impl Cup {
    pub fn new(count: usize) -> Vec<Rc<RefCell<Cup>>> {
      let mut all_cups: Vec<Rc<RefCell<Cup>>> = Vec::new();
      let mut prev: Option<Rc<RefCell<Cup>>> = None;

      for i in 1 .. count + 1 {
        let cup_rc = Rc::new(RefCell::new(Cup {
          label: i,
          numeric_prev: None,
          prev: None,
          next: None,
        }));

        match prev {
          Some(prev_rc) => {
            let mut cup = cup_rc.borrow_mut();
            cup.numeric_prev = Some(Rc::clone(&prev_rc));
            cup.prev = Some(Rc::clone(&prev_rc));

            let mut prev_cup = prev_rc.borrow_mut();
            prev_cup.next = Some(Rc::clone(&cup_rc));
          },
          None => { },
        }

        prev = Some(Rc::clone(&cup_rc));
        all_cups.push(cup_rc);
      }

      {
        let first_rc = &all_cups[0];
        let last_rc = &all_cups[all_cups.len()-1];
        let mut first_cup = first_rc.borrow_mut();
        let mut last_cup = last_rc.borrow_mut();
        first_cup.numeric_prev = Some(Rc::clone(last_rc));
        first_cup.prev = Some(Rc::clone(last_rc));
        last_cup.next = Some(Rc::clone(first_rc));
      }

      all_cups
    }

    #[allow(dead_code)]
    pub fn label(&self) -> usize {
      self.label
    }

    #[allow(dead_code)]
    pub fn numeric_prev(&self) -> Rc<RefCell<Cup>> {
      Rc::clone(self.numeric_prev.as_ref().unwrap())
    }

    #[allow(dead_code)]
    pub fn next(&self) -> Rc<RefCell<Cup>> {
      Rc::clone(self.next.as_ref().unwrap())
    }

    #[allow(dead_code)]
    pub fn prev(&self) -> Rc<RefCell<Cup>> {
      Rc::clone(self.prev.as_ref().unwrap())
    }

    #[allow(dead_code)]
    pub fn len(&self) -> usize {
      let mut result = 1;

      let mut next_rc = Rc::clone(self.next.as_ref().unwrap());
      loop {
        if next_rc.borrow().label == self.label {
          break;
        }
        let next_rc_tmp = Rc::clone(&next_rc.borrow().next.as_ref().unwrap());
        next_rc = next_rc_tmp;
        result += 1;
      }

      result
    }

    pub fn find(&self, to_find: usize) -> Option<Rc<RefCell<Cup>>> {
      let self_rc;
      {
        let next_cup = self.next.as_ref().unwrap().borrow();
        self_rc = Rc::clone(&next_cup.prev.as_ref().unwrap());
      }

      if self.label == to_find {
        Some(self_rc)
      } else {
        let mut point_rc = Rc::clone(self.next.as_ref().unwrap());
        loop {
          let point_label;
          {
            let point_cup = point_rc.borrow();
            point_label = point_cup.label;
          }
          if point_label == self.label {
            return None;
          }
          if point_label == to_find {
            return Some(point_rc);
          }
          {
            let next_point_rc = Rc::clone(point_rc.borrow().next.as_ref().unwrap());
            point_rc = next_point_rc;
          }
        }
      }
    }

    pub fn split_at(self_rc: Rc<RefCell<Cup>>, count: usize)
      -> (Rc<RefCell<Cup>>, Rc<RefCell<Cup>>)
    {
      let mut tail_rc = Rc::clone(self_rc.borrow().next.as_ref().unwrap());
      for _ in 1 .. count {
        let new_tail_rc = Rc::clone(tail_rc.borrow().next.as_ref().unwrap());
        tail_rc = new_tail_rc;
      }

      let head_last_rc = Rc::clone(tail_rc.borrow().prev.as_ref().unwrap());
      let tail_last_rc = Rc::clone(self_rc.borrow().prev.as_ref().unwrap());

      if Rc::ptr_eq(&tail_rc, &tail_last_rc) {
        let mut tail_cup = tail_rc.borrow_mut();
        tail_cup.prev = Some(Rc::clone(&tail_rc));
        tail_cup.next = Some(Rc::clone(&tail_rc));
      } else {
        let mut tail_cup = tail_rc.borrow_mut();
        let mut tail_last_cup = tail_last_rc.borrow_mut();
        tail_cup.prev = Some(Rc::clone(&tail_last_rc));
        tail_last_cup.next = Some(Rc::clone(&tail_rc));
      }

      if Rc::ptr_eq(&self_rc, &head_last_rc) {
        let mut self_cup = self_rc.borrow_mut();
        self_cup.next = Some(Rc::clone(&self_rc));
        self_cup.prev = Some(Rc::clone(&head_last_rc));
      } else {
        let mut self_cup = self_rc.borrow_mut();
        let mut head_last_cup = head_last_rc.borrow_mut();
        head_last_cup.next = Some(Rc::clone(&self_rc));
        self_cup.prev = Some(Rc::clone(&head_last_rc));
      }

      (Rc::clone(&self_rc), Rc::clone(&tail_rc))
    }

    pub fn splice_after(self_rc: Rc<RefCell<Cup>>,
                        to_insert_rc: Rc<RefCell<Cup>>)
    {
      let mut self_cup = self_rc.borrow_mut();

      let old_next_rc = Rc::clone(self_cup.next.as_ref().unwrap());

      let to_insert_last_rc =
          Rc::clone(to_insert_rc.borrow().prev.as_ref().unwrap());
      {
        let mut to_insert_last_cup = to_insert_last_rc.borrow_mut();
        to_insert_last_cup.next = Some(Rc::clone(&old_next_rc));
      }

      if Rc::ptr_eq(&old_next_rc, &self_rc) {
        self_cup.prev = Some(Rc::clone(&to_insert_last_rc));
      } else {
        let mut old_next_cup = old_next_rc.borrow_mut();
        old_next_cup.prev = Some(Rc::clone(&to_insert_last_rc));
      }

      let mut to_insert_cup = to_insert_rc.borrow_mut();
      to_insert_cup.prev = Some(Rc::clone(&self_rc));
      self_cup.next = Some(Rc::clone(&to_insert_rc));
    }

    pub fn splice_before(self_rc: Rc<RefCell<Cup>>, to_insert_rc: Rc<RefCell<Cup>>) {
      let prev_cup_rc = Rc::clone(self_rc.borrow().prev.as_ref().unwrap());
      Cup::splice_after(prev_cup_rc, to_insert_rc);
    }
  }
}  // mod cup_structure

use cup_structure::Cup;


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 initial_cups: Vec<usize> = Vec::new();
  for c in input[0].chars() {
    let label = usize::try_from(c.to_digit(10).unwrap()).unwrap();
    initial_cups.push(label);
  }

  {
    let max_cup = initial_cups.len();
    let cups_by_zero_based_label = Cup::new(max_cup);

    let mut label_iter = initial_cups.iter();
    let first_label: usize = *label_iter.next().unwrap();
    let first_cup_rc = &cups_by_zero_based_label[first_label-1];
    let (mut cups_rc, _) = Cup::split_at(Rc::clone(first_cup_rc), 1);
    for label in label_iter {
      let next_cup;
      {
        let next_cup_rc = &cups_by_zero_based_label[*label-1];
        let (next_cup_tmp, _) = Cup::split_at(Rc::clone(next_cup_rc), 1);
        next_cup = next_cup_tmp;
      }
      Cup::splice_before(Rc::clone(&cups_rc), next_cup);
    }

    for _ in 0 .. 100 {
      cups_rc = iterate_game(Rc::clone(&cups_rc));
    }

    let output1 = game_output1(Rc::clone(&cups_rc));
    println!("{}", output1);
  }

  {
    let max_cup = 1000000;
    let cups_by_zero_based_label = Cup::new(max_cup);
    let max_defined_cup = initial_cups.len();

    let mut label_iter = initial_cups.iter();
    let first_label: usize = *label_iter.next().unwrap();
    let first_cup_rc = &cups_by_zero_based_label[first_label-1];
    let (mut cups_rc, _) = Cup::split_at(Rc::clone(first_cup_rc), 1);
    for label in label_iter {
      let next_cup_rc = &cups_by_zero_based_label[*label-1];
      let (next_cup, _) = Cup::split_at(Rc::clone(next_cup_rc), 1);
      Cup::splice_before(Rc::clone(&cups_rc), next_cup);
    }
    Cup::splice_before(Rc::clone(&cups_rc),
        Rc::clone(&cups_by_zero_based_label[max_defined_cup]));

    for _ in 0 .. 10000000 {
      cups_rc = iterate_game(Rc::clone(&cups_rc));
    }

    let output = game_output2(Rc::clone(&cups_rc));
    println!("{}", output);
  }

  Ok(())
}


fn game_output1(cups: Rc<RefCell<Cup>>) -> String {
  let mut output = String::new();

  let mut cup = cups.borrow().find(1).unwrap();
  {
    let next_cup = cup.borrow().next();
    cup = next_cup;
  }
  loop {
    if cup.borrow().label() == 1 {
      break;
    }
    output.push_str(&format!("{}", cup.borrow().label()));
    let next_cup = cup.borrow().next();
    cup = next_cup;
  }

  output
}


fn game_output2(cups: Rc<RefCell<Cup>>) -> String {
  let mut result = 1;

  let mut cup = cups.borrow().find(1).unwrap();
  {
    let next_cup = cup.borrow().next();
    cup = next_cup;
  }
  result *= cup.borrow().label();
  {
    let next_cup = cup.borrow().next();
    cup = next_cup;
  }
  result *= cup.borrow().label();

  format!("{}", result)
}


fn iterate_game(cups: Rc<RefCell<Cup>>) -> Rc<RefCell<Cup>> {
  let current_cup = Rc::clone(&cups);
  let cups = cups.borrow().next();

  let (transferred_cups, _) = Cup::split_at(cups, 3);

  let mut destination_cup = current_cup.borrow().numeric_prev();

  loop {
    let destination_cup_label = destination_cup.borrow().label();
    if transferred_cups.borrow().find(destination_cup_label).is_none() {
      break;
    }
    let next_destination_cup =
        Rc::clone(&destination_cup.borrow().numeric_prev());
    destination_cup = next_destination_cup;
  }

  Cup::splice_after(destination_cup, transferred_cups);

  let next_current_cup = current_cup.borrow().next();
  next_current_cup
}