HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Single value computation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
computationsinglevalue

Problem

I'm writing code to compute a single value answer to a given numbers in integer array such that step sum is calculated till only 1 number is left.

For example:

Input:

3,5,2,6,7


Output is computed as:

(3+5)+(5+2)+(2+6)+(6+7)


It remains like this till I only have a single number left.

3   5   2   6   7
  8   7   8  13
   15  15  21
     30  36
       66


`int inputarray={3,5,2,6,7};
int inputlength=inputarray.length;
while(inputlength!=0)
{
for(int i=0;i

It computes the result in quadratic growth. Is there any way to compute my result more efficiently? What else can I do to improve it?

Solution

First of all it is always helpful to format your code properly (I now used the default code convention for Java):

int inputarray={3,5,2,6,7};
int inputlength=inputarray.length;
while (inputlength != 0) {  
    for (int i = 0; i < inputlength-1; i++) {
        inputarray[i] = inputarray[i+1] + inputarray[i];      
    }
    inputlength--;
}
System.out.println(inputarray[0]);


Also it is better to test for inputlength < 0 because then the termination of the loop is much more likely...

For performance tuning:

Try to create a formula for your problem to calculate the result. Your example could be reduced to 3 + 45 + 62 + 4*6 + 7...

Find a formula such like Gauss did for summing up the parts...

Code Snippets

int inputarray={3,5,2,6,7};
int inputlength=inputarray.length;
while (inputlength != 0) {  
    for (int i = 0; i < inputlength-1; i++) {
        inputarray[i] = inputarray[i+1] + inputarray[i];      
    }
    inputlength--;
}
System.out.println(inputarray[0]);

Context

StackExchange Code Review Q#86845, answer score: 3

Revisions (0)

No revisions yet.