php中的随机洗牌?

发布于 2024-12-02 10:46:20 字数 449 浏览 0 评论 0原文

我正在创建一个彩票来将人们配对。所以我想要一种方法来随机排列数组中的字符串,其中没有项目最终出现在同一位置。 (你无法与自己配对)

    public function shuffleSantas(){
    $query = $this->db->get('person');
    $givers = array();
    $recievers = array();
    foreach($query->result() as $row):          
        $givers[] = $row->name;
        //here i want a random order, but no name can be on the same place as in $givers!
        $recievers[] = '';
    endforeach;

I'm creating a lottery to pair up people. So I want a way to shuffle the strings in an array where no item ends up on the same place. (You can't pair up with yourself)

    public function shuffleSantas(){
    $query = $this->db->get('person');
    $givers = array();
    $recievers = array();
    foreach($query->result() as $row):          
        $givers[] = $row->name;
        //here i want a random order, but no name can be on the same place as in $givers!
        $recievers[] = '';
    endforeach;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

陌伤ぢ 2024-12-09 10:46:20

将数组打乱一次,然后将第一个元素与第二个元素配对,第二个元素与第三个元素配对,等等,最后一个元素与第一个元素配对。

shuffle the array once and then pair up the first element with the second, the second with the third etc. and the last with the first.

空城旧梦 2024-12-09 10:46:20
$src = $query->result();
$givers = array();
$receivers = array();
foreach ($src as $idx=>$first_person){
    $count = 0; //infinite loop guard
    do{
        ++$count;
        $sec_idx = rand(0,count($src)-1);
        $second_person = $src[$sec_idx];
    } while ($second_person==$first_person && $count<5); 
    $givers[] = $first_person;
    $receivers[] = $second_person; 
}

在这种情况下,一个人将能够从一个人那里获得并给予另一个人。可以吗?而且这个算法也不是最优的,如果数组中只有一个人,肯定会陷入无限循环。

$src = $query->result();
$givers = array();
$receivers = array();
foreach ($src as $idx=>$first_person){
    $count = 0; //infinite loop guard
    do{
        ++$count;
        $sec_idx = rand(0,count($src)-1);
        $second_person = $src[$sec_idx];
    } while ($second_person==$first_person && $count<5); 
    $givers[] = $first_person;
    $receivers[] = $second_person; 
}

In this case one will be able to receive from one person and to give to other person. Is it OK? Also, this algorithm is not optimal and will definitely fall into infinity loop if there is only one person in an array.

作妖 2024-12-09 10:46:20

如果认为 PHP 中没有内置函数可以以这种方式进行洗牌。您必须编写自己的函数。

If think there is no built-in function in PHP to shuffle that way. You have to write your own function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文