Created
November 8, 2021 22:04
-
-
Save rgsingh/a387bf20c237f705307b47b5774b9094 to your computer and use it in GitHub Desktop.
Generates an array, copies it, shuffles the copy, joins them, adds a odd number and then finds the unpaired number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
import java.util.stream.IntStream; | |
class FindUnpairedOddValue { | |
public static void main(String[] args) { | |
int[] myArray = new int[100]; | |
int max = 300; | |
int min = 1; | |
if (max % 2 == 0) --max; | |
if (min % 2 == 0) ++min; | |
for (int i=1; i<100; i++) { | |
int randomOddNum = min + 2*(int)(Math.random()*((max-min)/2+1)); | |
myArray[i] = randomOddNum; | |
} | |
int[] result = copyShuffleAndJoin(myArray); | |
IntStream stream = IntStream.of(result); | |
stream.forEach(System.out::println); | |
int[] plusOneArray = new int[result.length + 1]; | |
plusOneArray[result.length] = 323; | |
int solutionResult = solution(plusOneArray); | |
System.out.println("solution: " + solutionResult); | |
} | |
public static int[] copyShuffleAndJoin(int[] input) { | |
Random random = new Random(); | |
int[] copy = new int[input.length]; | |
int[] result = new int[input.length + copy.length]; | |
for (int i = 0; i < input.length; i++) { | |
copy[i] = input[i]; | |
} | |
for (int i=0; i < copy.length; i++) { | |
int randomPosition = random.nextInt(copy.length); | |
int temp = copy[i]; | |
copy[i] = copy[randomPosition]; | |
copy[randomPosition] = temp; | |
} | |
System.arraycopy(input, 0, result, 0, input.length); | |
System.arraycopy(copy, 0, result, input.length, copy.length); | |
return result; | |
} | |
public synchronized static int solution(int[] A) { | |
int unpaired; | |
unpaired = A[0]; | |
for(int i=1; i< A.length; i++){ | |
unpaired = unpaired ^ A[i]; // xor | |
} | |
return unpaired; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment