Generate Random numbers without using any external functions

后端 未结 9 1008
梦如初夏
梦如初夏 2020-12-08 16:26

This was questions asked in one of the interviews that I recently attended.

As far as I know a random number between two numbers can be generated as follows

9条回答
  •  臣服心动
    2020-12-08 16:40

    You can do it without external functions if you are allowed to use some external state (e.g. a long initialised with the current system time). This is enough for you to implement a simple psuedo-random number generator.

    In each call to your random function, you would use the state to create a new random value, and update the state, so that subsequent calls get different results.

    You can do this with just regular Java arithmetic and/or bitwise operations, so no external functions are required.

提交回复
热议问题