Tripadvisor Interview Question

Give a range of numbers, return 6 different numbers randomly. In O(n).

Interview Answers

Anonymous

May 9, 2015

Suppose the range from 0 to 100 1- Create and initialize an array of 101 elements, filled from 0 --> 100 2- Set the max to be the last element in the array i.e max = 100 3- Get a random number between 0 and max. r= rand(0,max) 4- Replace array[r] with array[max] and decrease max by 1(max = max -1) 5- Repeat from step 3

4

Anonymous

Jul 10, 2015

public static void main(String[] args) { int max = 100; Integer[] nums = new Integer[max]; for (int i = 0; i < nums.length; i++) { nums[i] = i; } Collections.shuffle(Arrays.asList(nums)); for (int i = 0; i < 6; i++) { System.out.println(nums[i]); } }

1