Skip to content

2016 - Day 4 - Security Through Obscurity #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions 2016/Sources/AdventOfCode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ let allChallenges: [any AdventDay] = [
Day01(),
Day02(),
Day03(),
Day04(),
]

@main
Expand Down
54 changes: 54 additions & 0 deletions 2016/Sources/Day04.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Foundation
import Collections

private typealias KeyValuePair = (k: Character, v: Int)

struct Day04: AdventDay {
let data: String

func part1() -> Int {
return data.matches(of: /([a-z-]+)-(\d+)\[([a-z]+)]/)
.reduce(0) { sum, match in
let (_, name, id, checksum) = match.output

let counts = Dictionary(
uniqueKeysWithValues: name.uniqued()
.filter { $0.isLetter }
.map { c in (c, name.count(where: { $0 == c })) }
)

let actualChecksum = counts.keys
.sorted()
.sorted(by: { counts[$0]! > counts[$1]! })
.prefix(5)

return if actualChecksum.elementsEqual(checksum) {
sum + Int(id)!
} else {
sum
}
}
}

func part2() -> Int {
let asciiStart = Int(Character("a").asciiValue!)

return data.matches(of: /([a-z-]+)-(\d+)\[([a-z]+)]/)
.map { match in
let (_, name, id, _) = match.output

let decrypted = name.split(separator: "-")
.map { word in
String(
word.map { letter in
Character(UnicodeScalar((Int(letter.asciiValue!) - asciiStart + Int(id)!) % 26 + asciiStart)!)
}
)
}
.joined(separator: " ")

return (decrypted, Int(id)!)
}
.first(where: { $0.0 == "northpole object storage" })!.1
}
}
16 changes: 16 additions & 0 deletions 2016/Tests/Day04Tests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Testing

@testable import AoC2016

struct Day04Tests {
let testData = """
aaaaa-bbb-z-y-x-123[abxyz]
a-b-c-d-e-f-g-h-987[abcde]
not-a-real-room-404[oarel]
totally-real-room-200[decoy]
"""

@Test func testPart1() throws {
#expect(try Day04(data: testData).part1() == 1514)
}
}