views:

282

answers:

6

Lets say I have the following array:

my_array = [1, 5, 8, 11, -6]

I need to iterate over this array and add the values prior to the current value together. An example will probably be easier to understand. I need to return an array that should look something like this:

final_array = [1, 6, 14, 25, 19]

I have tried doing something like this:

my_array.collect {|value| value + previous_values }

But obviously that doesn't work because I can't figure out how to get the previous values in the array.

I am a programming noob so this might be easier than I am making it. I am pretty sure I need to use either collect or inject, but I can't seem to figure out how to do this.

Any help would be appreciated.

+1  A: 
my_array.each_index{|i| my_array[i] += my_array[i-1] if i>0 }

or

my_array.inject([]){|memo, item| memo << item + memo.last.to_i }
Draco Ater
inject is unlikely to work as memo.last will return nil initially.
Anton
Yes, you are right. I thought it will convert automatically to int, but no, so added explicitly `to_i`.
Draco Ater
Seems unnecessarily complex having to make a special case of the first element in both solutions.
Arkku
@Arkku Actually it is necessary to add `if i>0` in first solution, because otherwise `my_array[i-1]` will be `my_array[0-1] = my_array[-1]`, which is last element of array.
Draco Ater
@Draco After: Yes, I know, that's why it seems unnecessarily complex; the first element becomes a special case.
Arkku
+2  A: 
x = 0
[1, 5, 8, 11, -6].map {|a| x = x +a }
Anton
A: 

You can use this:

my_array = [1, 5, 8, 11, -6]
final_array = []

my_array.inject(0) {|res, it| final_array << res + it; res + it}
Yossi
+2  A: 

Your own attempt at it with collect was already very close; just keep summing the previous values as you go.

my_array = [1, 5, 8, 11, -6]
previous_values = 0
my_array.collect { |value| previous_values += value }
# => [1, 6, 14, 25, 19]
Arkku
+5  A: 
Jörg W Mittag
A: 

Unfortunately I don't know this programming language so I write in Java. If you have some questions just post here.

public class newArray{

    public static void main(String[]args){
        int my_array[] = new int[]{1,5,8,11,-6};
        int final_array[] = new int[my_array.length];
        final_array[0] = my_array[0];

        for (int i=1; i<final_array.length; i++) {
            final_array[i] = my_array[i]+final_array[i-1];
        }

        for (int i=0; i<final_array.length; i++) {
            System.out.println(final_array[i]);
        }
    }
}

Output:

1
6
14
25
19