Programming Geek
Rated 4.7/5 based on 1446 reviews  ### Code Gladiators 2015 Solution : Expert Level

Problem Statement
Problem

A Machine M1 takes a sequence of numbers as input and outputs another sequence. Let input sequence be x1,x2,………,xn. Difference x2-x1 is called 1st step difference, x3-x2 is called 2nd step difference ,………., xn-xn-1 is called (n-1)th step difference. Thus these step differences make a new sequence. So, machine M1 calculates these step differences and outputs this new sequence formed. If input sequence is of length 1 then it just outputs the input sequence. Now a new Machine M2 is formed which takes a sequence as input and uses this machine M1 and outputs a sequence. A flag value ‘ f ’ is associated with machine M2 which will be 0 or 1 or 2. Working of machine M2 is shown in the following figure: Input/Output Specifications
Input Specification

### Input Specification

Input should be sequence of numbers(string) which will be given as an input to machine M2.
Output Specification

### Output Specification

Output should be the valid output(string) of machine M2.
Example
Example

I am giving the way to find the answer for test case 1. Similarly you can check for the other test cases. You have to find just the step differences for each new sequence formed by machine M 1 untill you get the sequence of length 1 (i.e. a number), that number will be the output.

1       5       9      2       3       5      6
4       4      ‐7      1       2       1
0      ‐11     8       1     ‐1
‐11      19     ‐7     ‐2
30    ‐26      5
‐56      31
87

Input    : 1,5,9,2,3,5,6
Output : 87

Solution
Solution

### Algorithm

1) Make an array of input values, say inputArray.
2) while length of inputArray>1
i) for i=inputArray.length-1 to i=1
i.a)inputArray[i]=inputArray[i]-inputArray[i-1]
ii) Remove first element from inputArray
3) return inputArray

### JavaScript Solution

``````
function sequences(input1) {
var inputArray = input1.split(',').map(function(value) {
return parseInt(value);
});
while (inputArray.length > 1) {
for (var i = inputArray.length - 1; i > 0; i--) {
inputArray[i] = inputArray[i] - inputArray[i - 1];
}
inputArray.shift();
}
return inputArray;
}
``````
Only 6 test cases passed out of 10 test cases using JavaScript.

### Java Solution

```            ```
public static String sequences(String input1){
String[] inputArray =  input1.split(",");
while(inputArray.length>1){
for(int i=inputArray.length-1; i>0;i--){
inputArray[i]=''+(Integer.parseInt(inputArray[i])-Integer.parseInt(inputArray[i-1]));
}
inputArray=ArrayUtils.remove(inputArray,0);
}
return inputArray;
}
```
```
All 10 test cases passed using Java. Algorithm is same in both the language but results are varying.