Personal Website

My Web: MindEchoes.com

Monday, June 22, 2009

Always Turn Left (Code Jam)

Siguiendo con los ejercicios de Code Jam.... hice el segundo ejercicio, y la verdad que me llevo su buen tiempoooo.... estos ejercicios estan buenos para plantearse otro tipo de problemas fuera de lo habitual y tienen 2 dificultades importantes:
  • Lograr entender bien el problema
  • Pensar como hacer para que la maquina pueda entender el problema
Segundo Problema:

Problem Always Turn Left

You find yourself standing outside of a perfect maze. A maze is defined as "perfect" if it meets the following conditions:

  1. It is a rectangular grid of rooms, R rows by C columns.
  2. There are exactly two openings on the outside of the maze: the entrance and the exit. The entrance is always on the north wall, while the exit could be on any wall.
  3. There is exactly one path between any two rooms in the maze (that is, exactly one path that does not involve backtracking).

You decide to solve the perfect maze using the "always turn left" algorithm, which states that you take the leftmost fork at every opportunity. If you hit a dead end, you turn right twice (180 degrees clockwise) and continue. (If you were to stick out your left arm and touch the wall while following this algorithm, you'd solve the maze without ever breaking contact with the wall.) Once you finish the maze, you decide to go the extra step and solve it again (still always turning left), but starting at the exit and finishing at the entrance.

The path you take through the maze can be described with three characters: 'W' means to walk forward into the next room, 'L' means to turn left (or counterclockwise) 90 degrees, and 'R' means to turn right (or clockwise) 90 degrees. You begin outside the maze, immediately adjacent to the entrance, facing the maze. You finish when you have stepped outside the maze through the exit. For example, if the entrance is on the north and the exit is on the west, your path through the following maze would be WRWWLWWLWWLWLWRRWRWWWRWWRWLW:

If the entrance and exit were reversed such that you began outside the west wall and finished out the north wall, your path would be WWRRWLWLWWLWWLWWRWWRWWLW. Given your two paths through the maze (entrance to exit and exit to entrance), your code should return a description of the maze.

Entradas y Salidas esperadas se pueden consultar en la pagina del problema.

Codigo para Solución:

import sys

class TurnLeft:

def walk(self, move):
if self.direction == 8 or self.direction == 2:
self.addDescriptor(self.direction + (self.direction >> 1))
else:
self.addDescriptor(self.direction + (self.direction << 1))

def turn(self, move):
newDirection = self.rotations[str(self.direction) + move[0]]
self.addDescriptor(self.direction + newDirection)
self.revert(newDirection)

def reverse(self, move):
self.addDescriptor(self.direction)
self.revert(self.direction)

def revert(self, newDirec):
if newDirec == 8 or newDirec == 2:
self.direction = newDirec >> 1
else:
self.direction = newDirec << 1

def addDescriptor(self, descriptor):
if self.result.has_key(str(self.row)+'-'+str(self.column)):
self.compare(descriptor)
elif self.column < 0:
i = 1
while self.result.has_key(str(self.row)+'-'+str(self.column+i)):
descriptor, self.result[str(self.row)+'-'+str(self.column+i)] = \
self.result[str(self.row)+'-'+str(self.column+i)], descriptor
i += 1
self.result[str(self.row)+'-'+str(self.column+i)] = descriptor
self.column = 0
else:
self.result[str(self.row)+'-'+str(self.column)] = descriptor

def compare(self, descriptor):
new = self.int2bin(descriptor)
old = self.int2bin(self.result[str(self.row)+'-'+str(self.column)])
s = "".join([str(1 * (int(new[i]) | int(old[i])))
for i in range(0, len(new))])
self.result[str(self.row)+'-'+str(self.column)] = int(s, 2)

def __init__(self):
self.direction = 1
self.rotations = {'8R': 1, '8L': 2, '4R': 2, '4L': 1,
'2R': 8, '2L': 4, '1R': 4, '1L': 8}
self.increment = {'1': [1, 0], '2': [-1, 0],
'4': [0, 1], '8': [0, -1]}
self.result = {}
self.row, self.column = 0, 0
self.maxRow, self.maxColumn = 0, 0
self.operations = {'WW': self.walk, 'RW': self.turn,
'LW': self.turn, 'RR': self.reverse}

def processMaze(self):
if(len(sys.argv) > 1):
f = open(sys.argv[1], 'r')
cant = int(f.readline())

for i in range(0, cant):
paths = f.readline().split(' ')
self.direction = 1
self.row, self.column = 0, 0
self.maxRow, self.maxColumn = 0, 0
for q in range(0, 2):
pos = 0
if len(paths[q]) > 2: pos = 1
if q == 1:
self.revert(self.direction)
paths[q] = 'W'+paths[q]

self.processPath(paths[q], pos)
self.row -= self.increment[str(self.direction)][0]
self.column -= self.increment[str(self.direction)][1]

if self.maxRow == 1: self.maxRow = 0
print "Case #"+str(i+1)+':'
for w in range(0, self.maxRow+1):
values = ''
for e in range(0, self.maxColumn+1):
values += str(hex(self.result[str(w)+'-'+str(e)])[2:])
self.result[str(w)+'-'+str(e)] = 0
print values
else:
print 'FileName Missing'

def processPath(self, path, pos):
move = path[pos:pos+2]
if len(move) < 2: return
self.operations[move](move)
if move == 'RR':
pos += 2
elif path[pos+2:pos+3] != 'W':
pos += 1
self.row += self.increment[str(self.direction)][0]
self.column += self.increment[str(self.direction)][1]
if self.row > self.maxRow: self.maxRow = self.row
if self.column > self.maxColumn: self.maxColumn = self.column
self.processPath(path, pos+1)

def int2bin(self, n):
return "".join([str((n >> y) & 1) for y in range(3, -1, -1)])


def main():
turn = TurnLeft()
turn.processMaze()

if __name__ == "__main__":
main()

Si Alguien se quiere poner a resolverlo desde cero y tiene algun problema, esto QUIZAS les pueda servir de ayuda... mi solucion para entender las caracteristicas del ejercicio en la pizarra:

1 comment:

NahuelGQ said...

Hola, como te va?
Yo estuve haciendo este ejercicio en java, y logré pasar la prueba B-large-practice.in, pero B-small-practice.in no lo logré.
Vos lograste pasarlo, podrías postear las respuestas así puedo comparar con lo que mi programa genera así encuentro el error?

Gracias!
Nahuel