Shuffle an array in c++

C++ program for Shuffle an array. Here problem description and explanation.

// Include header file
#include <iostream>
#include <math.h>
using namespace std;
/*
  C++ program for
  Shuffle the array elements
*/
class Shuffling
{
	public:
    // Function which is swapping two array elements 
    // of given location
    void swapElement(int arr[], int i, int j)
    {
      // Get i location element
      int temp = arr[i];
      // Set new values
      arr[i] = arr[j];
      arr[j] = temp;
    }
	// Returns the random location of array elements
	int randomLocation(int min, int max)
	{
		// Calculate random number between given range
		return rand() % (max - min) + min;
	}
	// Function which is shuffle given array elements
	void shuffleElement(int arr[], int size)
	{
		// (i,j) indicate locations
		int j = 0;
		int i = 0;
		// Variable which is controlling the 
		// execution process of loop
		int counter = 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++;
			}
		}
	}
	// Function which is display array elements
	void display(int arr[], int size)
	{
		for (int i = 0; i < size; ++i)
		{
			// Disply element value
			cout << "  " << arr[i];
		}
		cout << "\n";
	}
};
int main()
{
  	srand(time(NULL));
	Shuffling *task = new Shuffling();
	// Define array of integer elements
	int arr[] = {
		1 , 0 , -3 , 8 , 7 , 3 , 9 , 4 , 2 , 5 , 10 , 6
	};
	int size = sizeof(arr) / sizeof(arr[0]);
	// Before shuffling  array elements
	cout << " Initial array elements" << endl;
	task->display(arr, size);
	cout << " After Shuffle array elements" << endl;
	task->shuffleElement(arr, size);
	task->display(arr, size);
	task->shuffleElement(arr, size);
	task->display(arr, size);
	task->shuffleElement(arr, size);
	task->display(arr, size);
	return 0;
}

Output

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


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