Skip to content

Commit

Permalink
day 02: optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
sreedevk committed Dec 2, 2024
1 parent ea74fe8 commit 03cc241
Showing 1 changed file with 13 additions and 21 deletions.
34 changes: 13 additions & 21 deletions src/red_nosed_reports.gleam
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import gleam/int
import gleam/io
import gleam/list
import gleam/pair
import gleam/result
Expand All @@ -26,41 +25,34 @@ fn all_decr(report: List(Int)) -> Bool {
}
}

fn valid(report: List(Int)) -> Bool {
all_incr(report) || all_decr(report)
fn valid(report: List(Int), d: Bool) -> Bool {
case d {
False -> all_incr(report) || all_decr(report)
True -> valid(report, False) || list.any(variants(report), valid(_, False))
}
}

fn valid_after_dampener(report) -> Bool {
case valid(report) {
True -> True
False -> {
let indexed_list = list.index_map(report, fn(x, i) { #(i, x) })
let range = list.range(0, list.length(indexed_list) - 1)
let final_list =
list.map(range, fn(rmi) {
use #(_, flist) <- result.map(list.key_pop(indexed_list, rmi))
list.map(flist, pair.second)
})

let ys = list.map(final_list, fn(y) { result.unwrap(y, []) })
list.any(ys, fn(y) { valid(y) })
}
}
fn variants(report: List(Int)) -> List(List(Int)) {
list.range(0, list.length(report) - 1)
|> list.map(list.key_pop(list.index_map(report, fn(x, i) { #(i, x) }), _))
|> list.map(result.map(_, pair.second))
|> list.map(result.unwrap(_, []))
|> list.map(list.map(_, pair.second))
}

pub fn solve_a(input: String) -> Int {
input
|> string.trim()
|> string.split("\n")
|> list.map(parse_line)
|> list.count(valid(_))
|> list.count(valid(_, False))
}

pub fn solve_b(input: String) -> Int {
input
|> string.trim()
|> string.split("\n")
|> list.map(parse_line)
|> list.filter(valid_after_dampener(_))
|> list.filter(valid(_, True))
|> list.length()
}

0 comments on commit 03cc241

Please sign in to comment.