2016-01-02 41 views
-3

想要为替换密码创建随机生成的字母表。我的想法是这样的。如何在Java中创建随机生成的字母表

 char randomChar = (char) (97 + r.nextInt(25)); 

但是,这会造成字母的重复。浏览字符数组并查看该字母是否已经存在似乎也是无效的。

编辑:我的要求太模糊,现在就看到这个。这是我想解决的完整问题。字母表还必须包含空格按钮字符,例如''。

编写一个Java程序,它使用替换密码(将纯文本字符随机分配给密文字母)将(用户输入的)纯文本转换为密文。请注意,替代密码用密文替换明文。最普通的替换密码用明文的单个字符代替密文的单个字符(例如,明文字符'a'可能被密文字符'q'替代,'b'可能被'x'替代, 'c','k'等等)。每个纯文本字符应由不同的密文字符替换。 作为您的解决方案的一部分,您必须至少编写和使用以下函数/方法: (i)createCipher(),它确定并返回从纯文本到密文的映射。每个纯文本字符('a'..'z','')必须随机分配一个密文字符;

+1

在这个什么是 “R”?你的随机对象? –

+0

道歉,r是我的随机生成器。我设法想出了一个不同的想法,现在发布 – RonanMacF

回答

0

我想过一个解决方案,说解决方案的工作,但它是有效的?

public static char[] createCipher(char[] cipher) { 
    char[] cipher = new char[27]; 
    int characterNumber = 97; 
    cipher[0] = ' '; 
    for(int counter = 1; counter < cipher.length;counter++) 
    { 
     char character = (char) characterNumber; 
     cipher[counter] = character; 
     characterNumber++; 
    } 

    for(int counter = 0; counter < cipher.length;counter++) 
    { 
     int randomLocation = (int) (Math.random()*26); 
     char temporaryCharacter = cipher[randomLocation]; 
     cipher[randomLocation] = cipher[counter]; 
     cipher[counter] = temporaryCharacter; 
    } 
    return cipher; 

} 
+0

我已经对此进行了一些测试,'a'似乎是第一个入门1/20的时间,而不是1/26,因为它应该是( 'z'是大致的第一个字母)。可能是我的测试出了问题,但获取随机排序列表的正常方法是不使用数组;使用数组列表,并随时删除使用的entrys。 –

+0

如果你想重新编排字母表,你不得不清理你想要的东西:一个随机乱拼字母或字符的工具吗?并通过抓取你的意思 – gpasch

0

要做到字母表中的重新洗牌(26个字符,但在不同的顺序),你做

boolean[] b=new boolean[26]; 
    for(i=0; i<b.length; i++) b[i]=false; 
for(int counter = 0; counter < 26;counter++) 
{ 
    int randomLocation = (int) (Math.random()*26); 
    while(b[randomLocation]) randomLocation = (int) (Math.random()*26); 
    b[randomLocation]=true; 
    cipher[counter]=alphabet[randomLocation]; 
} 

忘了“高效”和东西首先你解决问题

0

如果你想要洗牌字母,你可以使用Collections.shuffle(..) metode。 Somethink这样的:

public static void main(String[] args) { 
    char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray(); 
    char[] randomAlphabet = new char[alphabet.length]; 

    // Copy to a List 
    List<Character> list = new ArrayList<Character>(); 
    for (char c : alphabet) { 
     list.add(c); 
    } 

    // shuffle it  
    Collections.shuffle(list); 

    // Copy it back to an array 
    for (int i = 0; i < list.size(); i++) { 
     randomAlphabet[i] = list.get(i); 
    } 

    System.out.print("Random alphabet: "); 
    for (int i = 0; i < randomAlphabet.length; i++) { 
     System.out.print(" " + randomAlphabet[i]); 
    } 
} 

这给了这个当我运行它:

Random alphabet: j b w q o c r f z k g n p a u s i d m y h v e l x t