Skip to content

Commit

Permalink
add code to distributed_merge.rb
Browse files Browse the repository at this point in the history
  • Loading branch information
msuliq committed Apr 15, 2023
1 parent 30b345d commit 5044192
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions lib/distributed_merge.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,34 @@
require_relative "distributed_merge/version"

module DistributedMerge
class Error < StandardError; end
# Your code goes here...
class Array # :nodoc:
# Accepts a two-dimensional array with subarrays of varying size and returns
# merged array with the elements distributed evenly.

def distributed_merge
return self unless two_dimensional?

data = sort_by { |ary| ary.flatten.count }.reverse
largest = data.first

data.drop(1).each do |ary|
offset = largest.length / (ary.length + 1)
ary.each_with_index do |el, i|
if i == 1
largest.insert(((largest.length / 2) - offset), el)
elsif i.even?
largest.insert(((largest.length / 2) + (offset + i)), el)
else
largest.insert(((largest.length / 2) - (offset + i)), el)
end
end
end

largest
end

def two_dimensional?
all? { |arg| arg.is_a?(Array) } && flatten(1).count > 1
end
end
end

0 comments on commit 5044192

Please sign in to comment.