How to shuffle characters in a string without using Collections.shuffle(…)?

后端 未结 14 2241
南旧
南旧 2020-11-27 07:19

How do I shuffle the characters in a string (e.g. hello could be ehlol or lleoh or ...). I don\'t want to use the Collections.shuffle(...) method, is there anyt

14条回答
  •  余生分开走
    2020-11-27 08:16

    Here's code that requires neither recursion, nor converting to a Collection.

    public static String shuffle(String string) {
        StringBuilder sb = new StringBuilder(string.length());
        double rnd;
        for (char c: string.toCharArray()) {
            rnd = Math.random();
            if (rnd < 0.34)
                sb.append(c);
            else if (rnd < 0.67)
                sb.insert(sb.length() / 2, c);
            else
                sb.insert(0, c);
        }       
        return sb.toString();
    }
    

提交回复
热议问题