-3

I am trying to get this code to run without duplicates but am having no success researching this area.

Its the start of a question I am doing which will ask the user to input the missing element. However, when I generate random elements I am getting duplicates

import java.util.Random;

public class QuestionOneA2 {

    public static void main(String[] args) {

        String[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango"};
        Random numberGenerator = new Random();

        for (int i = 0; i < 5; i++) {
            int nextRandom = numberGenerator.nextInt(6);
            System.out.println(fruit[nextRandom]);
        }


    }

}
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
StudentCoder
  • 25
  • 2
  • 3

9 Answers9

1

When you generate a random number, I suggest adding it into an array.

Then, when you generate your next number, do some sort of search (google for something efficient) to check if that number is already in the array and thus, has been used already.

If it is, generate a new one, if its not, use it.

You can do this by nesting it in a while loop.

Although, from what I can tell from your question, you would be better off just creating a copy of your fruit array using an ArrayList and then, when you generate a random number to select a fruit, simply remove this fruit from this new list and decrement the range of random numbers you are generating.

James
  • 1,471
  • 3
  • 23
  • 52
1

There are many different approaches you can consider, depending on how flexible the algorithm should be.

Taking 5 random elements from a list of 6, is the same as selection 1 element from the list of 6 that you don't choose. This is a very inflexible, but very easy.

Another approach could be to delete the element from the list, and decrease the maximum random number. In this cause I would advice to not use a String[].

cvesters
  • 678
  • 5
  • 14
0

Copy your array into List<String>, then shuffle it, then just pick elements one by one:

List<String> copy = new ArrayList<>(Arrays.asList(fruit));
Collections.shuffle(copy);
for (String f : copy)
    System.out.println(f);
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
0

If I understand you correctly, then you want to choose n-1 elements at random from a list of n elements. If yes, then I recommend to choose just one at random and take all the others.

Arrays.shuffle(fruit);
int notThis = numberGenerator.nextInt(6);
for(int i = 0; i < fruit.length; i++)
    if(i!=notThis) System.out.println(fruit[i]);
  • If he'll do that then he might end up getting the same ordering again and again. For instance, if `apple` is excluded then order will be `OPBSM` and if `pear` is excluded then order will be `OABSM`. In both the cases order of `Orage` is fixed i.e. 0. – user2004685 Feb 05 '16 at 15:32
  • 1
    Then shuffle the fruits first, then this issue is fixed as well: Arrays.shuffle(fruits) must be added before printing the results. I added this to my solution – thorshammer Feb 05 '16 at 15:36
  • Yes, `shuffling` would do it. – user2004685 Feb 05 '16 at 17:09
0

You can use a Set to validate if the random generated number is duplicate or not. You just have to keep generating randomNumber until you find a unique random and then add it to the Set to prevent the duplicates.

Here is a quick code snippet:

public static void main(String[] args) {
    String[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango"};
        Random numberGenerator = new Random();
        /* Generate A Random Number */
        int nextRandom = numberGenerator.nextInt(6);
        Set<Integer> validate = new HashSet<>();
        /* Add First Randomly Genrated Number To Set */
        validate.add(nextRandom);
        for (int i = 0; i < 5; i++) {
            /* Generate Randoms Till You Find A Unique Random Number */
            while(validate.contains(nextRandom)) {
                nextRandom = numberGenerator.nextInt(6);
            }
            /* Add Newly Found Random Number To Validate */
            validate.add(nextRandom);
            System.out.println(fruit[nextRandom]);
        }
}

Output:

mango
apple
strawberry
pear
orange
user2004685
  • 9,548
  • 5
  • 37
  • 54
0

You can wrap int into 'Interger' and add it to Set. Set holds no duplicates so there will be only unique values in it. So then just check if a Set already has given Integer with Set.contains(Integer).

0

my personal solution :

private static int[] randomIndexes(int len) {
    int[] indexes = new int[len];
    for (int i = 0; i < len; i++) {
        indexes[i] = i;
    }
    for (int i = len - 1, j, t; i > 0; i--) {
        j = RANDOM.nextInt(i);
        t = indexes[j];
        indexes[j] = indexes[i];
        indexes[i] = t;
    }
    return indexes;
}

See it in action : https://gist.github.com/GautierLevert/a6881cff798e5f53b3fb

Gut
  • 331
  • 1
  • 10
0

I think it will be easier using an ArrayList, and also controlling the generation of the random number as shown below.

import java.util.Random;

public class QuestionOneA2 {

      public static void main(String[] args) {

        List<String> fruits = new ArrayList<>();

        fruits.add("orange");
        fruits.add("apple");
        fruits.add("pear");
        fruits.add("bannana");
        fruits.add("strawberry");
        fruits.add("mango");

        Random numberGenerator = new Random();
        int nextRandom;

       for (int i = 0; i < 6 ; i++) {
           nextRandom = numberGenerator.nextInt(6 - i);
           System.out.println(fruits.get(nextRandom));
           fruits.remove(nextRandom);
        }
      }

}
cdaiga
  • 4,861
  • 3
  • 22
  • 42
-1
fruit.remove(fruit[nextRandom]);

Maybe, is it the remove sub-method?

CCV
  • 19
  • 3