Search code examples
javaarraysencodingsumdecoding

Decode Simple Encoded Array in Java


I have an encoded array in Java, and I need to find the first number and the sum of all numbers in the original array based on the encoding rules. The encoding used is as follows:

  • Each array element has been substituted with a value that is the difference of its original value and its succeeding element’s value.
  • The value in arr[i] = arr[i+1] - arr[i]
  • For example, if the original array is {2, 5, 1, 7, 9, 3}, the encoded array would be {3, -4, 6, 2, -6, 3}.

I tried the following code, and it's giving the wrong output. Can someone please help me identify the issue?

class Result {
    int output1;
    int output2;

    public Result(int output1, int output2) {
        this.output1 = output1;
        this.output2 = output2;
    }
}

public class EncodedArray {

    public static Result findOriginalFirstAndSum(int[] input1) {
        int[] res = new int[input1.length];
        res[res.length - 1] = input1[input1.length - 1];
        for (int i = input1.length - 1; i > 0; i--) {
            res[i - 1] = input1[i - 1] - res[i];
        }

        int sum = 0;
        for (int item : res) {
            sum += item;
        }

        return new Result(res[0], sum);
    }

    public static void main(String[] args) {
        int[] encodedArray = { 3, -4, 6, 2, -6, 3 };
        Result result = findOriginalFirstAndSum(encodedArray);

        System.out.println("First number in original array: " + result.output1);
        System.out.println("Sum of all numbers in original array: " + result.output2);
    }
}

The output I'm getting is:

First number in the original array: -3
Sum of all numbers in the original array: 12

The expected output should be:

First number in the original array: 2
Sum of all numbers in the original array: 27

Any help or suggestions on how to fix the code would be greatly appreciated. Thank you!


Solution

  • You made a mistake in writing here enter image description here

    The correct calculation method is as follows

     res[i - 1] =  res[i] - input1[i - 1] ;