1 Object subclass: #Queen
2 instanceVariableNames: ‘position‘
3 classVariableNames: ‘‘
4 poolDictionaries: ‘‘
5 category: ‘Queens‘!
6 !Queen commentStamp: ‘TomZhao 10/15/2015 13:17‘ prior: 0!
7 Queen at: 1@1.!
8
9
10 !Queen methodsFor: ‘accessing‘ stamp: ‘TomZhao 10/15/2015 13:22‘!
11 moveTo: aPoint
12 self position: aPoint.! !
13
14 !Queen methodsFor: ‘accessing‘ stamp: ‘TomZhao 10/15/2015 13:41‘!
15 position
16 ^ position! !
17
18 !Queen methodsFor: ‘accessing‘ stamp: ‘TomZhao 10/15/2015 13:17‘!
19 position: aPoint
20 position := aPoint! !
21
22
23 !Queen methodsFor: ‘as yet unclassified‘ stamp: ‘TomZhao 10/15/2015 13:29‘!
24 meets: queen
25 |a b|
26 a := self position.
27 b := queen position.
28 ^(a x = b x) | (a y = b y) | ((a x - b x) abs = (a y - b y) abs).! !
29
30
31 !Queen methodsFor: ‘testing‘ stamp: ‘TomZhao 10/15/2015 13:39‘!
32 isSafeWith: queens
33 ^queens allSatisfy: [ :queen | (self meets: queen) not ].! !
34
35 "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!
36
37 Queen class
38 instanceVariableNames: ‘‘!
39
40 !Queen class methodsFor: ‘as yet unclassified‘ stamp: ‘TomZhao 10/15/2015 09:42‘!
41 at: aPoint
42 "comment stating purpose of message"
43 | tmp |
44 tmp := self new.
45 tmp position: aPoint.
46 ^tmp.! !
47
48
49 Object subclass: #Queens
50 instanceVariableNames: ‘size‘
51 classVariableNames: ‘‘
52 poolDictionaries: ‘‘
53 category: ‘Queens‘!
54 !Queens commentStamp: ‘TomZhao 10/15/2015 14:25‘ prior: 0!
55 Queens run: 6.!
56
57
58 !Queens methodsFor: ‘acccessing‘ stamp: ‘TomZhao 10/15/2015 13:21‘!
59 size: anInteger
60 size := anInteger! !
61
62
63 !Queens methodsFor: ‘as yet unclassified‘ stamp: ‘TomZhao 10/15/2015 14:39‘!
64 printSolution: queens
65 Transcript show: ($- join: (queens collect: [ :q | q position y ])); cr.! !
66
67
68 !Queens methodsFor: ‘running‘ stamp: ‘TomZhao 10/15/2015 14:53‘!
69 run: anInteger
70 self size: anInteger.
71 self solve: 1 with: OrderedCollection new.
72 Transcript show: ‘Game Over!!‘; cr.
73 ^self.! !
74
75 !Queens methodsFor: ‘running‘ stamp: ‘TomZhao 10/15/2015 14:52‘!
76 solve: nRow with: queens
77 | q tmp |
78 q :=Queen at: nRow@1.
79 (1 to: size) do: [ :col |
80 q moveTo: nRow@col.
81 tmp := queens copy.
82 (q isSafeWith: tmp)
83 ifTrue: [
84 tmp add: q.
85 nRow = size
86 ifTrue:[self printSolution: tmp. ]
87 ifFalse:[self solve: (nRow+1) with: tmp.]]].! !
88
89 "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!
90
91 Queens class
92 instanceVariableNames: ‘‘!
93
94 !Queens class methodsFor: ‘as yet unclassified‘ stamp: ‘TomZhao 10/13/2015 17:01‘!
95 run: size
96
97 Queens new
98 run: size.
99 ^self.! !