• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
Bartender
Posts: 5465
212
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Bartender
Posts: 5465
212
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But then, that could be simplified to:
reply
    Bookmark Topic Watch Topic
  • New Topic