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
/
exercise1.rb
88 lines (76 loc) · 1.55 KB
/
exercise1.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
require 'matrix'
# Exercise 1
class Board
def initialize
@arr = []
3.times do
@arr << [nil,nil,nil]
end
end
def checkRows(symbol)
row = Array.new(3,symbol)
return @arr[0]==row||@arr[1]==row||@arr[2]==row
end
def checkCols(symbol)
for i in 0..2
if(@arr[0][i]==symbol&&@arr[1][i]==symbol&&@arr[2][i]==symbol)
return true
end
end
return false
end
def checkDiagonals(symbol)
return @arr[0][0]==symbol&&@arr[1][1]==symbol&&@arr[2][2]==symbol||
@arr[0][2]==symbol&&@arr[1][1]==symbol&&@arr[2][0]==symbol
end
def win?(symbol)
return checkRows(symbol)||
checkCols(symbol)||
checkDiagonals(symbol)
end
def full?
for i in 0..2
for j in 0..2
if(@arr[i][j].nil?)
return false
end
end
end
return true
end
def [](indx)
return @arr[indx]
end
end
def swp(symbol)
return symbol=="X"?"O":"X"
end
def exhaustiveSearch(board,player)
if(board.win?("X"))
return Vector[1,0,0]
elsif(board.win?("O"))
return Vector[0,1,0]
elsif(board.full?)
return Vector[0,0,1]
else
result = Vector[0,0,0]
for i in 0..2
for j in 0..2
if(board[i][j].nil?)
board[i][j] = player
result += exhaustiveSearch(board,swp(player))
board[i][j] = nil
end
end
end
return result
end
end
=begin
board = Board.new
result = exhaustiveSearch(board,"X")
puts "X: #{result[0]}"
puts "O: #{result[1]}"
puts "Tie: #{result[2]}"
puts "Games: #{result.sum}"
=end