Shuffle an array in swift

Swift program for Shuffle an array. Here problem description and explanation.

import Foundation
/*
  Swift 4 program for
  Shuffle the array elements
*/
#if os(Linux)
    srandom(UInt32(time(nil)))
#endif
class Shuffling
{
	// Function which is swapping two array elements 
	// of given location
	static func swapElement(_ arr: inout[Int], 
  			_ i: Int, _ j: Int)
	{
		// Get i location element
		let temp: Int = arr[i];
		// Set new values
		arr[i] = arr[j];
		arr[j] = temp;
	}
	// Returns the random location of array elements
	static func randomLocation(_ min: Int, _ max: Int) -> Int
	{
		// Calculate random number between given range
        var number: Int = 0;
        #if os(Linux)
          number = min + Int(random()%(max-min)) 
        #else
          number =  Int(min + arc4random_uniform(max - min)) 
        #endif
        return number;
	}
	// Function which is shuffle given array elements
	static func shuffleElement(_ arr: inout[Int], _ size: Int)
	{
		// (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 = Shuffling.randomLocation(0, size );
			j = Shuffling.randomLocation(0, size );
			if (i  != j)
			{
				// Swap array elements
				Shuffling.swapElement( &arr, i, j);
				counter += 1;
			}
		}
	}
	// Function which is display array elements
	static func display(_ arr: inout[Int], _ size: Int)
	{
		
			var i: Int = 0;
			while (i < size)
			{
				// Disply element value
				print("",arr[i], terminator: " ");
				i += 1;
			}
		
		print();
	}
	static func main()
	{
		// Define array of integer elements
		var arr: [Int] = [1, 0, -3, 8, 7, 3, 9, 4, 2, 5, 10, 6];
		let size: Int = arr.count;
		// Before shuffling  array elements
		print(" Initial array elements");
		Shuffling.display( &arr, size);
		print(" After Shuffle array elements");
		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();

Output

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


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