Skip to content

Instantly share code, notes, and snippets.

@danielronnkvist
Created December 9, 2020 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielronnkvist/c14d2a723011e45f18687bb98d853daf to your computer and use it in GitHub Desktop.
Save danielronnkvist/c14d2a723011e45f18687bb98d853daf to your computer and use it in GitHub Desktop.
Advent of code day 9
use std::collections::VecDeque;
use std::fs::File;
use std::io::{self, BufRead};
const PREAMBLE_LENGTH: usize = 25;
fn has_sum_makers(sum: u64, preamble: Vec<u64>) -> bool {
assert_eq!(preamble.len(), PREAMBLE_LENGTH);
for a in &preamble {
for b in &preamble {
if a + b == sum {
return true;
}
}
}
false
}
fn find_false_property(numbers: &Vec<u64>) -> u64 {
for x in PREAMBLE_LENGTH..numbers.len() {
let val = *numbers.get(x).unwrap();
let preamble: Vec<_> = numbers
.to_vec()
.splice(x - PREAMBLE_LENGTH..x, vec![])
.collect();
if !has_sum_makers(val, preamble) {
return val;
}
}
0
}
fn main() {
let file = File::open("input.txt").unwrap();
let lines: Vec<u64> = io::BufReader::new(file)
.lines()
.map(|line| line.unwrap().parse::<u64>().unwrap())
.collect();
let false_property = find_false_property(&lines);
println!("First: {}", false_property);
let mut acc = VecDeque::new();
for number in lines {
acc.push_back(number);
while acc.iter().sum::<u64>() > false_property {
acc.pop_front();
}
let sum = acc.iter().sum::<u64>();
if sum == false_property {
let small = acc.iter().min().unwrap();
let max = acc.iter().max().unwrap();
println!("Second: {}", small + max);
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment