add day 1 and 2

This commit is contained in:
timeshifter
2026-06-26 22:49:45 +02:00
parent 3cb098048d
commit 1d54ac6752
10 changed files with 304 additions and 0 deletions
+137
View File
@@ -0,0 +1,137 @@
use std::collections::HashSet;
fn main() {
let data: Vec<_> =
Instruction::parse(std::fs::read_to_string("input.txt").unwrap().trim()).collect();
part1(&data);
part2(&data);
}
fn part2(data: &[Instruction]) {
let mut visited = HashSet::new();
let mut direction = Direction::North;
let mut x: i32 = 0;
let mut y: i32 = 0;
'outer: for i in data {
direction = i.change(direction);
match direction {
Direction::North => {
for _ in 0..i.value() {
y += 1;
if visited.contains(&(x, y)) {
break 'outer;
}
visited.insert((x, y));
}
}
Direction::East => {
for _ in 0..i.value() {
x += 1;
if visited.contains(&(x, y)) {
break 'outer;
}
visited.insert((x, y));
}
}
Direction::South => {
for _ in 0..i.value() {
y -= 1;
if visited.contains(&(x, y)) {
break 'outer;
}
visited.insert((x, y));
}
}
Direction::West => {
for _ in 0..i.value() {
x -= 1;
if visited.contains(&(x, y)) {
break 'outer;
}
visited.insert((x, y));
}
}
}
}
println!("{}", x.abs() + y.abs());
}
fn part1(data: &[Instruction]) {
let mut direction = Direction::North;
let mut x = 0;
let mut y = 0;
for i in data {
direction = i.change(direction);
match direction {
Direction::North => y += i.value() as i32,
Direction::East => x += i.value() as i32,
Direction::South => y -= i.value() as i32,
Direction::West => x -= i.value() as i32,
}
}
println!("{}", x.abs() + y.abs());
}
#[derive(Debug, PartialEq)]
enum Instruction {
L(usize),
R(usize),
}
#[derive(Debug)]
enum Direction {
North,
East,
South,
West,
}
impl Instruction {
fn change(&self, d: Direction) -> Direction {
if let Instruction::R(_) = self {
match d {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
}
} else {
match d {
Direction::North => Direction::West,
Direction::East => Direction::North,
Direction::South => Direction::East,
Direction::West => Direction::South,
}
}
}
fn value(&self) -> usize {
match self {
Instruction::L(val) => *val,
Instruction::R(val) => *val,
}
}
}
impl Instruction {
fn parse(s: &str) -> impl Iterator<Item = Self> {
let mut result = vec![];
for item in s.split(", ") {
let amount = item.chars().skip(1).collect::<String>().parse().unwrap();
let this = if item.contains('L') {
Instruction::L(amount)
} else {
Instruction::R(amount)
};
result.push(this);
}
result.into_iter()
}
}