Skip to content

Instantly share code, notes, and snippets.

@huseyinyilmaz
Created May 25, 2011 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save huseyinyilmaz/990384 to your computer and use it in GitHub Desktop.
Save huseyinyilmaz/990384 to your computer and use it in GitHub Desktop.
my solution for 40 cups and 9 oranges problem.
#!/usr/bin/python3.2
from itertools import combinations
"""
You have 40 bowls, all placed in a line at exact intervals of 1 meter. You also have 9 oranges. You wish to place all the oranges in the bowls, no more than one orange in each bowl, so that there are no three oranges A, B, and C such that the distance between A and B is equal to the distance between B and C. How many ways can you arrange the oranges in the bowls?.
(http://www.bittorrent.com/company/about/developer_challenge)
"""
def find_count(orange_count=9,cup_count=40,start_point=0,l=[]):
"""
orange_count: how many oranges should be placed in cups. for our question it is 9.
cup_count: how many cups should be used
rest of the arguments are used in recursive calls.you don't need to give them to the method
start_point: from which cup we should start. default is zero
l: holds cup numbers that we have oranges inside
"""
if len(l)==orange_count:
# we have enugh of oranges. stop recursive calls
result=1
#print(l)
else:
result = 0
for i in range(start_point,cup_count):
is_valid = True
# Choose ABC cups as C is being current current bowl
# And AB is being every combination of current stack of bowls
tuples = combinations(l,2)
for t in tuples:
if t[1]-t[0] == i - t[1]:
is_valid = False
break
# Check if current bowl is a valid one
if is_valid:
# There is no such ABC as B-A == C-B
# We can now add another orange to stack
result += find_count(orange_count,cup_count,i+1,l+[i])
return result
if __name__ == '__main__':
import sys
print('total =',find_count(int(sys.argv[1]),int(sys.argv[2]),0,[]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment