Last active
November 24, 2023 15:35
-
-
Save sotolf2/04239f0fd89aeeecbbcbee30512d4d11 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/int | |
import gleam/io | |
import gleam/result | |
import gleam/set.{type Set} | |
import gleam/string | |
import simplifile | |
type Point { | |
Point(row: Int, col: Int) | |
} | |
fn next_pos(pos: Point, i: String) -> Point { | |
case i { | |
">" -> Point(pos.row, pos.col + 1) | |
"<" -> Point(pos.row, pos.col - 1) | |
"v" -> Point(pos.row + 1, pos.col) | |
"^" -> Point(pos.row - 1, pos.col) | |
_ -> pos | |
} | |
} | |
fn count_houses_rec(insts: List(String), seen: Set(Point), pos: Point) -> Int { | |
case insts { | |
[] -> set.size(seen) | |
[hd, ..tl] -> { | |
let newpos = next_pos(pos, hd) | |
count_houses_rec(tl, set.insert(seen, newpos), newpos) | |
} | |
} | |
} | |
fn count_houses(insts: String) -> Int { | |
count_houses_rec( | |
string.to_graphemes(insts), | |
set.from_list([Point(0, 0)]), | |
Point(0, 0), | |
) | |
} | |
fn count_houses_robo_rec( | |
instructions insts: List(String), | |
seen seen: Set(Point), | |
santa spos: Point, | |
robo rpos: Point, | |
) -> Int { | |
case insts { | |
[] -> set.size(seen) | |
[si, ri, ..tl] -> { | |
let new_santa = next_pos(spos, si) | |
let new_robo = next_pos(rpos, ri) | |
let new_seen = | |
seen | |
|> set.insert(new_santa) | |
|> set.insert(new_robo) | |
count_houses_robo_rec( | |
instructions: tl, | |
seen: new_seen, | |
santa: new_santa, | |
robo: new_robo, | |
) | |
} | |
} | |
} | |
fn count_houses_robo(insts: String) -> Int { | |
count_houses_robo_rec( | |
instructions: string.to_graphemes(insts), | |
seen: set.from_list([Point(0, 0)]), | |
santa: Point(0, 0), | |
robo: Point(0, 0), | |
) | |
} | |
fn part1(insts: String) { | |
let houses = count_houses(insts) | |
io.print("Part 1: ") | |
io.println(int.to_string(houses)) | |
} | |
fn part2(insts: String) { | |
let houses = count_houses_robo(insts) | |
io.print("Part 2: ") | |
io.println(int.to_string(houses)) | |
} | |
pub fn main() { | |
let instructions = | |
simplifile.read("./day03.txt") | |
|> result.unwrap(or: "") | |
part1(instructions) | |
part2(instructions) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment