0

I need to create a method whose arguments are an array of subarrays that are of equal size and a shift value. The output needs to be a new array where the shifted values add up to each other.

Example

array[[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]]
shift_value = 4

#shift explained below

[1,2,3,4,5,6]
    [7,8,9,10,11,12]
        [13,14,15,16,17,18]

#desired output
[1,2,10,12,27,30,26,28,17,18]

Is there a method in ruby to do this? I spent some time making loops finding the index numbers that need to be added and forming a new array, but got lost.

1
  • 2
    You say shift value is 4, and yet you move them over two spots? Commented Feb 15, 2017 at 22:45

2 Answers 2

3

This seems to do what you want even though the shift value is off by a factor of two:

arrays = [ [1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18] ]
shift = 2

arrays.map.with_index do |a, i|
  # Zero pad the arrays to shift them over
  [ 0 ] * i * shift + a
end.reduce do |a, b|
  # Zip to combine and derive sums
  b.zip(a).map { |x,y| x + (y || 0) }
end

# => [1, 2, 10, 12, 27, 30, 26, 28, 17, 18]
Sign up to request clarification or add additional context in comments.

Comments

0

This solution employs recursion.

def shifty(arr, n)
  return arr.first if arr.size == 1
  first, *rest = arr
  prepend = [0]*n
  shifty(rest.map { |a| prepend + a }, n).map { |m| m + first.shift.to_i }
end

arr = [[ 1,  2,  3,  4,  5,  6],
               [ 7,  8,  9, 10, 11, 12],
                       [13, 14, 15, 16, 17, 18]]

shifty(arr, 2)
  #=>  [ 1,  2, 10, 12, 27, 30, 26, 28, 17, 18] 

When first.shift #=> nil, first.shift.to_i #=> 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.