Programming Problem - Fast Number Pool Randomizer

Got this in an interview -
Create an optimized number pool randomizer with the following requirements:

  • Randomize a number from a given pool of numbers - O (1)
  • If the number has already been randomized, do not produce it again.
  • Hint: limited number of rooms
  • Reset pool of numbers to the full list - O (1) (I think this is the hard part)

Plus, what do you think of this as an interview? What level of developers should this be aimed at?

+3
source share
1 answer

Since there is a limited number of numbers, you can do the following (assuming, for example, valid identifiers 0..99)

  • When initializing for the first time, fill in an int array [100] with values ​​0..99
  • In reset (and initialization) set int endoflist = 100
  • When getting the identifier get index = rand ()% endoflist, decrement endoflist, swap array [index] with array [endoflist], return array [endoflist]
  • When the endoflist reaches 0, set it back to 100 (there is no need to replenish the array, it still contains ID 0..99)

IMO this question is suitable for nothing but really junior posts.

+5
source

Source: https://habr.com/ru/post/1793599/


All Articles