1

Very similar to Generating Unique Random Numbers in Java. But with letters and numbers, not just numbers.

So how would I go about 'Generate Random Array of Letters/Numbers, but can't use the same letter/number twice'. So for example:

Good: "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" "QWERTYUIOPASDFGHJKLZXCVBNM0246813579" Bad: "AACDDFGHHJKLMMOPPRSTUVVWXY2335925523"

It needs to contain every letter in the alphabet, but only once and in a random order.

Community
  • 1
  • 1
KiwiNinja
  • 63
  • 1
  • 7

3 Answers3

2

Have an array of the pool of characters, shuffle them, and then pop one off each time you need a random character.

alex
  • 479,566
  • 201
  • 878
  • 984
0
  1. Declare a List<Char> and add to it every letter and do the same with List<int> for the numbers.
  2. Use Math.random() to get a random number up to the length of the List.
  3. Use that number to get the corresponding item from the List and then remove it from the List
  4. Repeat until List.isEmpty() == true
  5. Do the same for the number List.

Edit: @alex's answer is probably simpler.

0

Another solution is to make a text array containing all the characters you want.

e.g Char[] myArray = {"a","b" ..};

Then take random indexes from the array and insert into map until the size of the map is equal to the size of your array. The map will never contain duplicates and you will have many random combinations. The key and value of the map can be the same in this case.

flimsy
  • 1
  • 1
  • For this to work, you have to use a sorted map, e.g. a `LinkedHashMap`. Since you are not interested in the values, you can also use a `LinkedHashSet`, which keeps the entries in the insertion order, but prevents duplicates. – Stefan Dollase Apr 04 '16 at 16:51
  • All in all, this method might take quite some time and is not even guaranteed to terminate, since the more elements are already inserted into the set, the higher is the probability to insert an element that is already contained in the set. – Stefan Dollase Apr 04 '16 at 16:53