使用C生成无重复的随机数列表?

我正在制作一个益智游戏,我想生成一个限制之间的随机数列表。 我已经使用了rand和srand函数,但它也给了我重复的值。 我想生成一个没有重复的随机列表我该怎么做?

通常的方法是这样的:

populate an array source_array of size  with numbers from 0 to n-1 while n > 0 use rand to generate a random number x in the range 0..n-1 add source_array[x] to the result list source_array[x] = source_array[n-1]; // replace number just used with last value --n; // next time, one less number 

我假设你使用数组存储数字,你可以使用这样的 inArray()函数,并将它与do ... while循环一起使用,它会生成一个随机数,直到它生成一个不在排列

编辑: w00te的评论链接到这个答案,我认为这比我的方法更好,绝对值得一读。 这也是David Gelhar简要建议的内容。

当限制很高并且您只想生成一些随机数时,此方法适用。

 #!/usr/bin/perl ($top, $n) = @ARGV; # generate $n integer numbers in [0, $top) $last = -1; for $i (0 .. $n-1) { $range = $top - $n + $i - $last; $r = 1 - rand(1.0)**(1 / ($n - $i)); $last += int($r * $range + 1); print "$last ($r)\n"; } 

请注意,这些数字是按升序生成的,但您可以随后进行随机播放。

为避免重复,您可以将所有生成的数字存储在列表中,并在每次迭代时检查数字是否已生成; 如果是,则重新生成,如果不将其添加到列表中并显示它。

你可以这样做:

 #include  #include  #define MAX_NUMBER_VALUE 60 #define HOW_MANY_NUMBERS 10 int main ( void ) { int numbers[HOW_MANY_NUMBERS]; int counter = 0; while ( counter < HOW_MANY_NUMBERS) { int tempRandom = rand ( MAX_NUMBER_VALUE + 1 ); int check = 0; while ( check <= counter ) { if ( number[counter] == number[check] ) tempRandom = rand ( MAX_NUMBER_VALUE + 1 ); } printf("Random number #%d - Value: %d", counter, tempRandom); } } 

你需要执行此操作,但它可以工作。