用Java随机化字符串

傻子

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

到目前为止,我的代码是:

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

    Collections.shuffle(arrayList);

但是我发现这会乱序字符串而不是单个字母。作为数组,它还具有普通书写中不会出现的括号,我希望它看起来像字母的随机排列

史蒂夫·沙洛纳

这是一种蛮力的方法,但是有效。它会随机整理索引位置,并将其映射到原始位置。

    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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章