Shuffle the elements of array in php

Php program for Shuffle the elements of array. Here more information.

<?php
/*
  Php program for
  Shuffle the array elements
*/
class Shuffling
{
	// Function which is swapping two array elements 
	// of given location
	public static
	function swapElement(&$arr, $i, $j)
	{
		// Get i location element
		$temp = $arr[$i];
		// Set new values
		$arr[$i] = $arr[$j];
		$arr[$j] = $temp;
	}
	// Returns the random location of array elements
	public static function randomLocation($min, $max)
	{
		// Calculate random number between given range
		return rand($min, $max);
	}
	// Function which is shuffle given array elements
	public static function shuffleElement(&$arr, $size)
	{
		// (i,j) indicate locations
		$j = 0;
		$i = 0;
		// Variable which is controlling the 
		// execution process of loop
		$counter = 0;
		// Loop which is shuffling random elements in array
		while ($counter < $size)
		{
			// Get random location of array index
			$i = Shuffling::randomLocation(0, $size - 1);
			$j = Shuffling::randomLocation(0, $size - 1);
			if ($i != $j)
			{
				// Swap array elements
				Shuffling::swapElement($arr, $i, $j);
				$counter++;
			}
		}
	}
	// Function which is display array elements
	public static
	function display($arr, $size)
	{
		for ($i = 0; $i < $size; ++$i)
		{
			// Disply element value
			echo "  ".strval($arr[$i]);
		}
		echo "\n";
	}
	public static
	function main($args)
	{
		// Define array of integer elements
		$arr = array(1, 0, -3, 8, 7, 3, 9, 4, 2, 5, 10, 6);
		$size = count($arr);
		// Before shuffling  array elements
		echo " Initial array elements", "\n";
		Shuffling::display($arr, $size);
		echo " After Shuffle array elements", "\n";
		Shuffling::shuffleElement($arr, $size);
		Shuffling::display($arr, $size);
		Shuffling::shuffleElement($arr, $size);
		Shuffling::display($arr, $size);
		Shuffling::shuffleElement($arr, $size);
		Shuffling::display($arr, $size);
	}
}
Shuffling::main(array());

Output

 Initial array elements
  1  0  -3  8  7  3  9  4  2  5  10  6
 After Shuffle array elements
  2  0  -3  8  1  6  10  4  5  3  9  7
  5  7  3  8  1  9  0  -3  10  6  4  2
  2  1  7  9  8  0  10  5  6  3  -3  4


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved