1

How can i randomized each string in Array words... for the word "Position" to "Psioiont". basically what i need to do is i want to display the i an funny way where a person has to think before he can answer...

Hello ---> "hlelo"

public class Rnd {
    public static void main(String[] args) {

       List  list = new ArrayList();
       Collections.shuffle(list);

       String[] words =new String[]{"Position", "beast", "Hello"};
       Collections.shuffle(Arrays.asList(words)); 
    }
}
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
yvensup
  • 75
  • 1
  • 3
  • 8

2 Answers2

2

Just put the characters in each string into a list, then call Collections.shuffle(), then put them back into a string:

    String x = "hello";
    List<Character> list = new ArrayList<Character>();
    for(char c : x.toCharArray()) {
        list.add(c);
    }
    Collections.shuffle(list);
    StringBuilder builder = new StringBuilder();
    for(char c : list) {
        builder.append(c);
    }
    String shuffled = builder.toString();

    System.out.println(shuffled); //e.g. llheo
Michael Berry
  • 70,193
  • 21
  • 157
  • 216
0

Convert the each string to an array of chars and call shuffle on that, then create a string again.

Of course, that doesn't actually work with real Unicode - there's no easy way to do it if there could be non-BMP characters or composite characters in there. But it will probably do for the kind of small game this appears to be.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157