Generate Random Array of Letters/Numbers, but can't use the same letter/number twice

时间:2016-04-04 16:28:41

标签: java

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.

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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.

答案 2 :(得分: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.