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

后端 未结 14 2245
南旧
南旧 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:07

    I dont know anything simpler. But you can use the Math.rand() functionality to generate a random number within the range of the character's length without replace and that would give you a shuffled output

    public class Shuffle {
        public static void main(String[] args) {
            Shuffle s = new Shuffle();
            s.shuffle("hello");
    
        }
        public void shuffle(String input){
            List characters = new ArrayList();
            for(char c:input.toCharArray()){
                characters.add(c);
            }
            StringBuilder output = new StringBuilder(input.length());
            while(characters.size()!=0){
                int randPicker = (int)(Math.random()*characters.size());
                output.append(characters.remove(randPicker));
            }
            System.out.println(output.toString());
        }
    }
    /*
    Sample outputs
    hlleo
    llheo
    leohl
    lleho
    */
    

提交回复
热议问题