Skip to content

Commit

Permalink
feat: 2021 day 12, part two with Swift
Browse files Browse the repository at this point in the history
  • Loading branch information
icyJoseph committed Nov 9, 2022
1 parent 3714671 commit 9ae4e6d
Showing 1 changed file with 33 additions and 7 deletions.
40 changes: 33 additions & 7 deletions 2021/swift/day-12.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Foundation

let filename = "../input/day-12.in"

func search(_ root: String, _ adj: [String: [String]], _ history: Set<String>, _ acc: [String]) -> [String] {
func search(_ root: String, _ adj: [String: [String]], _ history: Set<String>, _ acc: [String], _ allow: String? = nil) -> [String] {
let paths = acc.map {
input in
var next = input
Expand All @@ -20,13 +20,26 @@ func search(_ root: String, _ adj: [String: [String]], _ history: Set<String>, _
continue
}

if node.lowercased() == node {
visited.insert(node)
if allow == nil {
if node.lowercased() == node {
visited.insert(node)
}

let localResult = search(node, adj, visited, paths)

result.append(contentsOf: localResult)
} else {
if node == allow {
let localResult = search(node, adj, visited, paths)
result.append(contentsOf: localResult)
} else {
if node.lowercased() == node {
visited.insert(node)
}
let localResult = search(node, adj, visited, paths, allow)
result.append(contentsOf: localResult)
}
}

let localResult = search(node, adj, visited, paths)

result.append(contentsOf: localResult)
}

return result
Expand All @@ -53,6 +66,19 @@ func main() {
let partOne = search("start", adj, Set(), ["start"])

print("Part one:", partOne.count)

let smallCaves = adj.keys.filter { $0.lowercased() == $0 }.filter { $0 != "start" }

var partTwo = Set<String>()

for cave in smallCaves {
let result = search("start", adj, Set(), ["start"], cave)

partTwo.formUnion(result)
}

print("Part two:", partTwo.count)

} catch {
print(error)
}
Expand Down

0 comments on commit 9ae4e6d

Please sign in to comment.