this post was submitted on 02 Dec 2024
44 points (97.8% liked)

Advent Of Code

981 readers
36 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

Day 2: Red-Nosed Reports

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://blocks.programming.dev/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 5 points 3 weeks ago (2 children)

Rust

The function is_sorted_by on Iterators turned out helpful for compactly finding if a report is safe. In part 2 I simply tried the same with each element removed, since all reports are very short.

fn parse(input: String) -> Vec<Vec<i32>> {
    input.lines()
        .map(|l| l.split_whitespace().map(|w| w.parse().unwrap()).collect())
        .collect()
}

fn is_safe(report: impl DoubleEndedIterator<Item=i32> + Clone) -> bool {
    let safety = |a: &i32, b: &i32| (1..=3).contains(&(b - a));
    report.clone().is_sorted_by(safety) || report.rev().is_sorted_by(safety)
}

fn part1(input: String) {
    let reports = parse(input);
    let safe = reports.iter().filter(|r| is_safe(r.iter().copied())).count();
    println!("{safe}");
}

fn is_safe2(report: &[i32]) -> bool {
    (0..report.len()).any(|i| {  // Try with each element removed
        is_safe(report.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, n)| *n))
    })
}

fn part2(input: String) {
    let reports = parse(input);
    let safe = reports.iter().filter(|r| is_safe2(r)).count();
    println!("{safe}");
}

util::aoc_main!();
[โ€“] [email protected] 2 points 3 weeks ago

The is_sorted_by is a really nice approach. I originally tried using that function thinking that |a, b| a > b or |a, b| a < b would cut it but it didn't end up working. I never thought to handle the check for the step being between 1 and 3 in the callback closure for that though.

[โ€“] [email protected] 2 points 3 weeks ago

is_sorted_by is new to me, could be very useful.