Last active
December 23, 2015 20:39
-
-
Save timmyshen/6691317 to your computer and use it in GitHub Desktop.
A group of friends went to a party and purchased some food and drinks for that. Now they are trying to evenly split the total bill in an efficient way.
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
import random | |
numOfPeople = 8 | |
amountScale = 100 | |
init_amounts = [random.randrange(amountScale) for i in range(numOfPeople)] | |
# Real world example | |
init_amounts = [56.16, 0, 26.7, 14, 80.1, 225.98, 238.86/2, 238.86/2] | |
# print init_amounts | |
sorted_amounts = sorted(init_amounts, reverse=True) | |
# print init_amounts | |
print sorted_amounts | |
avg_amount = sum(sorted_amounts) / float(len(sorted_amounts)) | |
# print avg_amount | |
excess_amount = [(i - avg_amount) for i in sorted_amounts] | |
print excess_amount | |
collection_pointer = 0 | |
payment_pointer = len(sorted_amounts)-1 | |
while collection_pointer < payment_pointer: | |
if excess_amount[collection_pointer] > -excess_amount[payment_pointer]: | |
print "Person {0} pays person {1} ${2}.".format(payment_pointer, collection_pointer, -excess_amount[payment_pointer]) | |
excess_amount[collection_pointer] = excess_amount[collection_pointer] + excess_amount[payment_pointer] | |
payment_pointer = payment_pointer - 1 | |
elif excess_amount[collection_pointer] < -excess_amount[payment_pointer]: | |
print "Person {0} pays person {1} ${2}.".format(payment_pointer, collection_pointer, excess_amount[collection_pointer]) | |
excess_amount[payment_pointer] = excess_amount[payment_pointer] + excess_amount[collection_pointer] | |
collection_pointer = collection_pointer + 1 | |
else: | |
print "Person {0} pays person {1} ${2}.".format(payment_pointer, collection_pointer, excess_amount[collection_pointer]) | |
payment_pointer = payment_pointer - 1 | |
collection_pointer = collection_pointer + 1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment