Skip to content

Instantly share code, notes, and snippets.

@xullnn
Last active April 27, 2018 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xullnn/149e6790d7cfee3037362291827baca0 to your computer and use it in GitHub Desktop.
Save xullnn/149e6790d7cfee3037362291827baca0 to your computer and use it in GitHub Desktop.
Find the best destination combinations
class Destination
attr_accessor :name, :time_cost, :weight
def initialize(name,time_cost,weight)
@name = name
@time_cost = time_cost
@weight = weight
end
end
class Schedule
attr_accessor :limitation, :destinations, :table
def initialize(limitation)
@limitation = limitation
@destinations = []
@subtimes = make_subtimes
@table = Hash.new([0, [nil]])
end
def subtimes
@subtimes
end
def make_subtimes
t = 0.5
@subtimes = []
while t <= limitation
@subtimes << t
t += 0.5
end
@subtimes
end
def fill_destinations
destinations.each.with_index do |destination, index|
row = index + 1
subtimes.each.with_index do |subtime, index|
column = index + 1
previous_max_weight = table[[row-1, column]][0]
previous_max_name = table[[row-1, column]][1][0]
if subtime < destination.time_cost
table[[row, column]] = table[[row-1, column]]
elsif subtime == destination.time_cost
current_weight = destination.weight
current_weight >= previous_max_weight \
? table[[row, column]] = [current_weight, [destination.name]] \
: table[[row, column]] = table[[row-1, column]]
else
diff_time = subtime - destination.time_cost
offset_column = (diff_time/0.5).to_i
diff_weight = table[[row-1, offset_column]][0]
diff_destinations = table[[row-1, offset_column]][1]
if diff_weight == 0
table[[row, column]] = table[[row-1, column]]
else
new_weight = diff_weight + destination.weight
new_destinations = [destination.name] + diff_destinations
table[[row, column]] = [new_weight, new_destinations]
end
end
end
end
end
def find_best_combinations
sorted_table = table.sort_by { |k, v| v[0] }
best_combinations_weight = sorted_table[-1][1][0]
p best_combinations = table.select { |k,v| v[0] == best_combinations_weight }
end
end
a = Destination.new("A",0.5,7)
b = Destination.new("B",0.5,6)
c = Destination.new("C",1,9)
d = Destination.new("D",2,9)
e = Destination.new("E",0.5,8)
schedule = Schedule.new(2)
schedule.destinations = [a,b,c,d,e].shuffle
schedule.fill_destinations
schedule.find_best_combinations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment