Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6bd8af5

Browse files
committed
Incorporated @twobitlabs style suggestions; added some comments; fixed bug in Eight Queens problem
1 parent 195f697 commit 6bd8af5

File tree

5 files changed

+35
-33
lines changed

5 files changed

+35
-33
lines changed

‎Classic Computer Science Problems in Swift.playground/Pages/Chapter 2.xcplaygroundpage/Contents.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -265,11 +265,11 @@ func dfs<StateType: Hashable>(initialState: StateType, goalTestFn: (StateType) -
265265

266266
func nodeToPath<StateType>(_ node: Node<StateType>) -> [StateType] {
267267
var path: [StateType] = [node.state]
268-
var currentNode = node.parent
268+
var node = node // local modifiable copy of reference
269269
// work backwards from end to front
270-
while currentNode !=nil {
271-
path.insert(currentNode!.state, at: 0)
272-
currentNode = currentNode!.parent
270+
while letcurrentNode = node.parent {
271+
path.insert(currentNode.state, at: 0)
272+
node = currentNode
273273
}
274274
return path
275275
}

‎Classic Computer Science Problems in Swift.playground/Pages/Chapter 3.xcplaygroundpage/Contents.swift

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -74,21 +74,21 @@ public func backtrackingSearch<V, D>(csp: CSP<V, D>, assignment: Dictionary<V, D
7474
// assignment is complete if it has as many assignments as there are variables
7575
if assignment.count == csp.variables.count { return assignment } // base case
7676

77-
// get an unassigned variable
78-
var variable: V = csp.variables.first! // temporary
79-
for x in csp.variables where assignment[x] == nil {
80-
variable = x
81-
}
77+
// what are the unassigned variables?
78+
let unassigned = csp.variables.lazy.filter({ assignment[0ドル] == nil })
8279

83-
// get the domain of it and try each value in the domain
84-
for value in csp.domains[variable]! {
85-
var localAssignment = assignment
86-
localAssignment[variable] = value
87-
// if the value is consistent with the current assignment we continue
88-
if isConsistent(variable: variable, value: value, assignment: localAssignment, csp: csp) {
89-
// if as we go down the tree we get a complete assignment, return it
90-
if let result = backtrackingSearch(csp: csp, assignment: localAssignment) {
91-
return result
80+
// get the domain of the first unassigned variable
81+
if let variable: V = unassigned.first, let domain = csp.domains[variable] {
82+
// try each value in the domain
83+
for value in domain {
84+
var localAssignment = assignment
85+
localAssignment[variable] = value
86+
// if the value is consistent with the current assignment we continue
87+
if isConsistent(variable: variable, value: value, assignment: localAssignment, csp: csp) {
88+
// if as we go down the tree we get a complete assignment, return it
89+
if let result = backtrackingSearch(csp: csp, assignment: localAssignment) {
90+
return result
91+
}
9292
}
9393
}
9494
}
@@ -97,7 +97,7 @@ public func backtrackingSearch<V, D>(csp: CSP<V, D>, assignment: Dictionary<V, D
9797

9898
/// check if the value assignment is consistent by checking all constraints of the variable
9999
func isConsistent<V, D>(variable: V, value: D, assignment: Dictionary<V, D>, csp: CSP<V,D>) -> Bool {
100-
for constraint in csp.constraints[variable]! {
100+
for constraint in csp.constraints[variable]??[] {
101101
if !constraint.isSatisfied(assignment: assignment) {
102102
return false
103103
}
@@ -160,14 +160,14 @@ final class QueensConstraint: Constraint <Int, Int> {
160160
}
161161

162162
override func isSatisfied(assignment: Dictionary<Int, Int>) -> Bool {
163-
for (q1c, q1r) in assignment {
163+
for (q1c, q1r) in assignment { // q1c = queen 1 column, q1r = queen 1 row
164164
if (q1c >= vars.count) {
165165
break
166166
}
167-
for q2c in (q1c + 1)..<vars.count {
168-
if let q2r = assignment[q2c] {
169-
if q1r == q2r { return false }
170-
if abs(q1r - q2r) == abs(q1c - q2c) { return false }
167+
for q2c in (q1c + 1)...vars.count { // queen 2 column
168+
if let q2r = assignment[q2c] { // queen 2 row
169+
if q1r == q2r { return false } // rows same?
170+
if abs(q1r - q2r) == abs(q1c - q2c) { return false } // same diagonal?
171171
}
172172
}
173173
}

‎Classic Computer Science Problems in Swift.playground/Pages/Chapter 4.xcplaygroundpage/Contents.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ extension Graph {
5252
if let i = vertices.index(of: vertex) {
5353
return i
5454
}
55-
return nil;
55+
return nil
5656
}
5757

5858
/// Find all of the neighbors of a vertex at a given index.
@@ -339,11 +339,11 @@ open class WeightedGraph<V: Equatable & Hashable, W: Comparable & Summable>: Gra
339339
/// - parameter index: The index for the vertex to find the neighbors of.
340340
/// - returns: An array of tuples including the vertices as the first element and the weights as the second element.
341341
public func neighborsForIndexWithWeights(_ index: Int) -> [(V, W)] {
342-
var distanceTuples: [(V, W)] = [(V, W)]();
342+
var distanceTuples: [(V, W)] = [(V, W)]()
343343
for edge in edges[index] {
344344
distanceTuples += [(vertices[edge.v], edge.weight)]
345345
}
346-
return distanceTuples;
346+
return distanceTuples
347347
}
348348

349349
/// This is a convenience method that adds a weighted edge.

‎Classic Computer Science Problems in Swift.playground/Pages/Chapter 5.xcplaygroundpage/Contents.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ extension Array {
2727
if count < 2 { return shuffledArray } // already shuffled
2828
for i in (1..<count).reversed() { // count backwards
2929
let position = Int(arc4random_uniform(UInt32(i + 1))) // random to swap
30-
if i != position { // swap with the end, don't bother with selp swaps
30+
if i != position { // swap with the end, don't bother with self swaps
3131
shuffledArray.swapAt(i, position)
3232
}
3333
}

‎Classic Computer Science Problems in Swift.playground/Pages/Chapter 8.xcplaygroundpage/Contents.swift

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,18 @@ struct Item {
2626
let value: Float
2727
}
2828

29-
// based on sedgewick second edition p 596
29+
// originally based on Algorithms in C by Sedgewick, Second Edition, p 596
3030
func knapsack(items: [Item], maxCapacity: Int) -> [Item] {
3131
//build up dynamic programming table
3232
var table: [[Float]] = [[Float]](repeating: [Float](repeating: 0.0, count: maxCapacity + 1), count: items.count + 1) //initialize table - overshooting in size
33-
for iin 1...items.count {
33+
for (i, item)in items.enumerated() {
3434
for capacity in 1...maxCapacity {
35-
if capacity - items[i - 1].weight >= 0 { // still room in knapsack
36-
table[i][capacity] = max(table[i - 1][capacity - items[i - 1].weight] + items[i - 1].value, table[i - 1][capacity]) // only take if more valuable than previous combo
35+
let previousItemsValue = table[i][capacity]
36+
if capacity >= item.weight { // item fits in knapsack
37+
let valueFreeingWeightForItem = table[i][capacity - item.weight]
38+
table[i + 1][capacity] = max(valueFreeingWeightForItem + item.value, previousItemsValue) // only take if more valuable than previous combo
3739
} else { // no room for this item
38-
table[i][capacity]=table[i -1][capacity] //use prior combo
40+
table[i+1][capacity]= previousItemsValue //use prior combo
3941
}
4042
}
4143
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /