English 中文(简体)
以最有效的方式生成三个数字,三个数字都是不同的
原标题:Most efficient way to generate three numbers that are all different

我需要从1-9中各产生三个随机数字,每个数字必须与其他数字匹配。 我此时正在做这个脚本,下面的脚本很好,但想知道是否有其他更有效的方法来做这个?

$rndn1 = 0;
$rndn2 = 0;
$rndn3 = 0;
while ($rndn1 == $rndn2 || $rndn2 == $rndn3 || $rndn1 == $rndn3) {
  $rndn1 = rand(1,9);
  $rndn2 = rand(1,9);
  $rndn3 = rand(1,9);
}

此外,使用上文的简单表达方式可能会变得复杂,例如如果需要4个或4个以上的数字来经历同样的过程。

谢谢 谢谢

问题回答

从 1 - 9 建立数字随机变换, 然后选择第一个 3 个数字, 或者如果需要 4... 等...

http://en.wikipedia.org/wiki/Random_permutation#Knuth_shuffles

尝试使用此等格来创建变换 。

此解决方案可以在数字范围以及您需要选择的元素的qty 上进行缩放。 只要数字范围( 例如 1- 9) 是独特的, 此解决方案将不会给您选择的 3 个数字重复 。

你不需要每次生成三个数字

以下是第一步:

$rndn2 = 0;
$rndn3 = 0;
$rndn1 = rand(1,9);
while ($rndn1 == $rndn2 || $rndn2 == $rndn3 || $rndn1 == $rndn3) {
  $rndn2 = rand(1,9);
  $rndn3 = rand(1,9);
}

显然你可以做更多的事情:

$rndn1 = rand(1,9);
$rndn2 = rand(1,9);
while ($rndn1 == $rndn2) {
 $rndn2 = rand(1,9);
}
$rndn3 = rand(1,9);
while ($rndn2 == $rndn3 || $rndn1 == $rndn3) {
  $rndn3 = rand(1,9);
}

切勿试图在没有特征描述的情况下优化太多。 这通常是不需要的。 唯一代价昂贵的操作是兰特操作: 这是您必须最小化的操作( 所以在测试之前不要生成更多数字, 如果您只是寻找3个数字( 问题会不同) ) 。





相关问题
Find the closest time from a list of times

So, here s the scenario. I have a file with a created time, and I want to choose a time from a list of times that that file s created time is closest or equal too...what would be the best way to ...

PHP Comparison Operators and Data Types

I m currently working through O Reilly s "Programming PHP" and have come across this table titled "Type of comparison performed by the comparison operators": First Operand | Second ...

Loop Until Condition Reached, iPhone

I have a problem here... After a button is pressed I want a loop to run until a condition is reached: - (IBAction)buttonclick1 ... if ((value2ForIf - valueForIf) >= 3) { ... I would like a loop ...

nuSoap or Zend Soap? [closed]

I would like to know the differences between nusoap and ZendSoap, which is the best? what benefits and disadvantages of each? Anyone who has used both technologies could make this comparison? Thank ...

Logic for a file compare

I trying to write a programm for file compare. For example: file1 1 2 3 4 5 file2 1 2 @ 3 4 5 If I do it line by line, I get: 1 == 1; 2 == 2; 3 != @; 4 != 3; 5 != 4; != 5; But, the truth is ...

热门标签