To shuffle an array of integers into random order, a pseudo-code is developed as
ID: 3905834 • Letter: T
Question
To shuffle an array of integers into random order, a pseudo-code is developed as . elementsRemaining size of array while elementsRemaining > 1 o Randomly choose index rndNdx in range 0 - elementsRemaining-1 o Swap element at rndNdx with element at elementsRemaining-1 o Decrement elementsRemaining follows: Based on the pseudo-code, implement the shuffle) function below by filling the missing statements: function shuffle(anArray) 1 // Some statements are missing here Write ONLY the missing statement - do NOT rewrite the entire code given above. You may need to create some local variables in side the function body in order to make the shuffling work correctly. Note the programming style (naming convention, indentation, spacing, etc.) in your code. Hint: See the language reference at the end of the exam paper for Math methods that may be useful.Explanation / Answer
function shuffle(anArray){
var rndNdx;
var elementsRemaining = anArray.length;
while(elementsRemaining>1){
rndNdx = Math.floor(Math.Random()*elementsRemaining ; //selecting random index
swap(anArray[rndNdx],anArray[elementsRemaining-1]);
elementsRemaining = elementsRemaining-1;
}
}
swap function can be implemented as:
function swap(var a, var b)
{
var temp;
temp = a;
a = b;
b = temp;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.