I've been hitting my head against the wall for a while now...
The problem asks me to formulate this differentiation rule, applied to a byte array (the source should be overwritten), recursively, starting at the end of the array (derive.length - 1) and moving towards i=0. No second array should be used and the input-array should be overwritten. Below is the iterative version.
public static void derivative(byte[] derive) {
for (int i = derive.length - 1; i > 0; i--) {
if (i == 0 && derive[0] == 0) {
derive[0] = 0;
}
if (i > 0 && derive[i] == derive[i-1]) {
derive[i] = 0;
}
else {
derive[i] = 1;
}
}
The algorithm in question applies the following ruleset to an array of binary numbers such as [1,0,1,1]: a[i] (the output version) should be equal to:
- 0 if i=0 and a[i]=0
- 0 if i>0 and a[i]=a[i-1]
- 1 else
For example: {1,0,1,0,0} becomes: {1,1,1,1,0} and {0,1,1,0} becomes: {0,1,0,1}
How can I express this recursively?