Ajax Blackburn February 2016

Character assignment from a shuffled array

(edited, hopefully more clear) I'm learning to code for Android and would like to make a program that will randomly select a single number from a range, then run a random select of the remaining numbers for specified iterations.

4 iterations in this example:

  • 1 2 3 4 5 6 7 8 9 10, randomly select an integer from the set, say "7", then another new set,
  • 1 2 3 4 5 6 8 9 10, randomized, then select an integer from the new set, say "2", then a new set,
  • 1 3 4 5 6 8 9 10, randomly select an integer from the new set, say "9", then a new set,
  • 1 3 4 5 6 8 10, randomly select an integer, say "6".

Output would be 2, 6, 7, 9.

Would i be using character assignment, a=1, b=2 ect, from a shuffled array? I want the first random selected number to not be present in the consecutive sets to be randomized. Where, finally, 7,2 and 9, in this example, are not in the last set. The focus is not on avoiding duplication but generating a new specific non-sequential set to randomly choose another unique number from.

Answers


Neil February 2016

Take a look at the following example:

public static void main(String args[]) {
    // Create our test case
    List<Integer> integerList = new ArrayList<Integer>();
    for(int i=0; i<10; i++) {
        integerList.add(i+1);
    }

    // Print out 4 randomly chosen elements from list   
    Random rand = new Random();
    for(int i=0; i<4; i++) {
        System.out.println(selectOne(rand, integerList));
    }
}

private static Integer selectOne(Random rand, List<Integer> integerList) {
    int randomIndex = rand.nextInt(integerList.size());
    return integerList.remove(randomIndex);
}

To each successive call to selectOne, a random element is removed and returned. Since you cannot remove the same item twice, for each element in the list, it will be selected exactly once. This works for a series of numbers as well as a deck of cards.

In fact, if you use the following, then you could use a List<Integer> as easily as a List<Card> :

private static <T> T selectOne(Random rand, List<T> integerList) {
    int randomIndex = rand.nextInt(integerList.size());
    return integerList.remove(randomIndex);
}

Post Status

Asked in February 2016
Viewed 2,067 times
Voted 14
Answered 1 times

Search




Leave an answer