Improve 2025 day 1 in rust

This commit is contained in:
SebastianStork 2025-12-01 16:16:28 +01:00
parent e2af8dddbe
commit 99554bc83b
Signed by: SebastianStork
SSH key fingerprint: SHA256:iEM011ogNMG1q8+U500adGu/9rpPuZ2KnFtbdLeqTiI

View file

@ -1,5 +1,8 @@
use std::fs::{self}; use std::fs::{self};
const STARTING_POSITION: i32 = 50;
const DIAL_RANGE: i32 = 100;
fn main() { fn main() {
let rotations = read_rotations(); let rotations = read_rotations();
@ -8,34 +11,26 @@ fn main() {
} }
fn read_rotations() -> Vec<i32> { fn read_rotations() -> Vec<i32> {
let contents = fs::read_to_string("../../inputs/01.txt").unwrap(); fs::read_to_string("../../inputs/01.txt")
let lines = contents.lines(); .unwrap()
.lines()
let mut rotations = vec![]; .map(|line| {
let distance = line[1..].parse::<i32>().unwrap();
for line in lines { if line.starts_with('L') {
let (direction, distance) = line.split_at(1); -distance
} else {
let distance = distance.parse::<i32>().unwrap(); distance
}
let rotation = match direction { })
"L" => -distance, .collect()
"R" => distance,
_ => panic!(),
};
rotations.push(rotation);
}
rotations
} }
fn count_zero_positions(rotations: &Vec<i32>) -> i32 { fn count_zero_positions(rotations: &[i32]) -> i32 {
let mut counter = 0; let mut counter = 0;
let mut position = 50; let mut position = STARTING_POSITION;
for rotation in rotations { for rotation in rotations {
position = (position + rotation).rem_euclid(100); position = (position + rotation).rem_euclid(DIAL_RANGE);
if position == 0 { if position == 0 {
counter += 1; counter += 1;
@ -45,14 +40,14 @@ fn count_zero_positions(rotations: &Vec<i32>) -> i32 {
counter counter
} }
fn count_zero_clicks(rotations: &Vec<i32>) -> i32 { fn count_zero_clicks(rotations: &[i32]) -> i32 {
let mut counter = 0; let mut counter = 0;
let mut position = 50; let mut position = STARTING_POSITION;
for rotation in rotations { for rotation in rotations {
position += rotation; position += rotation;
counter += (position / 100).abs(); counter += (position / DIAL_RANGE).abs();
if position < 0 && position != *rotation { if position < 0 && position != *rotation {
counter += 1; counter += 1;
} }
@ -60,7 +55,7 @@ fn count_zero_clicks(rotations: &Vec<i32>) -> i32 {
counter += 1; counter += 1;
} }
position = position.rem_euclid(100); position = position.rem_euclid(DIAL_RANGE);
} }
counter counter