Win a copy of Transfer Learning for Natural Language Processing (MEAP) this week in the Artificial Intelligence and Machine Learning forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Tim Cooke
• Paul Clapham
• Devaka Cooray
• Bear Bibeault
Sheriffs:
• Junilu Lacar
• Knute Snortum
• Liutauras Vilda
Saloon Keepers:
• Ron McLeod
• Stephan van Hulst
• Tim Moores
• Tim Holloway
• Piet Souris
Bartenders:
• salvin francis
• Carey Brown
• Frits Walraven

# Best way of creating array from existing array using a[n] = a[n] + a[n-1].

Ranch Hand
Posts: 419
Hi,

I am not sure what should be the subject of this problem I have tried to put something meaningful. here is a problem:

I have an array a = [1,2,3,4,5,6]. I want to create a new array which should be something like a[n] = a[n] + a[n-1]. So for this array the result will be [1,3,6,10,15,21]. I am doing it in a very simple way by creating a new array. Is there any other tricky way of doing it? I am actually using ruby but I think it doesn't matter.

Thanks.

Marshal
Posts: 68914
275
You are summating triangular numbers. Why not clone the array and iterate the clone starting from arrCopy[1]?

There is bound to be a way to get a Stream and iterate it.
Arrays.asList(myArray).stream()....

Map place to sum to date and collect to an array?

Bartender
Posts: 5167
11

Campbell Ritchie wrote:There is bound to be a way to get a Stream and iterate it.

With the help of something I learned in this thread:

Saloon Keeper
Posts: 3900
154
Although a nice solution using streams, it has some drawbacks.

1) for each mapping, it calculates the complete partial sum, which is ineffectieve

This could be countered by:

2) which brings me to the next point:

it is a complicated way to get such a simple problem done.
The fact that Java8 has streams and lambda's does not mean we HAVE to use these things,
no matter what.

Edit: changed the text somewhat.

Piet Souris
Saloon Keeper
Posts: 3900
154
But then, that could be simplified to:

 That is a really big piece of pie for such a tiny ad: Two software engineers solve most of the world's problems in one K&R sized book https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton