Home >Backend Development >PHP Tutorial >用最短的代码 生成两个不相等的随机数

用最短的代码 生成两个不相等的随机数

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-06 20:42:451036browse

以1到100为固定区间

生成两个数 尽量不用递归

回复内容:

以1到100为固定区间

生成两个数 尽量不用递归

inspired by @finallygo

<code>$range = range(1,100);
</code>

1,

<code>shuffle($range);
$first = $range[0];
$second = $range[1];
</code>

2,

<code>list($first, $second) = array_rand($range,2);
//array_rand return index which starts from 0
$first++; $second++;
</code>

php语法不懂, 不过可以先生成两个随机数,两个相减作为第一个数, 相加作为第二个数

楼主应该是系统用php实现吧(以下代码需要在php 5.3以上版本支持)

<code class="lang-php">  1 <?php 2         $a = new SplDoublyLinkedList();
  3         for($i=1;$i<=100;$i++) {
  4                 $a->push($i);
  5         }
  6         $fetch_size = 2;
  7         for($j=0;$joffsetGet($index) . "\n";
                    $a->offsetUnset($index);
 10         }
 11 ?>

</code>

<code>Random rnd = new Random();
int a, b;
a = rnd.Next(100) + 1;
b = rnd.Next(99) + 1;
if (a == b) b = 100;
Console.WriteLine("{0} {1}", a, b);
</code>

<code>Random rnd = new Random();
var arr = Enumerable.Range(1, 100).OrderBy(t => rnd.Next()).Take(2).ToArray();
Console.WriteLine("{0} {1}", arr[0], arr[1]);
</code>

<code>var a, b; a = Math.random(); do{ b = Math.random(); } while(b == a)
</code>

任意数列都可以叫做“随机数列”,区别只是概率分布不同,既然题主没提分布,我只能假设题主不在乎:
$a=1; $b=2;
完全满足题主需求。

楼上太取巧啦。还是我来个吧

cat /dev/random

http://zh.wikipedia.org/zh-cn//dev/random

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn