user1594138
user1594138

Reputation: 1011

Subtraction of two arrays with incremental indexes of the other array to a maximum limit

I have lots of math to do on lots of data but it's all based on a few base templates. So instead of say, when doing math between 2 arrays I do this:

results = [a[0]-b[1],a[1]-b[2],a[2]-b[3]]

I want to instead just put the base template: a[0]-b[1] and make it automatically fill say 50 places in the results array. So I don't always have to manually type it.

What would be the ways to do that? And would a good way be to create 1 method that does this automatically. And I just tell it the math and it fills out an array?

I have no clue, I'm really new to programming.

Upvotes: 2

Views: 157

Answers (2)

AnkitG
AnkitG

Reputation: 6568

Custom

  a = [2,3,4..............,1000]
  b = [1,2,3,4,.............900]

  class Array
   def self.calculate_difference(arr1,arr2,limit)
    begin
     result ||= Array.new
     limit.send(:times) {|index| result << arr1[index]-arr2[index+=1]} 
     result
   rescue
    raise "Index/Limit Error"
   end
  end
 end

Call by:

Array.calculate_difference(a,b,50)

Upvotes: 1

megas
megas

Reputation: 21791

a = [2,3,4]
b = [1,2,3,4]

results = a.zip(b.drop(1)).take(50).map { |v,w| v - w }

Upvotes: 4

Related Questions