I have answered the following kata: Lost number in number sequence. The description is:
"An ordered sequence of numbers from 1 to N is given. One number might have deleted from it, then the remaining numbers were mixed. Find the number that was deleted.
Example:
The starting array sequence is [1,2,3,4,5,6,7,8,9]
The mixed array with one deleted number is [3,2,4,6,7,8,1,9]
Your function should return the int 5.
If no number was deleted from the array and no difference with it, your function should return the int 0.
Note that N may be 1 or less (in the latter case, the first array will be [])."
I have written a simple answer:
import java.util.*;
public class Kata {
public static int findDeletedNumber (int[] arr, int[] mixedArr) {
Arrays.sort(mixedArr);
for(int i = 0; i < arr.length; i++){
try{
if(arr[i] != mixedArr[i]){
return arr[i];
}
}catch(ArrayIndexOutOfBoundsException e) {
return arr[i];
}
}
return 0;
}
}
I was reading other people's answers and I found one which I find very hard to understand deeply:
import java.util.Arrays;
public class Kata {
public static int findDeletedNumber(int[] arr, int[] mixedArr) {
return Arrays.stream(arr).reduce((a, b) -> a ^ b).orElse(0) ^ Arrays.stream(mixedArr).reduce((a, b) -> a ^ b).orElse(0);
}
}
The link to the answer: https://www.codewars.com/kata/reviews/595be553429e11365c00006f/groups/59bef3a1eda42eb0bc001612
I would like to have some help, if anyone cares and have the patience to write an explanation and/or a trace, would be helpful. Currently I can see the answer but I do not understand it.
In addition I have tried to understand it by myself reading: What does the ^ operator do in Java? https://www.geeksforgeeks.org/bitwise-operators-in-java/