FA16-BCS-178 (AI ASSIGNMENT#2 8puzzle)
FA16-BCS-178 (AI ASSIGNMENT#2 8puzzle)
FA16-BCS-178 (AI ASSIGNMENT#2 8puzzle)
CODE:
import sys
import re
import copy
class Error(Exception):
pass
class InputError(Error):
class EightPuzzle():
def __init__(self, str):
pttn = re.compile("(\d)\s(\d)\s(\d)\s(\d)\s(\d)\s(\d)\s(\d)\s(\d)\s(\d)")
result = pttn.match(str)
if result is not None:
s = result.groups()
self.state = [[int(s[0]), int(s[1]), int(s[2])],
[int(s[3]), int(s[4]), int(s[5])],
[int(s[6]), int(s[7]), int(s[8])]]
else:
raise InputError("Improperly formatted 8-puzzle")
def __str__(self):
s = ''
for i in range(0, 3):
for j in range(0, 3):
s += str(self.state[i][j]) + ' '
return s
def __hash__(self):
uid = 0
mult = 1
for i in range(0, 3):
for j in range(0, 3):
uid += self.state[i][j] * mult
mult *= 9
return uid
def neighbors(self):
list = []
idx = self.get_blank_index()
x = idx[0]
y = idx[1]
if x > 0:
r = copy.deepcopy(self)
r.state[y][x] = r.state[y][x - 1]
r.state[y][x - 1] = 0
list.append((r, 'r'))
if x < 2:
l = copy.deepcopy(self)
l.state[y][x] = l.state[y][x + 1]
l.state[y][x + 1] = 0
list.append((l, 'l'))
if y > 0:
d = copy.deepcopy(self)
d.state[y][x] = d.state[y - 1][x]
d.state[y - 1][x] = 0
list.append((d, 'd'))
if y < 2:
u = copy.deepcopy(self)
u.state[y][x] = u.state[y + 1][x]
u.state[y + 1][x] = 0
list.append((u, 'u'))
return list
def get_blank_index(self):
for i in range(0, 3):
for j in range(0, 3):
if self.state[i][j] == 0:
x = j
y = i
return (x, y)
g_score = {self: 0}
f_score = {self: g_score[self] + heuristic(self, goal)}
open_set.remove(current)
closed_set.add(current)
# print "Closed set:"
# for p in closed_set:
# print p
for n in current.neighbors():
neighbor = n[0]
# print "Neighbor:\n",neighbor
if neighbor in closed_set:
# print "Current:\n",current
# print "Neighbor:\n",neighbor
continue
tentative_g_score = g_score[current] + 1
return "nil"
def main():
if len(sys.argv) < 2 or len(sys.argv) > 3:
raise InputError("Not enough arguments")
h = int(sys.argv[1])
if h == 1:
heuristic = EightPuzzle.manhatten_distance
elif h == 2:
heuristic = EightPuzzle.tile_switches_remaining
else:
raise InputError("Heuristic argument must be 1 or 2")
if len(sys.argv) == 3:
o = int(sys.argv[2])
if o == 0:
output = EightPuzzle.action_sequence
elif o == 1:
output = EightPuzzle.state_transition
else:
raise InputError("Output argument must be 0 or 1")
else:
output = EightPuzzle.action_sequence
input_i = sys.stdin.readline()
input_f = sys.stdin.readline()
initial = EightPuzzle(input_i)
goal = EightPuzzle(input_f)
if __name__ == '__main__':
main()