kirqe
kirqe

Reputation: 2470

Multiply every 3rd element in the existing array

How to multiply every 3rd element in the existing array.

The code below gives me the following output [6, 12, 18, 24] as expected.

But how to update values in myArr without creating new array: [1,2,6,4,5,12,7,8,18,10,11,24,13,14]

myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]

res = myArr[2].step(myArr.length-1, 3).map{|val| val*2}

Upvotes: 0

Views: 87

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110675

arr = [1,1,1,1,1,1,1,1,1]
factor = 2
every = 3

((every-1)...arr.size).step(every) { |i| arr[i] *= factor }
arr #=> [1,1,2,1,1,2,1,1,2]

Another way:

mult = ([1]*(every-1)).push(fac).cycle
  #=> #<Enumerator: [1,1,2].cycle>
arr.map! { |e| e*mult.next }
  #=> [1,1,2,1,1,2,1,1,2]

Upvotes: 1

sawa
sawa

Reputation: 168081

myArr.each_index{|i| myArr[i] *= 2 if i% 3 == 2}

Upvotes: 2

Mihails Butorins
Mihails Butorins

Reputation: 918

Just one more solution in addition to Paul's answer:

myArr.map!.with_index{|k,i| i % 3 == 2 ? k * 2 : k }

Upvotes: 1

Paul A Jungwirth
Paul A Jungwirth

Reputation: 24541

Looks like this does it:

0.upto(myArr.length - 1) {|i| myArr[i] *= 2 if i % 3 == 2}

Upvotes: 1

Related Questions