Skip to content

Commit

Permalink
refactor: Use a dynamic window!
Browse files Browse the repository at this point in the history
  • Loading branch information
icyJoseph committed Dec 1, 2021
1 parent f5e5bce commit e101c4b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 32 deletions.
34 changes: 11 additions & 23 deletions 2021/day-1/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,39 +14,27 @@ fn solve(raw: String) -> () {
.map(|x| parse_num::<u32>(x))
.collect::<Vec<u32>>();

let part_one_deltas = rows[1..]
.iter()
.scan(rows[0], |state, curr| {
let diff = curr > state;
let compare = |state: &mut usize, curr: &u32| {
let result = *curr > rows[*state];
*state += 1;

*state = *curr;
Some(result)
};

Some(diff)
})
let part_one_deltas = rows[1..]
.iter()
.scan(0usize, compare)
.filter(|x| *x)
.count();

println!("Part one: {}", part_one_deltas); // 1226

let windows: Vec<u32> = rows[..rows.len() - 2]
let part_two_deltas = rows[3..]
.iter()
.scan(0usize, |state, curr| {
let window_sum = curr + rows[*state + 1..*state + 3].iter().sum::<u32>();
*state += 1;

Some(window_sum)
})
.collect();

let part_two_deltas = windows[1..]
.iter()
.scan(0usize, |state, curr| {
let index = *state;
*state += 1;
Some(*curr > windows[index])
})
.scan(0usize, compare)
.filter(|x| *x)
.count();

println!("Part two: {}", part_two_deltas); // 1252
}

Expand Down
11 changes: 2 additions & 9 deletions 2021/deno/day-1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,9 @@ console.log("Part One:", deltas);

const windowDeltas = data
.reduce((prev: boolean[], _, index, src) => {
if (index === 0) return prev;
if (src.length - index < 3) return prev;

const prevWindow = src.slice(index - 1, index + 2);
const nextWindow = src.slice(index, index + 3);

const prevSum = prevWindow.reduce(sum);
const nextSum = nextWindow.reduce(sum);
if (index < 3) return prev;

return [...prev, nextSum > prevSum];
return [...prev, src[index] > src[index - 3]];
}, [])
.filter(Boolean).length;

Expand Down

0 comments on commit e101c4b

Please sign in to comment.