0

I want to make a random array and print it over one by one. But I need to print all of it without make any duplicate. I've try to adding it into list but it seems fail.

My Code :

String quest1 = "5x5#5*10#8/4"
String[] quest = quest1.split("#");

ArrayList <String> question = new ArrayList<String>();
question.add(quest[0]);
question.add(quest[1]);
question.add(quest[2]);


Random rand = new Random();
int id = rand.nextInt(question.size());
System.out.println(question.get(id));
question.remove(id);

I want to print 5x5 5*10 8/4 but in random order and I want to print each of it without print it again.

2 Answers2

0

Make a key value 2d object array or a hashmap of integer and boolean. Against all the numbers keep the boolean value false (implying that the number hasn't been printed yet ). Then generate a random number using Random class. Let this be n. Calculate n%array.length. Now see if for this new index whether you have true/false in the 2dArray/hashmap. If false then print the corresponding number and else don't print anything. I hope it's clear to you

denvercoder9
  • 2,979
  • 3
  • 28
  • 41
0

Try following code

ArrayList<Integer> questionPrinted = new ArrayList<Integer>();
        int i=0;
        while (question.size()>0) {
            Random rand = new Random();
            int id = rand.nextInt(question.size());
            if (questionPrinted.size() > 0) {
                if (questionPrinted.contains(id)) {
                    while (!questionPrinted.contains(id))
                        id = rand.nextInt(question.size());
                }
            }
            questionPrinted.add(i);
            System.out.println(question.get(id));
            question.remove(id);
            i++;
        }
Jaykishan Sewak
  • 822
  • 6
  • 13