Created
August 15, 2024 19:14
-
-
Save asiniy/d70ed58bbf560996a5d8b7cfb9881aa4 to your computer and use it in GitHub Desktop.
iDelsoft @ Lenar
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
# Alex: It's a greedy algorithm, so it doesn't optimize in a perfect manner, but it's good enough | |
Ride = Struct.new(:weight, :count) | |
def calculate_rides(box_weights, max_weight, max_boxes) | |
raise ArgumentError.new("The box weight exceeds the maximum one") if box_weights.any? { |box| box > max_weight } | |
boxes = box_weights.sort.reverse | |
rides = [] | |
boxes.each do |box| | |
placed = false | |
rides.each do |ride| | |
if ride.count < max_boxes && ride.weight + box <= max_weight | |
ride.weight += box | |
ride.count += 1 | |
placed = true | |
break | |
end | |
end | |
if !placed | |
rides << Ride.new(box, 1) | |
end | |
end | |
rides.count | |
end | |
box_weights = [500, 900, 800, 200, 150, 450, 451] | |
max_weight = 900 | |
max_boxes = 6 | |
puts calculate_rides(box_weights, max_weight, max_boxes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment