-1

Possible Duplicate:
How do I remove repeated elements from ArrayList?

I want to replace a duplicate number (if any) that i store in an ArrayList. I obtianed the numbers for a Random variable. Here is the class.

import java.util.*;

public class RandomNumbers {
// instance variables
private ArrayList<Integer> randomNumberList = new ArrayList<Integer>(); 
private Random randomNums = new Random();

public RandomNumbers(){
    // generating and adding random numbers to the list
    for (int i=0; i<MemoryGame.totalAnswers; i++)
        randomNumberList.add(randomNums.nextInt(32));

    System.out.println("Numbers in the list: " + randomNumberList);
    System.out.println("");
}

public ArrayList<Integer> getRandomNumbers(){
    return randomNumberList;
}
}

My school book tells me how to add,remove and retrieve a number, but not how to replace one that is duplicated.

thanks.

Community
  • 1
  • 1
chr.solr
  • 576
  • 1
  • 7
  • 19
  • 1
    What do you mean by "replace"? Is it that you want to keep generating random numbers until you get one you haven't already got? – Bohemian Dec 29 '12 at 02:58
  • 1
    duplication in duplication question: http://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist – İsmet Alkan Dec 29 '12 at 03:04
  • Just a comment, BTW, is `MemoryGame.totalAnswers` always smaller than 32? If not, you may run into problems.... – Yanick Rochon Dec 29 '12 at 03:05
  • I need 8 random numbers fro – chr.solr Dec 29 '12 at 03:42
  • For a reasonably sized set of distinct numbers to randomize, I would ***use a [Fisher-Yates] shuffle*** and then pick the first N (could be up to the entire input size) results. I find this approach cleaner in general. (The Fisher-Yates shuffle can also be implemented in such a way that numbers are generated as a stream without requiring full computation.) –  Dec 29 '12 at 03:43
  • I need 8 random numbers from 0-31 that are not duplicated. The Value in MemoryGame.totalAnswers is 8. I'm going to resource HashSet tonight. I didn't know about it since I'm still I'm my first semester at school. – chr.solr Dec 29 '12 at 03:46

4 Answers4

2

If you are not limited to ArrayList, use a HashSet<Integer> instead (or better yet, a LinkedHashSet). HashSet<Integer> will garantee you not to have duplicated values in the collection, LinkedHashSet<Integer> will do the same and also preserve the ordering the the items.

If you insist on having an ArrayList, then do this :

public RandomNumbers(){
    HashSet<Integer> set = new HashSet<Integer>();

    // generating and adding random numbers to the list
    //for (int i=0; i<MemoryGame.totalAnswers; i++)
    while (set.size()<MemoryGame.totalAnswers)
        set.add(randomNums.nextInt(32));

    randomNumberList.addAll(set);  // dump the set in your ArrayList

    System.out.println("Numbers in the list: " + randomNumberList);
    System.out.println("");
}

Also, if MemoryGame.totalAnswers == 32, then you can speed up this process with a random list instead :

public RandomNumbers(){
    // generating and adding random numbers to the list
    for (int i=0; i<MemoryGame.totalAnswers; i++)
        randomNumberList.add(i);

    Collections.shuffle(randomNumberList);

    System.out.println("Numbers in the list: " + randomNumberList);
    System.out.println("");
}

** Update **

Since MemoryGame.totalAnswers == 8, forget the last snippet. I'm leaving it there if anyone would happend to need it. You can skip the use of a Set entirely by folllowing pst's suggestion :

public RandomNumbers(){
    // generating and adding random numbers to the list
    for (int i=0; i<32; i++)
        randomNumberList.add(i);

    Collections.shuffle(randomNumberList);

    // keep only the first ones we need
    randomNumberList.removeRange(MemoryGame.totalAnswers + 1, 32);

    System.out.println("Numbers in the list: " + randomNumberList);
    System.out.println("");
}
Community
  • 1
  • 1
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
1

For replacing an element in a position use the set() method:

randomNumberList.set(index, element);

Of course, the logic to find out which elements are duplicated in the first place is up to you; if it doesn't make sense to have duplicate numbers for your problem, better use a Set data structure (for instance: HashSet, or LinkedHashSet if preserving insertion order when iterating is important for you) and keep adding random elements to the set until it has the desired size.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

If the ultimate objective is a random list of distinct numbers, and the range of possible numbers is not much larger than the number of results required, consider a shuffle rather than replacing duplicates.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
0

If all you want is as per your last comment

8 random, non-repeated numbers from 0-31

You don't need any instance variables, random number generating code, or instance methods.
All you need is just this:

public static List<Integer> getRandomNumbers() {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < 32; i++)
        list.add(i);
    Collections.shuffle(list);
    return list.subList(0, 8);
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • I tried this method, but somehow i get duplicate number with this method. – chr.solr Dec 29 '12 at 10:04
  • It is totally impossible to get duplicate numbers with this code, because each number 0-31 is added only once. What did you do to "try" it, exactly? – Bohemian Dec 29 '12 at 11:24
  • I replace my getRandomNumbers method with yours and delete what i had in the constructor method. But if I use it in the constructor and return the value through getRandomNumbers method it works just fine. is there any way to remove the non-use elements after shuffling. ei delete index from 9-31 after shuffling. I dont if it make since to delete them but i would think so, because efficiency. Thanks for the help. – chr.solr Dec 29 '12 at 19:00
  • to "delete" the used ones, do this: `myList = list.subList(8, list.size())` – Bohemian Dec 29 '12 at 19:15