user10942442
user10942442

Reputation:

How to make the output random in circular list java

This is a Duck Duck Goose problem. The output should end up random. However, my output and code ends up the last which is [Scooby]. How should the code be?

There are 19 names

http://collabedit.com/q248e

public class DuckDuckGoose {

    public static void main(String[] args) {

        LinkedList<String> linkedlist = new LinkedList<String>();
        // add try catch to add list
        try {
            FileReader fr = new FileReader("C:\\Users\\src\\players.txt");
            Scanner inFile = new Scanner(fr);
            // while loop to get the next line with add to get the next name
            while (inFile.hasNextLine()) {
                linkedlist.add(inFile.nextLine());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Iterator<String> iterator = linkedlist.iterator();
        // to get the names of the list in loop
        while(linkedlist.size() > 1){
            while (iterator.hasNext()) {
                iterator = linkedlist.iterator();
                iterator.next();
                // random number Goose landed method
                if (getRandomBoolean()) {
                    iterator.remove();
                }
                if(linkedlist.size() == 1) break;
            }    
        }

        System.out.println(linkedlist);
    }
    // gets the random number with a different number .80 
    // than .5 that is half
    public static boolean getRandomBoolean() {
        return Math.random() < .80;
    }

}

Upvotes: 1

Views: 114

Answers (1)

prasad
prasad

Reputation: 1302


i tried to reuse your logic so that you can understand easily.
There are 2 mistakes in existing code due to which you are getting same output every time.

  1. You are re initializing the iterator every time in 2nd while loop due to which you always try to remove first element
  2. Then you need to move your pointer(iterator) to next element if it is not removed. Or whenever getRandomBoolean() is false

    while(linkedlist.size() > 1){
        iterator = linkedlist.iterator(); // this is Point 1
        while (iterator.hasNext()) {
            iterator.next();
            // random number Goose landed method
            if (getRandomBoolean()) {
                iterator.remove();
            } else if (iterator.hasNext()) { // this is Point 2
                iterator.next();
            }
            if(linkedlist.size() == 1) break;
        }    
    }
    

i have tested multiple times it's working fine. i hope explained it properly please let me know if you have more questions.
Thanks

Upvotes: 1

Related Questions