From a4eb7956e3823d48e1c61aabc9f320767648f7ca Mon Sep 17 00:00:00 2001 From: 2onefan2 <159247397+2onefan2@users.noreply.github.com> Date: Sun, 28 Apr 2024 23:57:51 -0500 Subject: [PATCH] Updated --- src/main/java/uta/cse3310/GridField.java | 15 +++++++++++---- src/test/java/uta/cse3310/GridFieldTest.java | 6 ++++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/main/java/uta/cse3310/GridField.java b/src/main/java/uta/cse3310/GridField.java index 623fa7f..afe8027 100644 --- a/src/main/java/uta/cse3310/GridField.java +++ b/src/main/java/uta/cse3310/GridField.java @@ -1,6 +1,7 @@ package uta.cse3310; import java.util.ArrayList; +import java.util.Arrays; import java.util.Random; public class GridField { @@ -46,8 +47,7 @@ public int getRemainingWords() { } public void revealWord(String word) { - if (wordList.contains(word)) { - wordList.remove(word); + if (wordList.remove(word)) { remainingWords--; } } @@ -76,9 +76,12 @@ public void displayGrid() { public void placeRandomWords() { Random random = new Random(); - for (String word : wordList) { + ArrayList remainingWords = new ArrayList<>(wordList); // Create a copy of the wordList to track remaining words + for (int i = 0; i < wordList.size(); i++) { + String word = remainingWords.get(random.nextInt(remainingWords.size())); // Select a random word from the remaining words boolean wordPlaced = false; - while (!wordPlaced) { + int attempt = 0; + while (!wordPlaced && attempt < 100) { // Limit the number of attempts to prevent infinite loops int len = word.length(); int row = random.nextInt(grid.length); int col = random.nextInt(grid[0].length); @@ -87,6 +90,10 @@ public void placeRandomWords() { addWord(word, row, col, direction); wordPlaced = true; } + attempt++; + } + if (wordPlaced) { + remainingWords.remove(word); // Remove the word from remainingWords if successfully placed } } } diff --git a/src/test/java/uta/cse3310/GridFieldTest.java b/src/test/java/uta/cse3310/GridFieldTest.java index 62f02b6..8dac998 100644 --- a/src/test/java/uta/cse3310/GridFieldTest.java +++ b/src/test/java/uta/cse3310/GridFieldTest.java @@ -63,18 +63,20 @@ public void testPlaceRandomWords() { // Create a grid field GridField gridField = new GridField(wordList); - System.out.println("Finished"); + // Place random words on the grid gridField.placeRandomWords(); - System.out.println("Finished\n"+gridField.getGrid()); + // Get the grid from the grid field char[][] grid = gridField.getGrid(); // Check if the grid is not null assertNotNull(grid); + // Check if the grid size is within a reasonable range assertTrue(grid.length >= 5 && grid.length <= 10); assertTrue(grid[0].length >= 5 && grid[0].length <= 10); + // Check if all words from the word list are placed on the grid for (String word : wordList) { assertTrue(gridField.checkWord(word));