Skip to content

Instantly share code, notes, and snippets.

@davispuh
Last active December 15, 2015 10:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davispuh/5246323 to your computer and use it in GitHub Desktop.
Save davispuh/5246323 to your computer and use it in GitHub Desktop.
Equally distribute several array elements across single array. (Ruby)
#!/usr/bin/env ruby
require 'pp'
a = []
a << [:a, :c, :e]
a << [:b, :f, :g, :h, :i, :j]
a << [:d]
# element coefficients
def get_coefficients array
(1..array.size).map { |i| (i - 0.5) / array.size }
end
elements = []
coefficients = []
a.each do |e|
elements += e
coefficients += get_coefficients(e)
end
# Combine all the arrays with their sort index.
combined = elements.zip(coefficients)
# Extract the values from the original arrays in their new order
r = combined.sort_by { |zipped| zipped[1] }.map { |zipped| zipped[0] }
pp r
# [:b, :a, :f, :g, :d, :c, :h, :i, :e, :j]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment