Last active
January 6, 2019 02:48
-
-
Save seisvelas/9c1349d12e4ebbb980fa7f966f049482 to your computer and use it in GitHub Desktop.
Solution for Supermarket Queue Kata (https://www.codewars.com/kata/57b06f90e298a7b53d000a86) [edit: added comments for Pete education]
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
def queue_time(customers, n): | |
# keep track of time | |
wait = 0 | |
# pool of people currently checking out at a register | |
checkers_out = [] | |
# how many customers to load into queue. | |
# equals either the number of registers UNLESS | |
# there are less customers than registers, in which case | |
# all remaining customers are loaded up | |
load = n if n < len(customers) else len(customers) | |
# fill the checkout lanes! | |
for i in range(load): | |
checkers_out.append(customers[i]) | |
# take the customers in the registers out of the line | |
customers = customers[load:] | |
# we keep looping through until everyone has finished going through the registers and no one is left | |
# checking stuff out | |
while len(checkers_out) != 0: | |
# so we get the lowest wait time of everyone currently checking out | |
# and add that to how long we've been waiting | |
wait += min(checkers_out) | |
# then subtract that amount of time from everyone in the list. | |
# that means whoever had the minimum wait time is now done! | |
checkers_out = [i-min(checkers_out) for i in checkers_out] | |
# go through the checkout registers. People who are done checking out | |
# (ie, equal 0) are replaced with a new customer if there are anymore, | |
# otherwise they'll be left at zero and removed after this loop | |
for i in range(len(checkers_out)): | |
if checkers_out[i] == 0: | |
if len(customers) > 0: | |
checkers_out[i] = customers[0] | |
customers = customers[1:] | |
# get rid of everyone with zero wait time! (this happens | |
# when there's no one in the queue to replace the current | |
# people who've reached 0, but there are still others checking out. | |
checkers_out = [i for i in checkers_out if i != 0] | |
# all done, return our wait time! | |
return wait | |
print(queue_time([2,2,3,3,4,4], 2)) # prints 9! Rest of Codewars tests also pass <3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment