Barlet South
Barlet South

Reputation: 17

How to add two arrays in java for each iteration and then save the content of the array

Let's say I have a method like this:

public byte[] generateCoefficientsOfPolynomials(int k ,byte [] file,Random rnd) {

    for (int i=0;i<file.length;i++) {
        // for each iteration it creates a vector of size 3
    }

    // some other code here  

    // here we call the method below where allRndCoefficients is each
    // array taken from this method for instance [12,13,-20] and so on
    con.sumOfCoefficients(allRndCoefficients, k);

    // return type here
}

What I will get from this method will be something like those arrays: For the first iteration [12,13,-20], for the second iteration [123,-25,-56] and so on.

Note: Those arrays have random values since I have used rnd.nextBytes(k);, where k is the number of elements in the array.

Now what I want to achieve is to add those arrays element by element together. let say [12,13,-20] to add with [123,-25,56] and save the result. Then this result we saved we want to add with the array which will be produced by third iteration of the above method.

I wrote the following code to accomplish this:

public byte[] sumOfCoefficients(byte [] temp,int k) {
    galoaField256 d = new galoaField256 (); // create new reference 
    d.setGeneratorPolynom(3);
    d.getGeneratorPolynom();
    d.setString("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
    d.getString();
    d.loadExp();
    d.loadLog();
    byte [] initialSum=new byte [k];
    for(int i=0;i<k;i++) {
        initialSum[i]=(byte)d.add(initialSum[i],temp[i]);
    }

    System.out.println("The sum is" +Arrays.toString(initialSum));

    return initialSum;
}

where byte[] temp is the arrays we take after each iteration of the first method generateCoefficientsOfPolynomials.

Unfortunately, the sumation of two vectors is not done here. What i got are exactly the arrays which are produced by the first method meaning that every time we add the array taken from first method whit an array of 0 elements, so the initialSum array does not save its state for each iteration of the first method. Can anyone save my day and tell me what is wrong with my code?

Upvotes: 1

Views: 127

Answers (1)

Parfait
Parfait

Reputation: 107577

Currently, your initialSum[i] loop calculation is defining a blank array element and adding that blank element to temp[i] with each iteration and not last element. Consider conditionally handling the cumulative summation and notice the use of [i-1] index to capture last element value:

for(int i=0; i<k; i++) {

     if (i==0) { 
          initialSum[i] = temp[i];
     } else {
          initialSum[i] = (byte)d.add(initialSum[i-1],temp[i]);
     }

}

Upvotes: 1

Related Questions