Java string randomization

I need, using an already defined set of 2-4 letters, to create a string that is completely randomized. How to take letters, combine them into one line, randomize the position of each character, and then turn this large line into two lines with an arbitrary size (but> = 2). Thanks for helping everyone.

My code so far:

//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 it shuffles strings, not individual letters. It also, being an array, has brackets that won't be found in a regular letter, and I want it to look like a random assortment of letters

+6
source share
2 answers

This is a pretty brute force, but it works. It moves the index positions and displays them in their 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); 
+2
source

You can build a string and then shuffle the characters from that string. Using Math.rand (), you can generate a random number over a character length range. Generating it for each character will give you a 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()); } 

}

0
source

All Articles