This repository has been archived by the owner on Jan 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise13.rb
100 lines (85 loc) · 2.19 KB
/
exercise13.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
require_relative 'exercise12.rb'
# Exercise 13
# danger=1 for adding, danger=-1 for removing
def place_queen(row,col,spots_taken,danger=1)
if(danger!=1&&danger!=-1)
raise "1 or -1 for danger parameter"
end
if(danger==-1)
spots_taken[row][col] = 4 # after 4 passes value is 0
end
# add or remove horizontal danger
0.upto(CHB_SIZE-1) do |c|
spots_taken[row][c]+=danger
end
# add or remove vertical danger
0.upto(CHB_SIZE-1) do |r|
spots_taken[r][col]+=danger
end
# add or remove botleft diagonal danger
r = findBotLeft(row,col)
currentRow,currentCol = r[0],r[1]
while(currentRow>=0&¤tCol<CHB_SIZE)
spots_taken[currentRow][currentCol]+=danger
currentRow-=1
currentCol+=1
end
# add or remove topleft diagonal danger
r = findTopLeft(row,col)
currentRow,currentCol = r[0],r[1]
while(currentRow<CHB_SIZE&¤tCol<CHB_SIZE)
spots_taken[currentRow][currentCol]+=danger
currentRow+=1
currentCol+=1
end
if(danger==1)
spots_taken[row][col] = true
end
end
def remove_queen(row,col,spots_taken)
place_queen(row,col,spots_taken,-1)
end
# spot is true or number of attacking queens
def betterEightQueens(spots_taken,num_queens_positioned)
if(num_queens_positioned==CHB_SIZE)
return true
else
0.upto(CHB_SIZE-1) do |row|
0.upto(CHB_SIZE-1) do |col|
if(spots_taken[row][col]==0)
place_queen(row,col,spots_taken)
if(betterEightQueens(spots_taken,num_queens_positioned + 1))
return true
else
remove_queen(row,col,spots_taken)
end
end
end
end
return false
end
end
def showResult2(spots_taken)
spots_taken.each do |row|
row.each do |p|
if(true==p)
print "X"
elsif(p>0)
print "!"
else
print " "
end
end
puts
end
end
def runQueens2
spots_taken = Array.new(CHB_SIZE)
0.upto(CHB_SIZE-1) { |i| spots_taken[i] = Array.new(CHB_SIZE,0) }
starting = Process.clock_gettime(Process::CLOCK_MONOTONIC)
betterEightQueens(spots_taken,0)
ending = Process.clock_gettime(Process::CLOCK_MONOTONIC)
puts "Second Version: #{ending-starting}"
showResult2(spots_taken)
end
# runQueens2