找到交换卡的所有可能方法

Эџa*_*мaи 5 php algorithm

我正在开发一个PHP应用程序,它可以找到所有交换卡的方法.每个用户至少有一张卡.当用户请求一张卡片时,该应用程序会向他显示所有可能的方法来交换他的卡片,以获取他所要求的卡片.

让我们说:

user 1 has card type A
user 2 has card type B 
user 3 has card type C 
Run Code Online (Sandbox Code Playgroud)

我们假设:

user 1 wants card type C
user 2 wants card type A
user 3 wants card type B
Run Code Online (Sandbox Code Playgroud)

如果用户1请求卡C,唯一的解决方案是:

user 1 gives user 2 his card
user 2 gives user 3 his card
user 3 gives user 1 his card
Run Code Online (Sandbox Code Playgroud)

但是,如果还有其他两个用户呢:

user 4 has card type B & wants card type A
user 5 has card type C & wants card type B
Run Code Online (Sandbox Code Playgroud)

现在,如果用户1请求卡C,除了上面的那个之外还有另一个解决方案是:

user 1 gives user 4 his card
user 4 gives user 5 his card
user 5 gives user 1 his card
Run Code Online (Sandbox Code Playgroud)

用户可拥有或请求的卡数量没有限制.到目前为止,我创建了两个SQL表.表"cards"跟踪每个userID和cardID.表"请求"跟踪每个用户ID和所需的cardID.

Cli*_*ote 1

我不会为此使用纯 PHP。相反,我会创建一个 MySQL 表,为每个用户存储一条记录,记录该用户拥有哪张卡以及他想要哪张卡。然后,我会运行这样的事情:

$sql = "SELECT * FROM users";
$result = $this->db->query();
$users = $result->getAll(); //A list of all the users.

foreach ($users as $user)
{
   $sql = "SELECT * FROM users WHERE cardId = '$user->wantedCardId'";
   $result = $this->db->query($sql);

   if (! $result->has_rows())
   {
      echo "No other users with $user->wantedCardId were found.";
      continue;
   }

   $cardHolder = $result->row();
   echo: "User $cardHolder->id gives $user->id his card";
}
Run Code Online (Sandbox Code Playgroud)

如果我使用纯 PHP 来执行此操作,我会执行以下操作:

//Populate an array containing a list of all the users and their cards.

$users = array();

$user[1] = new StdClass();;
$user[1]->cardId = 2;
$user[1]->wantedId = 3;

$user[2] = new StdClass();
$user[2]->cardId = 3;
$user[2]->wantedId = 2;
// .....

foreach ($users as $userId=>$user)
{
   //Run a secondary loop through the users to find those that have the card that
   //this user wants.
   foreach ($users as $holderId=>$cardHolder)
   {
      if ($cardHolder->cardId != $user->wantedId)
         continue;
      echo "User $holderId gives $userId his card";
   }
}
Run Code Online (Sandbox Code Playgroud)