doushan2311 2018-11-28 08:06
浏览 80

在阵列中随机对,但不包括对可能性

I wish to create a small script to generate a pair of users.

Users are in an array so I use shuffle to pair them randomly.

My problem is I want to avoid/exclude some pair of users in the final result.

So I have the first part to shuffle users :

<?php 

$user[] = "Miaa";
$user[] = "Xavier";
$user[] = "Antoine";
$user[] = "Marie-Ange";
$user[] = "Claire";
$user[] = "Orlando";
$user[] = "Camille";
$user[] = "Chloé";
$user[] = "Audrey";
$user[] = "*";

$users = count($user);
// Shuffle user
shuffle($user);// You get a shuffled array

// Pair the adjacent user
for ( $index = 0; $index < $users; $index +=2) {

    // Pair $user[$index ] with $user[$index +1]
    echo $user[$index ] . " <=> " . $user[$index+1] . "
";
}

?>

Here it's a link with my code into a sandbox => http://sandbox.onlinephpfunctions.com/code/6ef04e99946849606544493e64e317206209c10c

I tried to include an if statement but without success

$user[$index[0]] == "Miaa" && $user[$index[1]] == "Xavier"
  • 写回答

3条回答 默认 最新

  • dongyongju9560 2018-11-28 08:39
    关注

    u can get all the combinations and then get it via random key:)

    <?php
    $user[] = "Miaa";
    $user[] = "Xavier";
    $user[] = "Antoine";
    $user[] = "Marie-Ange";
    $user[] = "Claire";
    $user[] = "Orlando";
    $user[] = "Camille";
    $user[] = "Chloé";
    $user[] = "Audrey";
    $user[] = "*";
    
    $shufla = [];
    
    foreach ($user as $us1) {
        foreach ($user as $us2) {
            if (
                ("Miaa" === $us1 and "Xavier" === $us2) ||
                ("Miaa" === $us2 and "Xavier" === $us1) ||
                ($us1 === $us2)
            ) continue;
            $shufla[] = $us1 . " <=> ". $us2;
        }
    }
    
    var_dump($shufla[mt_rand(0, count($shufla) - 1)]);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入