2024-12-02 11:51:12
2024-12-02 11:51:12
2024-12-02 11:51:09
6175093
Advent of Code 2024, day 2, tasks 1 and 2.
And task 2:
I am noticing how rusty I am though. Too long without coding.
Sensitive content
Today's AoC was weird. I finished the first task fairly quickly, but got stuck on the second because I was trying an approach that should work in principle, but is fiddly to get right.
In the end I extracted the verification code out into a function and just progressively removed an element until it verifies, or the loop ends. I'll post both tasks here:
Task 1:
use std::fs::read_to_string;
fn main() {
let mut numbers: Vec<Vec<i32>> = Vec::new();
let f = read_to_string("input.txt").unwrap();
let f = f.split('\n');
for i in f {
if i.is_empty() {
break;
}
let v: Vec<i32> = i
.split_whitespace()
.map(|n| n.parse::<i32>().unwrap())
.collect();
numbers.push(v);
}
let mut safe = 0;
'count: for i in numbers {
let mut v = Vec::new();
for j in 0..(i.len() - 1) {
let diff = i[j] - i[j + 1];
if (diff.abs() > 3) | (diff == 0) {
continue 'count;
}
v.push(diff);
}
if v.iter().all(|n| *n > 0) | v.iter().all(|n| *n < 0) {
safe += 1;
}
}
println!("{}", safe);
}
And task 2:
use std::fs::read_to_string;
fn verify(v: &[i32]) -> bool {
let mut d = Vec::new();
for i in 0..(v.len() - 1) {
let diff = v[i] - v[i + 1];
if (diff == 0) | (diff.abs() > 3) {
return false;
}
d.push(diff);
}
d.iter().all(|n| n.signum() == d[0].signum())
}
fn main() {
let mut numbers: Vec<Vec<i32>> = Vec::new();
let f = read_to_string("input.txt").unwrap();
let f = f.split('\n');
for i in f {
if i.is_empty() {
break;
}
let v: Vec<i32> = i
.split_whitespace()
.map(|n| n.parse::<i32>().unwrap())
.collect();
numbers.push(v);
}
let mut safe = 0;
'numbers: for i in numbers {
if verify(&i) {
safe += 1;
continue;
}
for j in 0..i.len() {
let mut v = i.clone();
v.remove(j);
if verify(&v) {
safe += 1;
continue 'numbers;
}
}
}
println!("{}", safe);
}
I am noticing how rusty I am though. Too long without coding.