Skip to content

Commit 06e5950

Browse files
committed
Day 2 part 1
1 parent 02eb202 commit 06e5950

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

src/adventofcode2024.gleam

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import argv
66
import simplifile
77

88
import day1
9+
import day2
910

1011
pub fn main() {
1112
case argv.load().arguments {
@@ -14,7 +15,7 @@ pub fn main() {
1415
Ok(n) -> run(n)
1516
Error(_) -> io.println("Invalid day: " <> arg)
1617
}
17-
_ -> list.range(1, 1) |> list.each(fn(n) { run(n) })
18+
_ -> list.range(1, 2) |> list.each(fn(n) { run(n) })
1819
}
1920
}
2021

@@ -24,6 +25,7 @@ fn run(n: Int) -> Nil {
2425
io.print(output("Part 1: "))
2526
io.println(case n {
2627
1 -> day1.part1(input) |> int.to_string
28+
2 -> day2.part1(input) |> int.to_string
2729
_ -> "(not implemented)"
2830
})
2931
io.print(output("Part 2: "))

src/day2.gleam

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import gleam/int
2+
import gleam/list
3+
import gleam/string
4+
5+
pub fn part1(input: String) -> Int {
6+
input |> parse_input |> list.count(safe)
7+
}
8+
9+
fn safe(report: List(Int)) -> Bool {
10+
increasing(report) || decreasing(report)
11+
}
12+
13+
fn increasing(report: List(Int)) -> Bool {
14+
case report {
15+
[first, second, ..rest] ->
16+
second > first && second - first <= 3 && increasing([second, ..rest])
17+
_ -> True
18+
}
19+
}
20+
21+
fn decreasing(report: List(Int)) -> Bool {
22+
case report {
23+
[first, second, ..rest] ->
24+
second < first && first - second <= 3 && decreasing([second, ..rest])
25+
_ -> True
26+
}
27+
}
28+
29+
fn parse_input(input: String) -> List(List(Int)) {
30+
input
31+
|> string.split("\n")
32+
|> list.filter(fn(line) { line != "" })
33+
|> list.map(fn(line) {
34+
line |> string.split(" ") |> list.filter_map(fn(str) { int.parse(str) })
35+
})
36+
}

test/day2_test.gleam

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import gleeunit
2+
import gleeunit/should
3+
4+
import day2
5+
6+
pub fn main() {
7+
gleeunit.main()
8+
}
9+
10+
const example1 = "7 6 4 2 1
11+
1 2 7 8 9
12+
9 7 6 2 1
13+
1 3 2 4 5
14+
8 6 4 4 1
15+
1 3 6 7 9
16+
"
17+
18+
pub fn part1_test() {
19+
day2.part1(example1) |> should.equal(2)
20+
}

0 commit comments

Comments
 (0)