Created
May 5, 2011 20:21
-
-
Save neptunius/957840 to your computer and use it in GitHub Desktop.
Python solution to the Egg-Balancing Puzzle I invented.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!python | |
## Egg-Balancing Puzzle | |
## Alan Davis - 5/4/2011 | |
from __future__ import division # to ensure true division | |
import sys # to read input from standard input | |
import json # to decode input in JSON format | |
## Attempt to balance the given egg carton | |
def balance_carton(width, height, eggs): | |
eggs = map(tuple, eggs) | |
## Calculate the center of mass (scaled by the number of eggs) | |
center_x, center_y = 0, 0 | |
for x, y in eggs: | |
center_x += x | |
center_y += y | |
## Save the number of eggs for later use | |
e = len(eggs) | |
## Check if the egg carton is already balanced | |
if center_x == e*width and center_y == e*height: | |
center_unscaled = (center_x/e, center_y/e) | |
print 'Egg carton is already balanced at (%d, %d).' % center_unscaled | |
else: | |
## Calculate the coordinates of the missing egg by finding the | |
## distance from the center of the carton to the center of mass (both scaled) | |
egg_x = (e+1)*width - center_x | |
egg_y = (e+1)*height - center_y | |
## Check if this is a valid egg position by checking 3 conditions: | |
## (1) if its coordinates are both odd integers | |
## (2) if its coordinates between the boundaries of the egg carton | |
## (3) if its coordinates are not already occupied by another egg | |
odd_coords = (egg_x % 2 == 1) and (egg_y % 2 == 1) | |
in_bounds = (0 < egg_x < 2*width) and (0 < egg_y < 2*height) | |
not_taken = (egg_x, egg_y) not in eggs | |
## Print the approriate output message | |
if odd_coords and in_bounds and not_taken: | |
print 'Need to add an egg at (%d, %d) to balance carton.' % (egg_x, egg_y) | |
else: | |
print 'Egg carton cannot be balanced by adding one egg.' | |
## Solve the problems in JSON read from the given input stream | |
def solve_problems(input): | |
problems = json.load(input) | |
## Check if the JSON is a single problem or a list of problems | |
if isinstance(problems, dict): | |
## Solve a single problem | |
balance_carton(**problems) | |
elif isinstance(problems, list): | |
## Solve each problem in the list | |
for carton in problems: | |
balance_carton(**carton) | |
## If run from terminal, call solve_problems using standard input | |
if __name__ == '__main__': | |
solve_problems(sys.stdin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment