0

In one interview I was asked to shuffle an associative array that has value like .

$card = array (
               "car"=>1,
                "bus"=>2,
                "truck"=>3,
);

etc. Using a radom function that generate random digit between 0,1 ;

They asked me not to use any inbuilt PHP function .

input: associative array;
output: randomly sequenced associative array;

Thanks & Regards

Vikram Anand Bhushan
  • 4,836
  • 15
  • 68
  • 130

2 Answers2

2

The built-in shuffle() doesn't handle associative arrays very well, so you'd need to shuffle the array keys and then reconstitute the array again.

I'm using the Fisher-Yates-Knuth algorithm to perform the shuffling, which is really the crux of the solution.

function myshuffle($arr)
{
    // extract the array keys
    $keys = [];
    foreach ($arr as $key => $value) {
        $keys[] = $key;
    }

    // shuffle the keys    
    for ($i = count($keys) - 1; $i >= 1; --$i) {
        $r = mt_rand(0, $i);
        if ($r != $i) {
            $tmp = $keys[$i];
            $keys[$i] = $keys[$r];
            $keys[$r] = $tmp;
        }
    }

    // reconstitute
    $result = [];
    foreach ($keys as $key) {
        $result[$key] = $arr[$key];
    }

    return $result;
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
-2
    $words = array("adumbrate","antipathy","aspersion","assiduous","cacophony","conundrum");


 $rand_word_index = array_rand($words); // Get any random index from an array

        //  Original Word
 $rand_word = $words[$rand_word_index]; // Stored array value basis of random index


$shuffled = str_shuffle($rand_word); // Shuffle this value or word

echo $shuffled;
Mahesh Shukla
  • 186
  • 10