我需要在一个范围内生成随机的UNIQUE数字吗?怎么做 ?
我可以生成随机数
generator:
$arr=array();
$x=rand($min,$max);
$len=count($arr);
$flag = 0;
for($i=0;$i<$len;$i++)
{
if ($flag == 1)
goto generator;
if ($x == $arr[$i])
$flag = 1;
}
$arr[$index] = $x;
$index++;
goto generator;
Run Code Online (Sandbox Code Playgroud)
我知道这段代码很糟糕,所以我需要一个更好的我的版本优化代码!救命 !
例如:如果我需要在1到15之间生成3个数字,它们应该像5,9,1但不是3,1,2 [在1-3中(我想要生成的数字)]
我只是想知道,如果你绘制5位数字,mt_rand()数是多么独特?在这个例子中,我试图用这个函数得到500个随机数的列表,其中一些是重复的.
http://www.php.net/manual/en/function.mt-rand.php
<?php
header('Content-Type: text/plain');
$errors = array();
$uniques = array();
for($i = 0; $i < 500; ++$i)
{
$random_code = mt_rand(10000, 99999);
if(!in_array($random_code, $uniques))
{
$uniques[] = $random_code;
}
else
{
$errors[] = $random_code;
}
}
/**
* If you get any data in this array, it is not exactly unique
* Run this script for few times and you may see some repeats
*/
print_r($errors);
?>
Run Code Online (Sandbox Code Playgroud)
可能需要多少位数才能确保循环中绘制的前500个随机数是唯一的?
到目前为止还没有找到我想要的东西,所以我寻求帮助。
我有一个 div ,其类需要以 1 到 8 之间的数字结尾,并且我需要它是一个随机数,而不重复...
<div class="parallax parallax_<?php echo $random_number ?>"></div>
Run Code Online (Sandbox Code Playgroud)
我认为这应该很简单,但我遇到了麻烦。
目前,我有:
<div class="parallax parallax_<?php echo rand(1, 8); ?>"></div>
Run Code Online (Sandbox Code Playgroud)
它有效,但会产生重复项。
编辑
因此,经过测试,我意识到我遇到了问题。我在 WordPress 模板中使用它。我正在查询一组 6 个帖子,对于每组帖子,我都包含上面的视差 div。因此,我为每个查询得到一个随机的、不重复的数字,但每个查询都会重置数字 - 给我重复的数字......这是我的整个代码。
<?php
$args = array(
'post_type' => 'post',
'orderby' => 'menu_order',
'posts_per_page' => -1,
'order' => 'ASC'
);
$posts = get_posts( $args );
?>
<?php foreach (array_chunk($posts, 6, true) as $posts) : ?>
<div class="parallax parallax_<?php echo rand(1, 8); ?>"></div>
<div class="posts_container">
<?php foreach( $posts as $post ) …Run Code Online (Sandbox Code Playgroud) 可能重复:
O(1)中的唯一随机数?
我是Java新手.我想从给定的集合中生成一组随机数,并且数字也必须不重复.例如,可能的数字是[0,1,2,3],我想获得存储在数组中的三个随机唯一数字.防爆.[0,2,1], [2,3,1], [0,3,2]等等
我想在数组中添加5个随机数,但每个数字必须不同.这是我到目前为止所拥有的......
$col_B = array();
for ($i=1; $i < 6; $i++) {
$rand = $col_ranges['B'][rand ( 0 , 14 )]; // calls to an array of numbers
if(!in_array($rand, $col_B)){
$col_B[] = $rand;
}
else{ $i - 1;}
}
echo implode($col_B, '<br>');
Run Code Online (Sandbox Code Playgroud)