-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
75 lines (70 loc) · 2.34 KB
/
main.rs
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
#![feature(linked_list_remove)]
// Problem: https://adventofcode.com/2022/day/20
use std::collections::LinkedList;
fn part1(input: &str) -> i32 {
let input: Vec<_> = input
.trim()
.lines()
.map(|line| line.parse::<i32>().unwrap())
.collect();
let len = input.len() as i32;
let mut cur: LinkedList<(usize, i32)> = input.into_iter().enumerate().collect();
for i in 0..len {
let idx = cur.iter().position(|&(idx, _)| idx == i as usize).unwrap() as i32;
let (mv_idx, mv_val) = cur.remove(idx as usize);
let target = (idx + mv_val).rem_euclid(len - 1);
let mut tail = cur.split_off(target as usize);
cur.push_back((mv_idx, mv_val));
cur.append(&mut tail);
}
let zero_idx = cur.iter().position(|(_, v)| *v == 0).unwrap();
vec![1000, 2000, 3000]
.iter()
.map(|p| {
let idx = (p + zero_idx) as i32 % len;
let (_, val) = cur.iter().nth(idx as usize).unwrap();
val
})
.sum::<i32>()
}
#[test]
fn test_part1() {
assert_eq!(part1(include_str!("test.txt")), 3);
}
fn part2(input: &str) -> i64 {
let key: i64 = 811589153;
let input: Vec<_> = input
.trim()
.lines()
.map(|line| line.parse::<i64>().unwrap() * key)
.collect();
let len = input.len() as i64;
let mut cur: LinkedList<(usize, i64)> = input.into_iter().enumerate().collect();
for _ in 0..10 {
for i in 0..len {
let idx = cur.iter().position(|&(idx, _)| idx == i as usize).unwrap() as i64;
let (mv_idx, mv_val) = cur.remove(idx as usize);
let target = (idx + mv_val).rem_euclid(len - 1);
let mut tail = cur.split_off(target as usize);
cur.push_back((mv_idx, mv_val));
cur.append(&mut tail);
}
}
let zero_idx = cur.iter().position(|(_, v)| *v == 0).unwrap();
vec![1000, 2000, 3000]
.iter()
.map(|p| {
let idx = (p + zero_idx) as i64 % len;
let (_, val) = cur.iter().nth(idx as usize).unwrap();
val
})
.sum::<i64>()
}
#[test]
fn test_part2() {
assert_eq!(part2(include_str!("test.txt")), 1623178306);
}
fn main() {
println!("Part 1: {:?}", part1(include_str!("input.txt")));
println!("Part 2: {:?}", part2(include_str!("input.txt")));
}