Tripadvisor Interview Question: Give a range of numbers, retu... | Glassdoor.ie

Interview Question

Senior Software Engineer Interview Dublin, Co. Dublin

Give a range of numbers, return 6 different numbers

  randomly. In O(n).
Answer

Interview Answer

3 Answers

3

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

Ahmad Bakr on 9 May 2015
0

As this question is usually posed, there is an additional constraint: the numbers are presented in a stream, and you do not have enough memory to store them all.

a hiring manager on 21 May 2015
0

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]);
        }

    }

Anonymous on 10 Jul 2015

Add Answers or Comments

To comment on this, Sign In or Sign Up.