Skip to content

Commit

Permalink
Added an alternative way to do second part with dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
devries committed Dec 1, 2024
1 parent e1228b9 commit bec97dd
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/day01/solution.gleam
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import gleam/dict
import gleam/int
import gleam/io
import gleam/list
Expand All @@ -15,6 +16,7 @@ pub fn main() {
// successfully then run each part of the problem
io.println("Part 1: " <> aoc_utils.solution_or_error(solve_p1(lines)))
io.println("Part 2: " <> aoc_utils.solution_or_error(solve_p2(lines)))
io.println("Part 2b: " <> aoc_utils.solution_or_error(solve_p2b(lines)))
}
Error(_) -> io.println("Error reading file")
}
Expand Down Expand Up @@ -50,6 +52,24 @@ pub fn solve_p2(lines: List(String)) -> Result(String, String) {
|> int.to_string
}

// After seeing Jonathan Paulson's video of his solution, I realize it is likely
// much more efficient to create a dictionary of the counts for each element in
// list 2, then run through list one looking up the counts.
pub fn solve_p2b(lines: List(String)) -> Result(String, String) {
use #(l1, l2) <- result.map(parse_lines(lines))

let counts = count_values(l2)

l1
|> list.map(fn(x) {
dict.get(counts, x)
|> result.unwrap(0)
|> int.multiply(x)
})
|> int.sum
|> int.to_string
}

// Parse all lines
fn parse_lines(lines: List(String)) -> Result(#(List(Int), List(Int)), String) {
use combined <- result.try(list.try_map(lines, parse_line))
Expand Down Expand Up @@ -87,3 +107,10 @@ fn parse_line(line: String) -> Result(List(Int), String) {
|> list.try_map(int.parse)
|> result.replace_error("Unable to parse line: " <> line)
}

fn count_values(l: List(a)) -> dict.Dict(a, Int) {
list.fold(l, from: dict.new(), with: fn(d, x) {
let current_count = dict.get(d, x) |> result.unwrap(0)
dict.insert(d, for: x, insert: current_count + 1)
})
}
6 changes: 6 additions & 0 deletions test/day01_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,9 @@ pub fn part2_test() {
solution.solve_p2(lines)
|> should.equal(Ok("31"))
}

pub fn part2b_test() {
let lines = string.split(testinput, "\n")
solution.solve_p2b(lines)
|> should.equal(Ok("31"))
}

0 comments on commit bec97dd

Please sign in to comment.