Question

I'm searching for a Ruby method or a general algorithm to sort 3 arrays into a new one. The criteria is that these 3 arrays have different lengths and that the result should reflect that regarding to the position of each of the elements in the new array.

Lets say I have these 3 arrays:

array1 = [0,1,2,3,4,5,6,7,8,9]
array2 = ['a','b','c']
array3 = ['x','y']

The end result should the look something like this:

[0,1,2,3,4,5,6,7,8,9]
[ 'a',   'b',   'c']
[    'x',    'y']

As you can see, the sorting should not be entirely random, each element should be placed regarding to the number of elements its original array has.

What's the best way to do this? Thanks!

Was it helpful?

Solution

Not sure if I understand your requirements, but here's my attempt:

  1. Calculate each element's relative position, i.e. 1st element = position 0, middle element = position 0.5, last element = position 1
  2. Merge all element / position pairs in a single array
  3. Sort the array by the calculated position
  4. Extract the elements / remove the position

Example implementation:

array1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
array2 = ['a', 'b', 'c']
array3 = ['x', 'y']

def pos(array)
  array.map.with_index { |e, i| [e, i / (array.size - 1.0)] }
end

result = pos(array1) + pos(array2) + pos(array3)
#=> [[0, 0.0], [1, 0.1111111111111111], [2, 0.2222222222222222], [3, 0.3333333333333333], [4, 0.4444444444444444], [5, 0.5555555555555556], [6, 0.6666666666666666], [7, 0.7777777777777778], [8, 0.8888888888888888], [9, 1.0], ["a", 0.0], ["b", 0.5], ["c", 1.0], ["x", 0.0], ["y", 1.0]]

result.sort_by(&:last).map(&:first)
#=> [0, "a", "x", 1, 2, 3, 4, "b", 5, 6, 7, 8, 9, "c", "y"]

You can change the order by tweaking the calculation, e.g. (i + 1) / (array.size + 1.0) gives:

#=> [0, 1, "a", 2, "x", 3, 4, "b", 5, 6, "y", 7, "c", 8, 9]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top