Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 653
Fool Avatar asked Dec 18 '15 06:12

Fool


1 Answers

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);
like image 191
Steve Chaloner Avatar answered Sep 30 '22 12:09

Steve Chaloner