Shuffle an array in kotlin

Kotlin program for Shuffle an array. Here problem description and other solutions.

/*
  Kotlin program for
  Shuffle the array elements
*/
class Shuffling
{
	// Function which is swapping two array elements 
	// of given location
	fun swapElement(arr: Array < Int > , i: Int, j: Int): Unit
	{
		// Get i location element
		val temp: Int = arr[i];
		// Set new values
		arr[i] = arr[j];
		arr[j] = temp;
	}
	// Returns the random location of array elements
	fun randomLocation(min: Int, max: Int): Int
	{
		// Calculate random number between given range
		return min + (Math.random() * (max - min)).toInt();
	}
	// Function which is shuffle given array elements
	fun shuffleElement(arr: Array < Int > , size: Int): Unit
	{
		// (i,j) indicate locations
		var j: Int ;
		var i: Int ;
		// Variable which is controlling the 
		// execution process of loop
		var counter: Int = 0;
		// Loop which is shuffling random elements in array
		while (counter < size)
		{
			// Get random location of array index
			i = this.randomLocation(0, size);
			j = this.randomLocation(0, size);
			if (i != j)
			{
				// Swap array elements
				this.swapElement(arr, i, j);
				counter += 1;
			}
		}
	}
	// Function which is display array elements
	fun display(arr: Array < Int > , size: Int): Unit
	{
		var i: Int = 0;
		while (i < size)
		{
			// Disply element value
			print("  " + arr[i]);
			i += 1;
		}
		print("\n");
	}
}
fun main(args: Array < String > ): Unit
{
	val task: Shuffling = Shuffling();
	// Define array of integer elements
	val arr: Array < Int > = arrayOf(1, 0, -3, 8, 7, 3, 9, 4, 2, 5, 10, 6);
	val size: Int = arr.count();
	// Before shuffling  array elements
	println(" Initial array elements");
	task.display(arr, size);
	println(" After Shuffle array elements");
	task.shuffleElement(arr, size);
	task.display(arr, size);
	task.shuffleElement(arr, size);
	task.display(arr, size);
	task.shuffleElement(arr, size);
	task.display(arr, size);
}

Output

 Initial array elements
  1  0  -3  8  7  3  9  4  2  5  10  6
 After Shuffle array elements
  9  2  4  1  3  7  6  5  0  8  10  -3
  10  3  4  1  5  2  6  7  8  9  0  -3
  2  8  10  -3  5  1  3  7  6  9  0  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