Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d195a9e

Browse files
committed
2022 day 12 refactor
1 parent f7ab996 commit d195a9e

File tree

1 file changed

+34
-22
lines changed
  • aoc22.playground/Pages/Day12.xcplaygroundpage/Sources

1 file changed

+34
-22
lines changed

aoc22.playground/Pages/Day12.xcplaygroundpage/Sources/Day12.swift

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,37 @@ struct Point: Hashable, Equatable {
1818
}
1919
}
2020

21+
struct World {
22+
let world: Dictionary<Point, Int>
23+
let start: Point
24+
let goal: Point
25+
}
26+
27+
func inputData() -> World {
28+
var world = Dictionary<Point, Int>()
29+
var start = Point(x: 0, y: 0)
30+
var goal = Point(x: 0, y: 0)
31+
var y = 0
32+
for line in stringsFromFile() where line != "" {
33+
var x = 0
34+
for ch in line {
35+
let p = Point(x: x, y: y)
36+
var value = Int(ch.asciiValue!) - 97
37+
if ch == "S" {
38+
start = p
39+
value = 0
40+
} else if ch == "E" {
41+
goal = p
42+
value = 25
43+
}
44+
world[p] = value
45+
x += 1
46+
}
47+
y += 1
48+
}
49+
return World(world: world, start: start, goal: goal)
50+
}
51+
2152
func bfs(start: Point, goal: (Point) -> Bool, world: Dictionary<Point, Int>) -> [Point] {
2253
var queue = [Point]()
2354
queue.append(start)
@@ -44,26 +75,7 @@ func bfs(start: Point, goal: (Point) -> Bool, world: Dictionary<Point, Int>) ->
4475
}
4576

4677
public func part1() -> Int {
47-
var world = Dictionary<Point, Int>()
48-
var start = Point(x: 0, y: 0)
49-
var goal = Point(x: 0, y: 0)
50-
var y = 0
51-
for line in stringsFromFile() where line != "" {
52-
var x = 0
53-
for ch in line {
54-
let p = Point(x: x, y: y)
55-
var value = Int(ch.asciiValue!) - 97
56-
if ch == "S" {
57-
start = p
58-
value = 0
59-
} else if ch == "E" {
60-
goal = p
61-
value = 25
62-
}
63-
world[p] = value
64-
x += 1
65-
}
66-
y += 1
67-
}
68-
return bfs(start: start, goal: { $0 == goal }, world: world).count
78+
let data = inputData()
79+
return bfs(start: data.start, goal: { $0 == data.goal }, world: data.world).count
80+
}
6981
}

0 commit comments

Comments
 (0)