【问题标题】:Randomizing a string in Java在Java中随机化一个字符串
【发布时间】:2016-03-24 19:53:34
【问题描述】:

我需要使用已经定义的 2-4 个字母集创建一个完全随机的字符串。如何获取字母,将它们组合成一个字符串,随机化每个字符的位置,然后将该大字符串变成两个随机大小(但 >= 2)的其他字符串。感谢大家的帮助。

到目前为止我的代码是:

    //shuffles letters
    ArrayList arrayList = new ArrayList();
    arrayList.add(fromFirst);
    arrayList.add(fromLast);
    arrayList.add(fromCity);
    arrayList.add(fromSong);

    Collections.shuffle(arrayList);

但我发现这会打乱字符串而不是单个字母。作为一个数组,它也有在常规写作中找不到的括号,我确实希望它看起来像一个随机的字母组合

【问题讨论】:

  • Collections.shuffle来找
  • 请展示你到目前为止尝试过的...
  • fromFirstfromLast 等是什么?字符串?人物?人物列表?
  • 它们是字符串,很抱歉造成混淆

标签: java string random


【解决方案1】:

这是一种相当暴力的方法,但它确实有效。它打乱索引位置并将它们映射到原始位置。

    final String possibleValues = "abcd";
    final List<Integer> indices = new LinkedList<>();
    for (int i = 0; i < possibleValues.length(); i++) {
        indices.add(i);
    }
    Collections.shuffle(indices);

    final char[] baseChars = possibleValues.toCharArray();
    final char[] randomChars = new char[baseChars.length];
    for (int i = 0; i < indices.size(); i++) {
        randomChars[indices.get(i)] = baseChars[i];
    }
    final String randomizedString = new String(randomChars);
    System.out.println(randomizedString);

    final Random random = new Random();
    final int firstStrLength = random.nextInt(randomChars.length);
    final int secondStrLength = randomChars.length - firstStrLength;
    final String s1 = randomizedString.substring(0, firstStrLength);
    final String s2 = randomizedString.substring(firstStrLength);

    System.out.println(s1);
    System.out.println(s2);

【讨论】:

  • 这很有帮助,但是您知道将这个字符串分成两个随机大小的字符串的方法吗?
  • 我已更新代码以显示这一点。此解决方案提供了s1s2 可能包含所有字符的可能性。
【解决方案2】:

您可以构建一个字符串,然后随机播放该字符串中的字符。使用 Math.rand() 您可以在字符长度范围内生成一个随机数。为每个字符生成它会让你得到洗牌的字符串。由于你的代码不清楚,我就写个例子吧

public class ShuffleInput {

public static void main(String[] args) {
    ShuffleInput si = new ShuffleInput();
    si.shuffle("input");

}
public void shuffle(String input){
    List<Character> chars = new ArrayList<Character>();

    for(char c:input.toCharArray()){
        chars.add(c);
    }

    StringBuilder output = new StringBuilder(input.length());

    while(chars.size()!=0){
        int rand = (Integer)(Math.random()*characters.size());
        output.append(characters.remove(rand));
    }
    System.out.println(output.toString());
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2019-08-07
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多