-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_07.rs
64 lines (50 loc) · 1.29 KB
/
day_07.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
use common::{solution, Answer};
solution!("The Treachery of Whales", 7);
fn part_a(input: &str) -> Answer {
let data = parse_crabs(input);
let min = data.iter().min().unwrap();
let max = data.iter().max().unwrap();
let mut this_min = u32::MAX;
for i in *min..=*max {
let cost = move_crabs(&data, i);
if cost < this_min {
this_min = cost;
}
}
this_min.into()
}
fn part_b(input: &str) -> Answer {
let data = parse_crabs(input);
let min = data.iter().min().unwrap();
let max = data.iter().max().unwrap();
let mut this_min = u32::MAX;
for i in *min..=*max {
let cost = move_crabs_b(&data, i);
if cost < this_min {
this_min = cost;
}
}
this_min.into()
}
fn parse_crabs(inp: &str) -> Vec<u32> {
inp.lines()
.next()
.unwrap()
.split(',')
.map(|x| x.parse().unwrap())
.collect::<Vec<u32>>()
}
fn move_crabs(crabs: &[u32], to: u32) -> u32 {
let mut cost = 0;
for i in crabs {
cost += (*i as i32 - to as i32).abs();
}
cost as u32
}
fn move_crabs_b(crabs: &[u32], to: u32) -> u32 {
let mut cost = 0;
for crab in crabs {
cost += (0..=(*crab as i32 - to as i32).abs()).sum::<i32>();
}
cost as u32
}