Skip to content

Commit 05428ef

Browse files
committed
day1 done
1 parent b805dd4 commit 05428ef

File tree

3 files changed

+62
-1
lines changed

3 files changed

+62
-1
lines changed

Sources/AdventOfCode.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import ArgumentParser
22

33
// Add each new day implementation to this array:
44
let allChallenges: [any AdventDay] = [
5-
Day00()
5+
Day01()
66
]
77

88
@main

Sources/Day01.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import Algorithms
2+
3+
struct Day01: AdventDay {
4+
// Save your data in a corresponding text file in the `Data` directory.
5+
var data: String
6+
7+
var lines: [[Substring.SubSequence]] {
8+
data.split(separator: "\n").map { $0.split(separator: " ") }
9+
}
10+
11+
// add here any computed values useful for the challenge
12+
13+
func part1() -> Int {
14+
let listRight = lines.map { Int($0[0]) ?? 0 }.sorted()
15+
let listLeft = lines.map { Int($0[1]) ?? 0 }.sorted()
16+
var sum = 0
17+
for (one, two) in zip(listLeft, listRight) {
18+
sum += abs(one - two)
19+
}
20+
return sum
21+
}
22+
23+
func part2() -> Int {
24+
let left = lines.map { Int($0[0]) ?? 0 }.sorted()
25+
let right = lines.map { Int($0[1]) ?? 0 }.sorted()
26+
27+
var similarity = 0
28+
for elem in left {
29+
let occurrences = right.filter { $0 == elem }.count
30+
similarity += elem * occurrences
31+
}
32+
return similarity
33+
}
34+
}

Tests/Day01.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import Testing
2+
3+
@testable import aoc
4+
5+
@Suite("Day01")
6+
struct Day01Tests {
7+
let testData = """
8+
3 4
9+
4 3
10+
2 5
11+
1 3
12+
3 9
13+
3 3
14+
"""
15+
16+
@Test("part1")
17+
func testPart1() async throws {
18+
let challenge = Day01(data: testData)
19+
#expect(challenge.part1() == 11)
20+
}
21+
22+
@Test("part2")
23+
func testPart2() async throws {
24+
let challenge = Day01(data: testData)
25+
#expect(challenge.part2() == 31)
26+
}
27+
}

0 commit comments

Comments
 (0)