From charlesreid1

Question

Question from Goodrich et al, Data Structures in Java, Chapter 3: Arrays and Lists

Question 3.2: Write a Java method that repeatedly selects and removes a random entry from an array until the array holds no more entries.

We can first create an array of sequential integer indices, then we can utilize the Fisher Yates method to shuffle this array of indexes.

For example, to shuffle an array holding integers [5, 44, 89]:

First, generate an array of sequential integer indices: [0, 1, 2]

Now, use the Fisher Yates method to shuffle these: [2, 1, 0]

Last, remove the items from the original array in the order [2, 1, 0]. (Remove them by setting to null or 0.)

The Code

Link to git.charlesreid1.com repository: https://git.charlesreid1.com/cs/java/src/master/arrays/sequential-remove/SequentialRemove.java

Here is the implementation code:

	public static void selectAndRemove() { 
		String[] a = {"A","B","C","D","E","F","G"};
		Integer[] indices = new Integer[a.length];
		
		// Start by populating an array of index values
		for(int i=0; i<indices.length; i++) { 
			indices[i] = i;
		}
		
		// Create new shuffled order
		shuffle(indices);

		// Remove each item, one at a time.
		for(int i=0; i<indices.length; i++) { 
			int rmi = indices[i];
			a[rmi] = null;
			System.out.printf("Removed item %d. New String array: %s \n", rmi, Arrays.toString(a));
		}
	}




Flags