ClassicComputerScienceProblemsInSwift icon indicating copy to clipboard operation
ClassicComputerScienceProblemsInSwift copied to clipboard

Bug in eight queens algorithm?

Open faif opened this issue 5 years ago • 2 comments

A direct copy of the algorithm found in https://github.com/davecom/ClassicComputerScienceProblemsInSwift/blob/master/Classic%20Computer%20Science%20Problems%20in%20Swift.playground/Pages/Chapter%203.xcplaygroundpage/Contents.swift can give results that violate the same row constraint (if the format is "column: row"). For example:

"[2: 3, 5: 4, 7: 5, 4: 6, 8: 8, 1: 1, 3: 8, 6: 2]"

8:8 and 3:8 are in the same row, which is a violation. Another example:

"[5: 2, 7: 6, 8: 1, 1: 1, 4: 7, 2: 3, 6: 4, 3: 5]"

8:1 and 1:1 are violating the same row constraint

faif avatar Oct 09 '19 20:10 faif

Hi @faif,

You are correct, I am seeing this just now running the Playground in the latest version of Xcode/Swift (11.1, 5.1). I have not seen this before on the versions released at the time of the book (Swift 4.1 era). So, this either means:

A) Our algorithm was always wrong to begin with and we just got lucky on earlier versions

B) Something about how our algorithm is interpreted on current versions of Swift has changed

Right now I haven't had enough of a chance to look into this in detail. Let me know if you know the cause.

Thanks, David

davecom avatar Oct 10 '19 02:10 davecom

break statement in the isSatisfied function should be continue, since one can't count on the order that the for loop pulls (q1c, q1r) pairs from the assignment dictionary. As written, the isSatisfied function returns true whenever q1c == 8 without checking whatever pairs may remain in the dictionary.

trudolph99 avatar Nov 30 '23 20:11 trudolph99