Skip to content

Commit 55f1c62

Browse files
author
mflinn-broad
committed
day 7
1 parent 7de4032 commit 55f1c62

File tree

4 files changed

+75
-1
lines changed

4 files changed

+75
-1
lines changed

src/days/day7.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
use crate::util;
2+
3+
pub fn run() {
4+
let raw_input = util::read_input("inputs/day7.txt").unwrap();
5+
let input = process(&raw_input);
6+
7+
println!("Part 1: {}", part_1(&mut input.clone()));
8+
println!("Part 2: {}", part_2(&input));
9+
}
10+
11+
fn process(input: &str) -> Vec<usize> {
12+
input
13+
.trim()
14+
.split(',')
15+
.map(|pos| pos.parse().unwrap())
16+
.collect()
17+
}
18+
19+
fn part_1(input: &mut Vec<usize>) -> usize {
20+
input.sort();
21+
22+
let median = input[(input.len() / 2) + (input.len() % 2)];
23+
cost_at(median, &input)
24+
}
25+
26+
fn part_2(input: &Vec<usize>) -> usize {
27+
let mean: usize = input.iter().sum::<usize>() / input.len();
28+
(mean - 5..mean + 5)
29+
.map(|pos| cost_at_v2(pos, input))
30+
.min()
31+
.unwrap()
32+
}
33+
34+
fn cost_at(pos: usize, crabs: &Vec<usize>) -> usize {
35+
crabs.iter().map(|crab_pos| pos.abs_diff(*crab_pos)).sum()
36+
}
37+
38+
fn cost_at_v2(pos: usize, crabs: &Vec<usize>) -> usize {
39+
crabs
40+
.iter()
41+
.map(|crab_pos| {
42+
let abs_dist = pos.abs_diff(*crab_pos);
43+
abs_dist * (1 + abs_dist) / 2
44+
})
45+
.sum()
46+
}
47+
48+
#[cfg(test)]
49+
mod tests {
50+
use super::*;
51+
extern crate test;
52+
use test::Bencher;
53+
54+
#[bench]
55+
fn bench_part_1(b: &mut Bencher) {
56+
let raw_input = util::read_input("inputs/day7.txt").unwrap();
57+
b.iter(|| {
58+
let mut input = process(&raw_input);
59+
part_1(&mut input);
60+
});
61+
}
62+
63+
#[bench]
64+
fn bench_part_2(b: &mut Bencher) {
65+
let raw_input = util::read_input("inputs/day7.txt").unwrap();
66+
b.iter(|| {
67+
let input = process(&raw_input);
68+
part_2(&input);
69+
});
70+
}
71+
}

src/days/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ pub mod day3;
44
pub mod day4;
55
pub mod day5;
66
pub mod day6;
7+
pub mod day7;

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#![feature(drain_filter, test)]
1+
#![feature(drain_filter, test, int_abs_diff)]
22

33
pub mod days;
44
mod util;

src/main.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,6 @@ fn main() {
1313
day5::run();
1414
println!("Day 6 --------");
1515
day6::run();
16+
println!("Day 7 --------");
17+
day7::run();
1618
}

0 commit comments

Comments
 (0)