在最近的一次采访中,我被问到以下问题:
Print random numbers from 1-100 using the given getrnd50() method
which generates the random numbers from 1-50. Each random number
should be printed only once and in random order. Use of no other random number generator
is allowed and i was not allowed to change the definition of
getrnd50().
我想出了以下代码,它给出了正确的输出.
import java.util.Random;
public class Test {
public static void main(String[] args) {
int[] rs = new int[100];
int count = 0;
int k;
while (count != 100) {
// I decided to simply multiply the result of `getrnd50()` by 2.
// But since that would generate only even numbers,
k = getrnd50() * 2;
// I decided to randomly subtract 1 from the numbers.
// Which i accomlished as follows.
if (getrnd50() <= 25) // 25 is to half the possibilities.
k--;
// Every number is to be stored in its own unique location
// in the array `rs`, the location is `(number-1)`.
// Every time a number is generated it is checked whether it has
// already been generated. If not, it is saved in its position, printed and
// `count` is incremented.
if (rs[k-1] == 0) {
rs[k-1] = k;
count++;
System.out.print(k + " ");
}
}
}
// This is the method and i am not supposed to touch it.
static int getrnd50() {
Random rand = new Random();
return (1 + rand.nextInt(50));
}
}
虽然它在那一轮被接受,但在下一轮中,面试官告诉我getrnd50()是一种昂贵的方法,即使在最好的情况下,我必须为每个生成的数字调用它两次.即1-100的200次.在最坏的情况下,它将是无限的,平均情况下数万.他要求我优化代码,以便显着改善平均情况.
当我表示无法做到时,他给了我一个暗示,他说:
To consider the number of numbers generated while generating a new
number. For ex. if count becomes 99 i don’t have to call getrnd50() I
can simply find the remaining number and print it.
虽然我理解他的漂移我不知道它会如何帮助我,所以显然我被拒绝了.现在我很想知道答案.帮我! Thanx提前!
注意:如果有人懒得写一个冗长的代码只是指出数字生成部分,其余的很容易.此外,我们不一定遵循提示.