Shuffle logic int array access data randomly Java
This question was asked during Amazon interview where interviewer wanted to write full implementation using java and details question was below:
- Can you write shuffle logic for int array value and access its data randomly in java ?
ShuffleArray.java:
package com.javahonk.javatoxml; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class ShuffleArray { public static void main(String args[]) { int[] intArray = { 6, 17, 55, 99, 13, 12, 11, 5, 15, 25, 2, 8,7 }; shuffleIntArray(intArray); System.out.print("Shuffle value:--> "); for (int i = 0; i < intArray.length; i++) { System.out.print(intArray[i] + " "); } } private static void shuffleIntArray(int[] array) { Random random = ThreadLocalRandom.current(); for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); int a = array[index]; array[index] = array[i]; array[i] = a; } } }
- Output:
For more information on Shuffle logic please refer Oracle documentation logic here