Created
November 24, 2023 12:29
-
-
Save sotolf2/5e81d88115ea6a1d1f9747df5465c998 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gleam/io | |
import gleam/int | |
import gleam/function | |
import gleam/list | |
import gleam/result | |
import gleam/string | |
import simplifile | |
import nibble.{ type DeadEnd } | |
pub type Gift { | |
Gift(length: Int, width: Int, height: Int) | |
} | |
fn parse_line(line: String) -> Result(Gift, List(DeadEnd(a))) { | |
let parser = | |
nibble.succeed(function.curry3(Gift)) | |
|> nibble.drop(nibble.spaces()) | |
|> nibble.keep(nibble.int()) | |
|> nibble.drop(nibble.grapheme("x")) | |
|> nibble.keep(nibble.int()) | |
|> nibble.drop(nibble.grapheme("x")) | |
|> nibble.keep(nibble.int()) | |
|> nibble.drop(nibble.spaces()) | |
nibble.run(line, parser) | |
} | |
fn get_and_parse(path: String) -> List(Gift) { | |
simplifile.read(path) | |
|> result.unwrap(or: "") | |
|> string.split(on: "\n") | |
|> list.map(parse_line) | |
|> result.values() | |
} | |
fn area_of_smallest_side(g: Gift) -> Int { | |
list.fold(over: [g.length * g.width, g.height * g.length], | |
from: g.width * g.height, | |
with: int.min) | |
} | |
fn needed_paper(g: Gift) -> Int { | |
2 * g.length * g.width + | |
2 * g.width * g.height + | |
2 * g.height * g.length + | |
area_of_smallest_side(g) | |
} | |
fn smallest_perimeter(g: Gift) -> Int { | |
list.fold(over: [g.length * 2 + g.width * 2, g.height * 2 + g.length *2], | |
from: g.width * 2 + g.height * 2, | |
with: int.min) | |
} | |
fn needed_ribbon(g: Gift) -> Int { | |
smallest_perimeter(g) + g.height * g.width * g.length | |
} | |
fn part1(gifts: List(Gift)) { | |
let paper = | |
gifts | |
|> list.map(needed_paper) | |
|> list.fold(from: 0, with: int.add) | |
io.print("Part 1: ") | |
io.println(int.to_string(paper)) | |
} | |
fn part2(gifts: List(Gift)) { | |
let ribbon = | |
gifts | |
|> list.map(needed_ribbon) | |
|> list.fold(from: 0, with: int.add) | |
io.print("Part 2: ") | |
io.println(int.to_string(ribbon)) | |
} | |
pub fn main() { | |
let gifts = get_and_parse("./day02.txt") | |
part1(gifts) | |
part2(gifts) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment