Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring: Round-robin retrieve elements from nested arrays

I need to go over an array of hashes, with each hash containing a label and an array of data. The end result will be a concatenated string, label first, followed by the data that corresponds to that label.

The input array of hashes looks like:
[{label: "first", data: [1, 2]}, {label: "second", data: [3, 4, 5]}, {label: "third", data: []}, {label: "fourth", data: [6]}]
In this example,max_returns would be something high like: 10

def round_robin(arr, max_returns)
  result = ''
  i = 0 # number of grabbed elements
  j = 0 # inner array position
  k = 0 # outer array position
  l = 0 # number of times inner array length has been exceeded
  while i < max_returns do
    if k >= arr.length
      j += 1
      k = 0
    end
    element = arr[k]
    if element[:data].empty?
      k += 1
      next
    end

    if j >= element[:data].length
      l += 1
      k += 1

      if l > arr.length && i < max_returns
        break
      end
      next
    end
    result += element[:label] + ': ' + element[:data][j].to_s + ', '
    i += 1
    k += 1
  end
  result
end

Based on the input given above, output should be:
"first: 1, second: 3, fourth: 6, first: 2, second: 4, second: 5"

Also: max_returns is the maximum number of retrieved results total. So if my example had a max_returns = 3, then the output would have been:
"first: 1, second: 3, fourth: 6"

Question: Is there a better, or more efficient way to grab data from multiple arrays in a round robin fashion?

like image 989
Scytherswings Avatar asked Jul 18 '26 10:07

Scytherswings


1 Answers

This would work:

arr = [{ label: "first",  data: [1, 3] },
       { label: "second", data: [3, 4, 5] },
       { label: "third",  data: [] },
       { label: "fourth", data: [6] }]

results = []
arr.each do |h|
  h[:data].each_with_index do |d, i|
    results[i] ||= []
    results[i] << "#{h[:label]}: #{d}"
  end
end

results.flatten.join(', ')
#=> "first: 1, second: 3, fourth: 6, first: 3, second: 4, second: 5"
like image 67
Stefan Avatar answered Jul 20 '26 23:07

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!