Shuffle an array in scala

Scala program for Shuffle an array. Here more information.

/*
  Scala program for
  Shuffle the array elements
*/
class Shuffling()
{
	// Function which is swapping two array elements 
	// of given location
	def swapElement(arr: Array[Int], i: Int, j: Int): Unit = {
		// Get i location element
		var temp: Int = arr(i);
		// Set new values
		arr(i) = arr(j);
		arr(j) = temp;
	}
	// Returns the random location of array elements
	def randomLocation(min: Int, max: Int): Int = {
		val r = new scala.util.Random;
        // Calculate random number between given range
        return min + r.nextInt((max-min)) ;
	}
	// Function which is shuffle given array elements
	def shuffleElement(arr: Array[Int], size: Int): Unit = {
		// (i,j) indicate locations
		var j: Int = 0;
		var i: Int = 0;
		// 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 = randomLocation(0, size);
			j = randomLocation(0, size);
			if (i != j)
			{
				// Swap array elements
				swapElement(arr, i, j);
				counter += 1;
			}
		}
	}
	// Function which is display array elements
	def display(arr: Array[Int], size: Int): Unit = {
		var i: Int = 0;
		while (i < size)
		{
			// Disply element value
			print("  " + arr(i));
			i += 1;
		}
		print("\n");
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: Shuffling = new Shuffling();
		// Define array of integer elements
		var arr: Array[Int] = Array(
          1, 0, -3, 8, 7, 3, 9, 4, 2, 5, 10, 6);
		var size: Int = arr.length;
		// 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
  0  5  7  1  4  10  9  6  2  8  -3  3
  -3  0  8  6  3  4  9  1  10  5  7  2
  -3  6  2  7  0  8  10  1  9  5  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