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

Advent Of Code

982 readers
90 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

(page 2) 7 comments
sorted by: hot top controversial new old
[–] [email protected] 1 points 2 weeks ago

Uiua

Took me a bit longer to get this one but still quite simple overall.
Spent quite some time on getting to know the try and assert operators better.

Run with example input here

# Get the indices matching the ascending/
# descending criteria
CheckAsc ← β‰‘Β°β–‘βš(⍣(⊸⍀.≍⍆.)⍣(⊸⍀.β‰β‡Œβ†.)0)
# Get the indices matching the distance criteria
CheckDist ← β‰‘Β°β–‘βš(⍣(⊸⍀.β‰ 1∈:0)0Γ—βŠ“β‰₯≀1,3⌡⧈-)
Split     ← βŠ™(β–½β‰ 1)β–½,,

PartOne ← (
  &rs ∞ &fo "input-2.txt"
  ⊜(β–‘βŠœβ‹•β‰ @ .)β‰ @\n.
  CheckAsc.
  β–½
  CheckDist
  ⧻⊚
)

PartTwo ← (
  &rs ∞ &fo "input-2.txt"
  ⊜(β–‘βŠœβ‹•β‰ @ .)β‰ @\n.
  CheckAsc.
  Split
  CheckDist.
  Split
  βŠ™(βŠ‚)
  ⧻
  :
  ⍚(≑(β–½:°⊟)⍜€⊞⊟:β‰ 1⊞=.⇑⧻.)
  ≑(⧻⊚CheckDistβ–½CheckAsc.Β°β–‘)
  +β§»β—΄βŠš
)

&p "Day 2:"
&pf "Part 1: "
&p PartOne
&pf "Part 2: "
&p PartTwo
[–] [email protected] 1 points 3 weeks ago

R (R-Wasm)

input = file('input2024day2.txt',open='r')
lines = readLines(input)
library(stringr)
safe = 0
safe2 = 0
for (ln in lines){
  vals = as.numeric(unlist(str_split(ln,' ')))
  diffs = diff(vals)
  cond1 = min(diffs) > 0 || max(diffs) < 0
  cond2 = max(abs(diffs)) < 4
  if (cond1 && cond2){
    safe = safe + 1
  }
  else { #Problem Dampener
    dampen = FALSE
    for (omit in -1:-length(vals)){
      diffs = diff(vals[omit])
      cond1 = min(diffs) > 0 || max(diffs) < 0
      cond2 = max(abs(diffs)) < 4
      if (cond1 && cond2){
        dampen = TRUE
      }
    }
    if (dampen){
      safe2 = safe2 + 1}
  }
}
print (safe) #Part 1
print (safe + safe2) #Part 2
[–] [email protected] 1 points 3 weeks ago

Kotlin:

import kotlin.math.abs
import kotlin.math.sign

data class Report(val levels: List<Int>) {
    fun isSafe(withProblemDampener: Boolean): Boolean {
        var orderSign = 0.0f  // - 1 is descending; +1 is ascending

        levels.zipWithNext().forEachIndexed { index, level ->
            val difference = (level.second - level.first).toFloat()
            if (orderSign == 0.0f) orderSign = sign(difference)
            if (sign(difference) != orderSign || abs(difference) !in 1.0..3.0) {
                // With problem dampener: Drop either element in the pair or the first element from the original list and check if the result is now safe.
                return if (withProblemDampener) {
                    Report(levels.drop(1)).isSafe(false) || Report(levels.withoutElementAt(index)).isSafe(false) || Report(levels.withoutElementAt(index + 1)).isSafe(false)
                }  else false
            }
        }

        return true
    }
}

fun main() {
    fun part1(input: List<String>): Int = input.map { Report(it.split(" ").map { it.toInt() }).isSafe(false) }.count { it }

    fun part2(input: List<String>): Int = input.map { Report(it.split(" ").map { it.toInt() }).isSafe(true) }.count { it }

    // Or read a large test input from the `src/Day01_test.txt` file:
    val testInput = readInput("Day02_test")
    check(part1(testInput) == 2)
    check(part2(testInput) == 4)

    // Read the input from the `src/Day01.txt` file.
    val input = readInput("Day02")
    part1(input).println()
    part2(input).println()
}

The Report#isSafe method essentially solves both parts.

I've had a bit of a trip up in part 2:

I initially only checked, if the report was safe, if either elements in the pair were to be removed. But in the edge case, that the first pair has different monotonic behaviour than the rest, the issue would only be detected by the second pair with indices (2, 3), whilst removing the first element in the list would yield a safe report.

[–] [email protected] 1 points 3 weeks ago (2 children)

Rust

Turned out alright, I am looking forward to seeing what 2d coordinate grid code I can cannibalize from last year's solutions πŸ˜„

Github link

load more comments (2 replies)
[–] [email protected] 1 points 3 weeks ago

C#

using MathNet.Numerics.LinearAlgebra;
public class Day02 : Solver
{
  private ImmutableList<Vector<Double>> data;

  public void Presolve(string input)
  {
    data = input.Trim().Split("\n")
        .Select(
            line => Vector<Double>.Build.DenseOfEnumerable(line.Split(' ').Select(double.Parse))
        ).ToImmutableList();
  }

  private bool IsReportSafe(Vector<Double> report) {
    Vector<Double> delta = report.SubVector(1, report.Count - 1)
        .Subtract(report.SubVector(0, report.Count - 1));
    return (delta.ForAll(x => x > 0) || delta.ForAll(x => x < 0))
        && Vector<Double>.Abs(delta).Max() <= 3;
  }

  private bool IsDampenedReportSafe(Vector<Double> report) {
    for (Double i = 0; i < report.Count; ++i) {
      var dampened = Vector<Double>.Build.DenseOfEnumerable(
            report.EnumerateIndexed()
                .Where(item => item.Item1 != i)
                .Select(item => item.Item2));
      if (IsReportSafe(dampened)) return true;
    }
    return false;
  }

  public string SolveFirst() => data.Where(IsReportSafe).Count().ToString();

  public string SolveSecond() => data.Where(IsDampenedReportSafe).Count().ToString();
}
load more comments
view more: β€Ή prev next β€Ί