diff options
author | J.J <thechairman@thechairman.info> | 2024-05-30 21:49:58 -0400 |
---|---|---|
committer | J.J <thechairman@thechairman.info> | 2024-05-30 21:49:58 -0400 |
commit | 231c2b688d1e6cf0846d46e883da30e042a9c6cf (patch) | |
tree | 98a6d3a461fe190b38b2cf33a708a1d01703fa70 /codingquest2024/src/day2/solution.gleam | |
parent | fe088aa5778dcdbaab4dd8d4a7395a91c444b45c (diff) | |
parent | a2c2b728ec6051323ed937f54816089cd2ae9d20 (diff) | |
download | gleam_aoc-231c2b688d1e6cf0846d46e883da30e042a9c6cf.tar.gz gleam_aoc-231c2b688d1e6cf0846d46e883da30e042a9c6cf.zip |
Merge branch 'main' of https://github.com/hunkyjimpjorps/AdventOfCode
Diffstat (limited to 'codingquest2024/src/day2/solution.gleam')
-rw-r--r-- | codingquest2024/src/day2/solution.gleam | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/codingquest2024/src/day2/solution.gleam b/codingquest2024/src/day2/solution.gleam new file mode 100644 index 0000000..59f8d29 --- /dev/null +++ b/codingquest2024/src/day2/solution.gleam @@ -0,0 +1,66 @@ +import gleam/bit_array +import gleam/list +import gleam/int +import gleam/io +import gleam/string +import simplifile + +pub type Location { + Internal + Passenger + Other +} + +pub type Packet { + Packet(length: Int, endpoint: Location) +} + +pub fn main() { + let assert Ok(data) = simplifile.read(from: "./src/day2/data.txt") + + let #(internal_packets, passenger_packets) = + data + |> string.split("\n") + |> list.map(parse_packet) + |> list.partition(fn(p) { p.endpoint == Internal }) + + { + int.to_string(sum_packet_lengths(internal_packets)) + <> "/" + <> int.to_string(sum_packet_lengths(passenger_packets)) + } + |> io.println() +} + +fn parse_packet(raw_packet: String) { + let assert Ok(<< + _:bytes-size(2), + length:int-size(16), + _:bytes-size(8), + source:bytes-size(4), + destination:bytes-size(4), + >>) = bit_array.base16_decode(raw_packet) + + Packet(length, set_endpoint(source, destination)) +} + +fn set_endpoint(source: BitArray, dest: BitArray) -> Location { + case identify_location(source), identify_location(dest) { + Other, Internal | Internal, Other -> Internal + Other, Passenger | Passenger, Other -> Passenger + _, _ -> Other + } +} + +fn identify_location(ip: BitArray) -> Location { + case ip { + <<192, 168, _, _>> -> Internal + <<10, 0, _, _>> -> Passenger + _ -> Other + } +} + +fn sum_packet_lengths(packets: List(Packet)) -> Int { + use acc, p <- list.fold(packets, 0) + acc + p.length +} |