Write a program that uses Shuffle algorithm to print the words in its argument list in random order. Hint: Use List and Collection.
Updated: Aug. 10, 2022 — Training Time: 2 minutes
Overseen by: Archangel Macsika
All Training Resources
Scroll for more menu list
Topic: Shuffle Algorithm | List and Collection - Java Programming
Difficulty: Intermediate.
Companies who previously asked this: -.
Objective: Write a program that uses Shuffle algorithm to print the words in its argument list in random order. Hint: Use List and Collection.
Input: List of words.
Expected Output: Result will vary based on the user input - words in its argument list in random order.
Sikademy Solution
package sikademy;
/**
*
* @author Archangel Macsika
*/
import java.io.EOFException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
// This class uses Shuffle Algorithm of print the words in random order.
public class ShuffleAlgorithm {
private static final Logger LOG = Logger.getLogger(ShuffleAlgorithm.class.getName());
public static void main(String[] args) {
LOG.info("Into Main method ");
String[] words = { "apple", "ball", "cat", "dog", "elephant", "fish" };
List<string> listOfWords = new ArrayList<string>();
for (String word : words) {
listOfWords.add(word);
}
LOG.info("Original list is : " + listOfWords);
shuffleList(listOfWords);
LOG.info("Shuffled list is : " + listOfWords);
}
// This method generates a random number and uses it to change the position of a word in the original list of strings.
private static void shuffleList(List<string> a) {
LOG.info("Into method shuffleList");
int n = a.size();
Random random = new Random();
for (int i = 0; i < n; i++) {
int change = random.nextInt(n - 1);
swap(a, i, change);
}
}
// This method swaps the current index of the word with the randomly generated number.
private static void swap(List<string> list, int i, int change) {
LOG.info("Into method swap");
String temp = list.get(i);
list.set(i, list.get(change));
list.set(change, temp);
}
}