Skip to content
Snippets Groups Projects
Commit 2c300cea authored by Falk Rehse's avatar Falk Rehse
Browse files

Day 10-1

parent 1e11f5a3
Branches
No related tags found
No related merge requests found
pub enum Command {
NoOp { cycles: u32 },
AddX { cycles: u32, value: i32 },
}
impl Command {
pub fn from_str(input: &str) -> Command {
match input.split(' ').next().expect("Expected command!") {
"noop" => Self::NoOp { cycles: 1 },
"addx" => Self::AddX {
cycles: 2,
value: input
.split(' ')
.nth(1)
.expect("Expected value!")
.parse()
.expect("Expected value to be a number!"),
},
_ => panic!("Unexpected command!"),
}
}
}
mod command;
use command::Command;
pub fn solve_from_str(input: &str) -> i32 {
let commands = input
.split('\n')
.map(|command| Command::from_str(command))
.collect();
solve(&commands)
}
pub fn solve(commands: &Vec<Command>) -> i32 {
let mut cycle = 1;
let mut x = 1;
let mut signal_strengths = Vec::new();
for command in commands {
match command {
Command::NoOp { cycles } => {
increment_cycle(&mut cycle, &mut signal_strengths, cycles, &x);
},
Command::AddX { cycles, value } => {
increment_cycle(&mut cycle, &mut signal_strengths, cycles, &x);
x += value;
},
}
}
signal_strengths.iter().sum()
}
fn increment_cycle(cycle: &mut u32, signal_strengths: &mut Vec<i32>, cycles: &u32, x: &i32) {
for _ in 0..*cycles {
if [20, 60, 100, 140, 180, 220].contains(cycle) {
signal_strengths.push(*x * *cycle as i32);
}
*cycle += 1;
}
}
......@@ -14,13 +14,14 @@ mod day_8_1;
mod day_8_2;
mod day_9_1;
mod day_9_2;
mod day_10_1;
use std::fs;
fn main() {
let input = fs::read_to_string("input").expect("Could not read input!");
let solution = day_9_2::solve_from_str(input.as_str());
let solution = day_10_1::solve_from_str(input.as_str());
println!("Solution: {}", solution);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment