Skip to content

Instantly share code, notes, and snippets.

@JEG2
Created February 19, 2014 00:49
Show Gist options
  • Save JEG2/9084019 to your computer and use it in GitHub Desktop.
Save JEG2/9084019 to your computer and use it in GitHub Desktop.
I'm trying to solve or at least learn more about this problem.

I have a problem that pretty much boils down to this:

a = [1, 2, 3]
b = [1.1, 2.2, 3.3]

# BEGIN GROSS SOLUTION:  avert your eyes!
results = [ ]
a.each do |i|
  b.each do |j|
    results << [i, j, i + j]
  end
end
results.sort_by!(&:reverse)
# END GROSS SOLUTION

results.each do |row|
  p row
end
# >> [1, 1.1, 2.1]
# >> [2, 1.1, 3.1]
# >> [1, 2.2, 3.2]
# >> [3, 1.1, 4.1]
# >> [2, 2.2, 4.2]
# >> [1, 3.3, 4.3]
# >> [3, 2.2, 5.2]
# >> [2, 3.3, 5.3]
# >> [3, 3.3, 6.3]

As my gross solution hopefully shows, I want to combine these items into a list ordered by the cheapest combinations as efficiently as possible. I know the lists are sorted going into the challenge. I need to do this in the most efficient manner possible.

Is this a famous problem with a name? I feel like I should recognize it, but I don't.

Thanks in advance for any context you can provide.

@JEG2
Copy link
Author

JEG2 commented Feb 19, 2014

I was looking for this problem: Sorting X + Y/Pairwise Sums.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment