HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Optimized solution for a rolling dice code puzzle

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
rollingoptimizeddiceforcodesolutionpuzzle

Problem

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:

$a)
  { 
    if(in_array($a,$input2))
    {$p = array_search($a, $input2);
     unset($input2[$p]);
    }
    else
    { return 'Unlucky';}
  }
return 'Lucky';
}
?>

Solution

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";
}

Code Snippets

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

    return ($array1 == $array2) ? "Lucky" : "Unlucky";
}

Context

StackExchange Code Review Q#47835, answer score: 5

Revisions (0)

No revisions yet.