Andrea McKenzie
Andrea McKenzie

Reputation: 239

How to increase the increment of n if you want to iterate over every nth value of an array?

I'm trying to figure out how to increase the value of n so that I can iterate over an array multiple times while only grabbing certain elements at a time.

So let's say,

array = [1,2,3,4,5,6,7,8]
final_array = []
array.map.with_index do |x,i| 
   num = 2
    final_array << x if (i+1) % num == 0
    num += 1
end

This will only run as far as i % 2 and won't run for 3 or 4 or anything. I need to collect all the elements at i % 2, then i % 3, etc. How do I do that?

Upvotes: 0

Views: 396

Answers (2)

Stefan
Stefan

Reputation: 114178

This should work:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(2..5).map { |n| (0...numbers.size).step(n).map { |i| numbers[i] } }
#=> [[1, 3, 5, 7, 9], [1, 4, 7, 10], [1, 5, 9], [1, 6]]

You can also replace the first map with flat_map to get a flat array, i.e.:

(2..5).flat_map { |n| (0...numbers.size).step(n).map { |i| numbers[i] } }
#=> [1, 3, 5, 7, 9, 1, 4, 7, 10, 1, 5, 9, 1, 6]

Upvotes: 2

Dbz
Dbz

Reputation: 2761

If you don't care about time complexity i.g. O(n*m) vs O(n), you can make a nested loop.

numbers = [1, 2, 3, 4, 5, 6]
divisors = [1, 2, 3]
numbers_by_divisor = Hash.new { |h, k| h[k] = [] }

divisors.each do |divisor|
  numbers.each do |number|
    numbers_by_divisor[divisor] << number if (number + 1) % divisor == 0
  end
end

The numbers_by_divisor hash will be a hash of the arrays you want, with the key for each array being the divisor.

If you don't care about separating those numbers into different arrays, instead of a numbers_by_divisor hash just have an array called divisible_numbers:

numbers = [1, 2, 3, 4, 5, 6]
divisors = [1, 2, 3]
divisible_numbers = []

divisors.each do |divisor|
  numbers.each do |number|
    divisible_numbers << number if (number + 1) % divisor == 0
  end
end

The latter can be done in a more "Ruby" way with a select and any statement:

numbers.select do |number|
  divisors.any? { |divisor| (number + 1) % divisor == 0 }
end

Upvotes: 2

Related Questions