Php随机填充范围 [英] Php random fill range
本文介绍了Php随机填充范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个:
$ numbers = range(1,52);
shuffle($数字);
foreach($ users为$ user){
$ uniqueRand = array_pop($ numbers);
这给我的数据库中的每个用户一个唯一的随机数。
我总共有15个用户,是否有可能填补1-32的范围内的其余部分,并重复随机说。 b
$ b
看起来像这样:
1 - 24
2 - 26
3 - 2
4 - 6
5 - 8
6 - 31
7 - 25
8 - 16
9 - 13
10 - 21
11 - 19
12 - 29
13 - 8
14 - 4
15 - 6
$ c $只有拥有随机数的用户,是否有可能给这些未分配给范围内的用户的号码再次随机地给一个用户,直到所有的号码在范围内给出?
解决方案
<?php
function f($ userIds,$ numbers)
{
shuffle($ numbers); //添加
$ picks = array();
$ b foreach($ userIds as $ id){
$ picks [] = array('id'=> $ id,'numbers'=> array());
}
//将userIds的顺序排序。给每个用户一个号码。重复这两个步骤
//直到所有数字都消失了
$ n = count($ userIds);
$ i = 0;
while(!empty($ numbers)){
if($ i%$ n === 0){
shuffle($ picks);
}
$ picks [$ i%$ n] ['numbers'] [] = array_pop($ numbers);
$ i ++;
}
返回$ picks; (1,2,3,4,9,12,47,50),range(1,30));
$ picks = f
$ b foreach($ picks as $ p){
printf(id%s:%s\\\
,$ p ['id'],implode(',',$ p [ '数字']));
}
会输出如下内容:
id 47:28,22,8,6
id 1:30,17,12,5
id 12:24,16,7, 4
id 9:23,19,13,3
id 50:25,18,14,2
id 3:27,15,9,1
id 4: 29,20,10
id 2:26,21,11
编辑: 。你也可能想把数字洗牌,以得到一个更随机的分布。将该行添加到函数中。
I have this:
$numbers = range(1,52);
shuffle($numbers);
foreach($users as $user) {
$uniqueRand = array_pop($numbers);
}
This give each user in my database a unique random number.
I have 15 users in total, is it somehow possible to fill the rest of the range from 1-32 and repeat the randoming so to say.
it looks like this now:
1 - 24
2 - 26
3 - 2
4 - 6
5 - 8
6 - 31
7 - 25
8 - 16
9 - 13
10 - 21
11 - 19
12 - 29
13 - 8
14 - 4
15 - 6
Just users with random numbers, is it possible the give those numbers which were not allocated to a user in the range again randomly a user until all numbers in the range are given?
解决方案 <?php
function f($userIds, $numbers)
{
shuffle($numbers); // added
$picks = array();
foreach ($userIds as $id) {
$picks[] = array('id' => $id, 'numbers' => array());
}
// Shuffle order of userIds. Give one number to each user. Repeat both steps
// until all numbers are gone
$n = count($userIds);
$i = 0;
while (!empty($numbers)) {
if ($i % $n === 0) {
shuffle($picks);
}
$picks[$i % $n]['numbers'][] = array_pop($numbers);
$i++;
}
return $picks;
}
$picks = f(array(1, 2, 3, 4, 9, 12, 47, 50), range(1, 30));
foreach ($picks as $p) {
printf("id %s: %s\n", $p['id'], implode(', ', $p['numbers']));
}
Will output something like:
id 47: 28, 22, 8, 6
id 1: 30, 17, 12, 5
id 12: 24, 16, 7, 4
id 9: 23, 19, 13, 3
id 50: 25, 18, 14, 2
id 3: 27, 15, 9, 1
id 4: 29, 20, 10
id 2: 26, 21, 11
Edit: Forgot something. You might want to shuffle() the numbers, too, to get a more random distribution. Added the line to the function.
这篇关于Php随机填充范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文