Day 9 complete

This commit is contained in:
Cassandra de la Cruz-Munoz 2023-12-09 14:07:42 +01:00
parent 7817b74d35
commit 1f225db08d
2 changed files with 75 additions and 0 deletions

37
src/09part1.rs Normal file
View File

@ -0,0 +1,37 @@
use std::fs;
fn main() {
let file_path = "input/09input.txt";
let contents = fs::read_to_string(file_path).expect("should read file");
let lines = contents.lines();
let mut total = 0;
for line in lines {
let split_line = line.split_whitespace();
let sub_seq: Vec<i128> = split_line.map(|item| item.parse::<i128>().ok().unwrap()).collect();
let mut seq = vec![sub_seq];
let mut found_zeros = false;
while !found_zeros {
found_zeros = true;
let curr_seq = seq.last().unwrap();
let mut new_seq: Vec<i128> = Vec::new();
for i in 0..curr_seq.len()-1 {
let diff = curr_seq[i+1] - curr_seq[i];
new_seq.push(diff);
found_zeros = found_zeros && diff == 0;
}
seq.push(new_seq);
}
seq.reverse();
for i in 0..seq.len() {
if i == 0 {
seq[i].push(0);
} else {
let a = seq[i].last().unwrap().to_owned();
let b = seq[i-1].last().unwrap().to_owned();
seq[i].push(a + b);
}
}
total += seq.last().unwrap().last().unwrap();
}
println!("{}", total);
}

38
src/09part2.rs Normal file
View File

@ -0,0 +1,38 @@
use std::fs;
fn main() {
let file_path = "input/09input.txt";
let contents = fs::read_to_string(file_path).expect("should read file");
let lines = contents.lines();
let mut total = 0;
for line in lines {
let split_line = line.split_whitespace();
let mut sub_seq: Vec<i128> = split_line.map(|item| item.parse::<i128>().ok().unwrap()).collect();
sub_seq.reverse();
let mut seq = vec![sub_seq];
let mut found_zeros = false;
while !found_zeros {
found_zeros = true;
let curr_seq = seq.last().unwrap();
let mut new_seq: Vec<i128> = Vec::new();
for i in 0..curr_seq.len()-1 {
let diff = curr_seq[i+1] - curr_seq[i];
new_seq.push(diff);
found_zeros = found_zeros && diff == 0;
}
seq.push(new_seq);
}
seq.reverse();
for i in 0..seq.len() {
if i == 0 {
seq[i].push(0);
} else {
let a = seq[i].last().unwrap().to_owned();
let b = seq[i-1].last().unwrap().to_owned();
seq[i].push(a + b);
}
}
total += seq.last().unwrap().last().unwrap();
}
println!("{}", total);
}