3
\$\begingroup\$

I was asked to provide the solution of this rolling dice problem in an interview. When I showed him my solution, he said that there is another way to find the solution. I am looking for answer in PHP script only.

Question:

Two persons are playing a game of rolling 2 dices. Each person rolls the two dices n times and records the outcomes (sum of value of two dices) of all the n attempts. So after n attempts of both the player we have two list corresponding to the n outcomes of two players.

They want to know that whether they have got all possible outcomes( 1 to 12) same number of times or not. If they got all the possible outcomes same number of times then they are called lucky otherwise unlucky.

Input: Two Integer Arrays (L1, L2) corresponding to outcomes of two players.

Output: Lucky or Unlucky depending on the case

My Answer:

<?php
function rollingdice($input1,$input2)
{
  foreach($input1 as $k=>$a)
  { 
    if(in_array($a,$input2))
    {$p = array_search($a, $input2);
     unset($input2[$p]);
    }
    else
    { return 'Unlucky';}
  }
return 'Lucky';
}
?>
\$\endgroup\$
  • \$\begingroup\$ Couldn't you just compare the two arrays directly? Ideally after sorting. \$\endgroup\$ – Mr Wednesday Apr 22 '14 at 2:39
  • \$\begingroup\$ all possible outcomes (1 to 12) You can't roll a 1 with two dice. :) \$\endgroup\$ – Alex Howansky Jun 4 '14 at 15:32
3
\$\begingroup\$

Based on your use of in_array(), you don't appear to be concerned with the order of the elements. In that case, you can simply sort the arrays and compare them directly.

function compare($array1, $array2)
{
    sort($array1);
    sort($array2);

    return ($array1 == $array2) ? "Lucky" : "Unlucky";
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.