Last active
December 13, 2021 08:19
-
-
Save GeeWee/69fe8059323e9f9e5b0dbf48168d2c64 to your computer and use it in GitHub Desktop.
Advent of code day 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Advent of code day 1 --> | |
pub fn calculate_part_1(input: &str) -> i32 { | |
let mut lines = input.lines(); | |
let first: i32 = lines.next().unwrap().parse().unwrap(); | |
let mut larger = 0; | |
let mut last_line = first; | |
for line in lines { | |
let line = line.parse::<i32>().unwrap(); | |
if last_line < line { | |
larger += 1; | |
} | |
last_line = line; | |
} | |
larger | |
} | |
pub fn calculate_part_2(input: &str) -> i32 { | |
let mut lines: Lines = input.lines(); | |
let mut larger = 0; | |
// Build two iterators with differing offsets | |
let offset_one = lines.clone().skip(1); | |
let offset_two = lines.clone().skip(2); | |
// Create one iterator that gives us three results at once. Could've used itertools here. | |
let mut triplet_iterator = lines.zip(offset_one).zip(offset_two); | |
let triplet = triplet_iterator.next().unwrap(); | |
// Generate initial value | |
let (first, second, third): (i32, i32, i32) = (triplet.0.0.parse().unwrap(), triplet.0.1.parse().unwrap(), triplet.1.parse().unwrap()); | |
let mut last_triplet_total = first + second + third; | |
// For each triplet, calculate the total and see if larger | |
for triplet in triplet_iterator { | |
let (first, second, third): (i32, i32, i32) = (triplet.0.0.parse().unwrap(), triplet.0.1.parse().unwrap(), triplet.1.parse().unwrap()); | |
println!("({}, {}, {})", first, second, third); | |
let total = first + second + third; | |
if last_triplet_total < total { | |
larger += 1; | |
} | |
last_triplet_total = total; | |
} | |
larger | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment