php - Finding all possible ways to swap cards -
i working on php application finds possible ways swap cards. each user has @ least 1 card. when user request card, application shows him possible ways swap card in excange card requested.
lets that:
user 1 has card type user 2 has card type b user 3 has card type c
and lets assume that:
user 1 wants card type c user 2 wants card type user 3 wants card type b
if user 1 requests card c, solution that:
user 1 gives user 2 card user 2 gives user 3 card user 3 gives user 1 card
but if there 2 other users:
user 4 has card type b & wants card type user 5 has card type c & wants card type b
now, if user 1 requests card c, there 1 other solution besides 1 above :
user 1 gives user 4 card user 4 gives user 5 card user 5 gives user 1 card
there no limit in terms of how many cards user may have or request. far, created 2 sql tables. table "cards" keeps track of each userid , cardid. table "requests" keeps track of each userid , desired cardid.
i wouldn't use pure php this. rather create mysql table stores record each user, recording card user has card wants. then, run this:
$sql = "select * users"; $result = $this->db->query(); $users = $result->getall(); //a list of users. foreach ($users $user) { $sql = "select * users cardid = '$user->wantedcardid'"; $result = $this->db->query($sql); if (! $result->has_rows()) { echo "no other users $user->wantedcardid found."; continue; } $cardholder = $result->row(); echo: "user $cardholder->id gives $user->id card"; }
if using plain php, this:
//populate array containing list of users , 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 $userid=>$user) { //run secondary loop through users find have card //this user wants. foreach ($users $holderid=>$cardholder) { if ($cardholder->cardid != $user->wantedid) continue; echo "user $holderid gives $userid card"; } }
Comments
Post a Comment