• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

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

 
Ranch Hand
Posts: 419
Mac jQuery Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 64680
225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Netbeans IDE Opera Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: 3297
146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 3297
146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But then, that could be simplified to:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!