1
0

optimized day 10 part 2 by eliminating padded noops and repeating the noop block once in addx block

This commit is contained in:
Ishan Jain 2022-12-10 23:15:15 +05:30
parent 7fa967e4d3
commit 7b58b9d577
Signed by: ishan
GPG Key ID: 0506DB2A1CC75C27

View File

@ -8,7 +8,6 @@ const INPUTS: [&[u8]; 2] = [
#[derive(Debug)] #[derive(Debug)]
enum Ins { enum Ins {
Null,
Noop, Noop,
Addx(i32), Addx(i32),
} }
@ -17,8 +16,8 @@ fn parse(input: &[u8]) -> Vec<Ins> {
input input
.split(|&c| c == b'\n') .split(|&c| c == b'\n')
.filter(|c| !c.is_empty()) .filter(|c| !c.is_empty())
.flat_map(|line| match &line[0..4] { .map(|line| match &line[0..4] {
[b'n', b'o', b'o', b'p'] => [Ins::Noop, Ins::Null], [b'n', b'o', b'o', b'p'] => Ins::Noop,
[b'a', b'd', b'd', b'x'] => { [b'a', b'd', b'd', b'x'] => {
let is_neg = line[5] == b'-'; let is_neg = line[5] == b'-';
let b: i32 = line[5..] let b: i32 = line[5..]
@ -26,7 +25,7 @@ fn parse(input: &[u8]) -> Vec<Ins> {
.filter(|&&c| (b'0'..=b'9').contains(&c)) .filter(|&&c| (b'0'..=b'9').contains(&c))
.fold(0, |a, &x| (a * 10) + (x - b'0') as i32); .fold(0, |a, &x| (a * 10) + (x - b'0') as i32);
[Ins::Noop, Ins::Addx(if is_neg { -b } else { b })] Ins::Addx(if is_neg { -b } else { b })
} }
_ => unreachable!(), _ => unreachable!(),
}) })
@ -51,26 +50,53 @@ fn solution(input: Vec<Ins>) -> String {
let mut i = 0; let mut i = 0;
for ip in input.into_iter() { for ip in input.into_iter() {
if let Ins::Null = ip { match ip {
continue; Ins::Noop => {
} if sprite & ((1 << 63) >> i) > 0 {
line |= (1 << 63) >> i;
}
if sprite & ((1 << 63) >> i) > 0 { cycle += 1;
line |= (1 << 63) >> i; i += 1;
}
if let Ins::Addx(v) = ip { if cycle % 40 == 0 {
register += v; answer.push(line);
line = 0;
i = 0;
}
}
Ins::Addx(v) => {
// Noop
if sprite & ((1 << 63) >> i) > 0 {
line |= (1 << 63) >> i;
}
sprite = (0b111 << 61) >> (register - 1); cycle += 1;
} i += 1;
cycle += 1;
i += 1;
if cycle % 40 == 0 { if cycle % 40 == 0 {
answer.push(line); answer.push(line);
line = 0; line = 0;
i = 0; i = 0;
}
// Add
if sprite & ((1 << 63) >> i) > 0 {
line |= (1 << 63) >> i;
}
register += v;
sprite = (0b111 << 61) >> (register - 1);
cycle += 1;
i += 1;
if cycle % 40 == 0 {
answer.push(line);
line = 0;
i = 0;
}
}
} }
} }