Fool
Fool

Reputation: 117

Randomizing a string in Java

I need to, using an already defined set of 2-4 letters, create a string that is completely randomized. How would one take letters, combine them into one string, randomize the position of each character and then turn that large string into two randomly sized (but >= 2) other strings. Thanks for everyone's help.

My code so far is:

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

    Collections.shuffle(arrayList);

But I found that this shuffles the Strings and not the individual letters. It also, being an array, has the brackets that wouldn't be found in regular writing and I do want it to look like a randomish assortment of letters

Upvotes: 6

Views: 2722

Answers (2)

Steve Chaloner
Steve Chaloner

Reputation: 8202

This is a pretty brute force approach, but it works. It shuffles index positions and maps them to the original position.

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

Upvotes: 2

Irina Avram
Irina Avram

Reputation: 1522

You can build a string and then shuffle the characters from that string. Using Math.rand() you cano generate a random number within the range of the character's length. Generating it for each character will get you the shuffled string. Since your code is unclear, I will just write an example

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

}

Upvotes: 0

Related Questions