Shuffle an array in node js
Js program for Shuffle an array. Here more information.
/*
Node JS program for
Shuffle the array elements
*/
class Shuffling
{
// Function which is swapping two array elements
// of given location
swapElement(arr, i, j)
{
// Get i location element
var temp = arr[i];
// Set new values
arr[i] = arr[j];
arr[j] = temp;
}
// Returns the random location of array elements
randomLocation(min, max)
{
// Calculate random number between given range
return Math.floor(Math.random() * (max + 1 - min) + min);
}
// Function which is shuffle given array elements
shuffleElement(arr, size)
{
// (i,j) indicate locations
var j = 0;
var i = 0;
// Variable which is controlling the
// execution process of loop
var counter = 0;
// Loop which is shuffling random elements in array
while (counter < size)
{
// Get random location of array index
i = this.randomLocation(0, size - 1);
j = this.randomLocation(0, size - 1);
if (i != j)
{
// Swap array elements
this.swapElement(arr, i, j);
counter++;
}
}
}
// Function which is display array elements
display(arr, size)
{
for (var i = 0; i < size; ++i)
{
// Disply element value
process.stdout.write(" " + arr[i]);
}
process.stdout.write("\n");
}
}
function main()
{
var task = new Shuffling();
// Define array of integer elements
var arr = [1, 0, -3, 8, 7, 3, 9, 4, 2, 5, 10, 6];
var size = arr.length;
// Before shuffling array elements
console.log(" Initial array elements");
task.display(arr, size);
console.log(" 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);
}
// Start program execution
main();
Output
Initial array elements
1 0 -3 8 7 3 9 4 2 5 10 6
After Shuffle array elements
2 7 10 5 0 8 3 4 1 -3 6 9
1 5 -3 0 6 2 8 9 3 10 7 4
3 1 -3 0 4 8 5 2 7 9 10 6
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