Add day2
This commit is contained in:
61
2024/day2/src/main.rs
Normal file
61
2024/day2/src/main.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
use std::{collections::HashSet, fs};
|
||||
|
||||
fn main() {
|
||||
let file = fs::read_to_string("./input.txt").unwrap();
|
||||
let mut rows = Vec::new();
|
||||
|
||||
for line in file.lines() {
|
||||
let vals = line
|
||||
.split_whitespace()
|
||||
.map(|x| x.parse::<i32>().unwrap())
|
||||
.collect::<Vec<i32>>();
|
||||
|
||||
rows.push(vals);
|
||||
}
|
||||
|
||||
println!("Solution 1: {}", puzzle1(rows.clone()));
|
||||
println!("Solution 2: {}", puzzle2(rows));
|
||||
}
|
||||
|
||||
fn puzzle1(rows: Vec<Vec<i32>>) -> i32 {
|
||||
let mut counter = 0;
|
||||
for r in rows {
|
||||
if is_safe(&r) {
|
||||
counter += 1;
|
||||
}
|
||||
}
|
||||
counter
|
||||
}
|
||||
|
||||
fn puzzle2(rows: Vec<Vec<i32>>) -> i32 {
|
||||
let mut counter = 0;
|
||||
for r in rows {
|
||||
if is_safe(&r) {
|
||||
counter += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
for i in 0..r.len() {
|
||||
let mut modrow = r.clone();
|
||||
modrow.remove(i);
|
||||
if is_safe(&modrow) {
|
||||
counter += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
counter
|
||||
}
|
||||
|
||||
fn is_safe(row: &[i32]) -> bool {
|
||||
let mut safeslopes: HashSet<i32> = HashSet::from_iter(vec![1, 2, 3]);
|
||||
let mut safenegslopes: HashSet<i32> = HashSet::from_iter(vec![-1, -2, -3]);
|
||||
|
||||
for i in 1..row.len() {
|
||||
let diff = row[i] - row[i - 1];
|
||||
safeslopes.insert(diff);
|
||||
safenegslopes.insert(diff);
|
||||
}
|
||||
|
||||
safeslopes.len() == 3 || safenegslopes.len() == 3
|
||||
}
|
Reference in New Issue
Block a user