1

I have a pair of arrays,

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

and I'm trying to subtract the nth element of one array from the (n-1)-th element of the second array, starting with the n-th element, yielding an array of:

[9-1, 8-2, 7-3, 6-4] = [8, 6, 4, 2]

I wrote it in a procedural fashion:

 array_1.pop
 array_2.shift
 [array_2,array_1].transpose.map { |a,b| a-b }

but I do not wish to alter the arrays. Is there a method or another way to go about this?

2
  • What do you mean by "starting with the nth element"? Commented Mar 25, 2015 at 3:00
  • Sure, just a slight change to what you have: [array_2[1..-1], array_1[0..-2]].transpose.map { |a,b| a-b } #=> [8, 6, 4, 2]. Commented Mar 25, 2015 at 3:17

3 Answers 3

2

Another way:

enum1 = array_1.to_enum
enum2 = array_2.to_enum
enum2.next
arr = []

loop do
  arr << enum2.next - enum1.next
end
arr
  #=> [8, 6, 4, 2]
Sign up to request clarification or add additional context in comments.

2 Comments

Very nice, though how does the loop terminate? I've tested that it does, in fact, terminate, though there's something happening here that I haven't encountered before!
@Chris, Enumerator#next raises a StopIteration exception when an attempt is made to advance the enumerator beyond its end. (Same for peek.) The exception is handled by Kernel#loop by breaking out of the loop.
1

Use the non-destructive drop for the receiver, and zip, which will stop when the receiver runs out of an element even if the argument has more.

array_2.drop(1).zip(array_1).map{|a, b| a - b}

Comments

1

I think you may be overthinking it a bit; as long as both arrays are the same length, you can just iterate over the indices you care about, and reference the other array by index - offset.

array_1 = [1,2,3,4,5]
array_2 = [10,9,8,7,6]
n = 1
(n...array_1.length).map {|i| array_2[i] - array_1[i - 1] }

You can set n to whatever number you like and compute from that point onwards, so even if the arrays were tremendously large, you don't have to generate any intermediate arrays, and you don't have to perform any unnecessary work.

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.