Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
buckets = [
{
capacity: 17,
bookings: [2,2,2,2,2,2]
},
{
capacity: 17,
bookings: [0]
},
{
capacity: 2,
bookings: [0]
}
]
bookings = buckets.map (bucket) ->
bucket.bookings.reduce (sum, booking) -> sum + booking
total = bookings.reduce (sum, booking) ->
sum + booking
average = total / buckets.length
spread_evenly = (buckets,average) ->
pre_process = (buckets) ->
buckets_pre_processed = buckets.map (bucket) ->
bucket.sum_bookings = bucket.bookings.reduce (sum, booking) -> sum + booking
bucket.bookings = bucket.bookings.sort (a,b) -> a-b
bucket.difference = bucket.sum_bookings - average
bucket
buckets_pre_processed.sort (a,b) ->
b.difference - a.difference
sorted_buckets = pre_process(buckets)
try_swap = (over, under)->
i = 0
end_absolute_difference = 1
start_absolute_difference = 0
did_swap = false
while !did_swap && end_absolute_difference > start_absolute_difference && i < over.bookings.length
over_to_move = over.bookings[i]
start_absolute_difference = Math.abs(over.difference) + Math.abs(under.difference)
end_absolute_difference = Math.abs(over.difference - over_to_move) + Math.abs(under.difference)
if end_absolute_difference > start_absolute_difference || (under.sum_bookings + over_to_move > under.capacity)
else
under.bookings.push(over_to_move)
over.bookings.splice(i,1)
did_swap = true
i++
did_swap
found_swap = false
i = 0
largest_over = sorted_buckets[i]
largest_under = sorted_buckets[sorted_buckets.length-1]
while !found_swap && largest_over.difference > 0
found_swap = try_swap(largest_over, largest_under)
largest_over = sorted_buckets[++i]
if found_swap
spread_evenly(sorted_buckets, average)
else
sorted_buckets
final_result = spread_evenly(buckets,average)
console.log "All Done"
console.log final_result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment