【问题标题】:Trying to set value using shuffle尝试使用随机播放设置值
【发布时间】:2015-04-29 18:06:29
【问题描述】:

好的,这是我的问题。我有一个名字数组。我想以随机顺序设置一个名称指向另一个名称的位置。但没有任何名称指向自己。我希望每个值都指向一个不同的值,并且每个值只指向一个值,而不是它本身。 希望我能想到一个更好的表达方式。这是我目前使用的方法

    while($xcount>=1){
        $orderarray[($xcount-1)]=$xcount;
        $xcount--;
    }
    shuffle($orderarray);

问题是我不希望 $orderarry[$x] 等于 [$x] 这似乎几乎每次都会发生。有没有办法做到这一点。

无论如何,我试图虚拟地做当一群人都把他们的名字放在帽子里,然后每个人从帽子里挑选一个名字时会发生什么。就像一个秘密的圣诞老人。

【问题讨论】:

  • 假设你有 [1,2,3,4] 得到 12,21,34,43 合法吗?
  • 这不会发生,因为您可以看到我使用 $xcount 变量将值从 1 设置为数组的大小。所以它会出现 1, 2, 3, 4, 5 ... 等。
  • 那么,请在问题示例中添加输入输出数据。

标签: php arrays logic shuffle


【解决方案1】:

试试这个

$names = [1, 2, 3, 4, 5];
shuffle($names);
while (key($names) !== null)
    {
    $current = current($names);
    $next = next($names);
    if ($next) // is not last
        $bonds[] = [$current, $next];
    }
$bonds[] = [end($names), reset($names)]; // last
var_dump($bonds);

【讨论】:

  • 这会创建一个数组数组,这对我的问题没有帮助。
【解决方案2】:

使用以下代码解决了这个问题,方法是获取一个随机数并确保该数字未被使用且未指向自身。

    $neworder=array();
    $xcount=count($gmemberarray);
    //fill the array with numbers and a setting of false *hasn't been used*
    while($xcount>=1){
        //$orderarray[($xcount-1)]=arrray();
        $orderarray[($xcount-1)][0]=($xcount-1);
        $orderarray[($xcount-1)][1]=false;
        $xcount--;
    }
    $xcount=count($gmemberarray);
    $count=$xcount;
    while($xcount>=1){
        R:
        $randnum=rand(0, ($count-1));
        if($orderarray[$randnum][1]==true) //If it's already been used get a different number
            goto R; //otherwise try again
        if($xcount!=$randnum){ //if it's not equal to itself
            $neworder[($xcount-1)]=$randnum;
            $orderarray[$randnum][1]=true;
            echo "<br><br>Neworder ".$xcount.": ".$neworder[($xcount-1)];
        }
        else
            goto R; //otherwise try again
        $xcount--;

    }

输入数据为:

    orderarray[1]=1
    orderarray[2]=2
    orderarray[3]=3
    orderarray[4]=4

我希望的输出示例是:

    orderarray[1]=3
    orderarray[2]=4
    orderarray[3]=2
    orderarray[4]=1

【讨论】:

  • 让我看看输入和输出数据的例子。
猜你喜欢
  • 2012-12-16
  • 1970-01-01
  • 2023-01-23
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多