java - Randomly generating an array of unique chars. Know of better ways to do it now, but wondering why my original method doesn't work -


i supposed generating randomly ordered alphabet. know of shuffle methods , things fisher-yates shuffle algorithm, tried never work. had "reference" array of alphabet in regular order. have loop each 26 spaces. generate random int between 0 , 25(for index in reference array). then, check if array has char in it(it must unique) if unique, add array. still has duplicates though. here's code:

public static final char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',                                       'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v',                                       'w', 'x', 'y', 'z', ' '}; public static char[]    ciphergenerator(){     char[] cipheralpha = new char[26];     for(int index = 0; index < 26; index++){          random rand = new random();         int newletter = rand.nextint(25);         char newchar = alphabet[newletter];          while(arrays.aslist(cipheralpha).contains(newchar)){             newletter = rand.nextint(25);             newchar = alphabet[newletter];         }         cipheralpha[index] = newchar;      }     return cipheralpha; } 

this returns code duplicates, despite me trying try , find logic error. in advance help!

when pass primitive array such char[] arrays.aslist, method can't return list<char>, because primitive types aren't allowed type arguments. can , produce list<char[]>. random char never equal single char[] inside list, duplicate char allowed. if use character[] instead of char[] cipheralpha, , change return type of method character[], arrays.aslist infer type argument character correctly, allowing duplicate check work correctly.

second, nextint(25) generate random index between 0 , 24, not 25. can use alphabet.length, 26 here. first change without change, have 25 distinct characters, , never find 26th distinct character, looping forever.


Comments

Popular posts from this blog

How to run C# code using mono without Xamarin in Android? -

c# - SharpSsh Command Execution -

python - Specify path of savefig with pylab or matplotlib -