Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Distance sorting solution in Clear category for Colder-Warmer by Rounin
def cmp(a, b):
return (0 if a == b else (-1 if a < b else 1))
def distance(candidate, step):
return ((candidate[0]-step[0])**2+(candidate[1]-step[1])**2)**0.5
def checkio(steps):
# Find squares that match all the distance hints given in the steps.
acceptableSquares = []
for row in range(10):
for col in range(10):
for i in range(1, len(steps)+1):
if i == len(steps):
acceptableSquares.append([row, col])
elif cmp(distance([row, col], steps[i-1]), distance([row, col], steps[i])) != steps[i][2]:
break
# Find the step furthest away from the steps already tried.
acceptableSquares = sorted(acceptableSquares, key=lambda node: sum(map(lambda othernode: distance(node, othernode), steps)))
return (acceptableSquares[len(acceptableSquares)-1] if len(acceptableSquares) > 0 else None)
if __name__ == '__main__':
# This part is using only for self-checking and not necessary for auto-testing
from math import hypot
MAX_STEP = 12
def check_solution(func, goal, start):
prev_steps = [start]
for step in range(MAX_STEP):
row, col = func([s[:] for s in prev_steps])
if [row, col] == goal:
return True
if 10 <= row or 0 > row or 10 <= col or 0 > col:
print("You gave wrong coordinates.")
return False
prev_distance = hypot(prev_steps[-1][0] - goal[0], prev_steps[-1][1] - goal[1])
distance = hypot(row - goal[0], col - goal[1])
alteration = 0 if prev_distance == distance else (1 if prev_distance > distance else -1)
prev_steps.append([row, col, alteration])
print("Too many steps")
return False
assert check_solution(checkio, [7, 7], [5, 5, 0]), "1st example"
assert check_solution(checkio, [5, 6], [0, 0, 0]), "2nd example"
Oct. 15, 2017
Comments: