Task: Modify the program below by writing the function that \"shuffles\" the arr
ID: 654524 • Letter: T
Question
Task: Modify the program below by writing the function that "shuffles" the array of numbers
The current program as it stands creates a global integer array of 50 numbers. When the program runs, it creates the array and initializes it with 50 numbers in sequential order. It then calls the "shuffle" function which you must add code to so that the numbers are randomly ordered. You can use whatever shuffling algorithm you can create. Notice that when the shuffle function is complete, the main program will print the array.
Programming requirements:
Only add code to the shuffle function. Leave the main function as it is. This is a good way to practice working in project teams where someone else is responsible for writing the main function. Your task is simply to write the code to shuffle the array.
As before, you must use comments and proper indentation in your code and I will look at code first. In Week 13, we will discuss more about arrays enough to complete this assignment. This function may be of use for you in the final programming assignment as well so you may want to address this one before end of next week.
public class ProgAssn5
{
public static int[] numbers;
public static void shuffle()
{
// ADD YOUR CODE HERE FOR THE ASSIGNMENT
}
public static void main(String[] args)
{
numbers = new int[50];
for (int n = 0; n < 50; n++)
numbers[n] = n+1;
shuffle();
for (int n = 0; n < 50; n++)
System.out.printf("%d ", numbers[n]);
System.out.println();
}
}
Explanation / Answer
static void shuffle()
{
Random rnd = new Random();
for (int i = numbers.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = numbers[index];
numbers[index] = numbers[i];
numbers[i] = a;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.