How to Shuffle Characters in a String Without Using Collections.Shuffle(...)

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

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<Character> characters = new ArrayList<Character>();
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
*/

How can I shuffle the letters of a word?

Really no need for collection and anything more than what follows:

public static void main(String[] args) {

// Create a random object
Random r = new Random();

String word = "Animals";

System.out.println("Before: " + word );
word = scramble( r, word );
System.out.println("After : " + word );
}

public static String scramble( Random random, String inputString )
{
// Convert your string into a simple char array:
char a[] = inputString.toCharArray();

// Scramble the letters using the standard Fisher-Yates shuffle,
for( int i=0 ; i<a.length ; i++ )
{
int j = random.nextInt(a.length);
// Swap letters
char temp = a[i]; a[i] = a[j]; a[j] = temp;
}

return new String( a );
}

How to shuffle the characters of different strings in an array?

The issue is that you are trying to call an instance method (shuffle()) from a static method (main()). You need to make shuffle() a static method.

In addition to this, you can't do System.out.println(values[0] + " " + shuffle(values[1])), because shuffle() method returns no String, in fact it returns nothing. Hence you also need to change this piece of code as follows:

public class Shuffle { 
public static void main(String[] args) {
String path = "/Users/SaberKlai/Documents/vokabeln.csv";
String line = "";

try {
BufferedReader br = new BufferedReader(new FileReader(path));

while ((line = br.readLine()) != null) {
String[] values = line.split(",");
System.out.print(values[0] + " ");
shuffle(values[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void shuffle(String input){
List<Character> characters = new ArrayList<Character>();
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());
}
}

Shuffling strings in Java

Shuffling made easy:

int len = array.length;
char[] tempArray = new char[len];
int i=0, j=0, k=len-1;

while (i<len) {
tempArray[i++] = array[j++];
if (i<len) {
tempArray[i++] = array[k--];
}
}

How to Shuffle char From Array of Strings?

Create a List of indices from 0 to names_ofcolor[random].length() - 1 and shuffle it using Collections::shuffle. Then, you can use the shuffled indices to set the label of the button.

String names_ofcolor[] = { "red", "green", "blue" };

int random = (int) (Math.random() * names_ofcolor.length);
List<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < names_ofcolor[random].length(); i++) {
indices.add(i);
}
Collections.shuffle(indices);
for (int j = 0; j < names_ofcolor[random].length(); j++) {
Button btn = new Button(this);
btn.setId(j);
btn.setBackgroundColor(Color.WHITE);
btn.setTextSize(16);
linearlayout.addView(btn);
btn.setText("" + names_ofcolor[random].charAt(indices.get(j)));
}

A quick demo:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
public static void main(String[] args) {
String names_ofcolor[] = { "red", "green", "blue" };

int random = (int) (Math.random() * names_ofcolor.length);
List<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < names_ofcolor[random].length(); i++) {
indices.add(i);
}
Collections.shuffle(indices);
for (int j = 0; j < names_ofcolor[random].length(); j++) {
String label = "" + names_ofcolor[random].charAt(indices.get(j));
System.out.print(label);
}
}
}

A sample run:

regne

Another sample run:

erd

Another sample run:

elbu

Shuffling a string containing 3 words, and assigning the output to three different strings

Your strategy is correct. Try this:

List<String> words = Arrays.asList(unsorted.split(","));
Collections.shuffle(originalWords);
// After this you can access random-ed word
words.get(0); words.get(1);..

how to shuffle an array without involving the first element?

Here is a quick example, using Lists:

String [] example = { "A", "B", "C", "D"};
List<String> items = Arrays.asList(example);
Collections.shuffle(items.subList(1, items.size()));
System.out.println(items);

The point is: you can create a view using the sublist() method, and shuffle that. And of course you can use the toArray() methods of the List interface to turn your list back into an array.

How to shuffle a character array with no two duplicates next to each other?

[ there is a test cases failing as was pointed in the comments]
So take care of the same if referring my answer
I see, but it doesn't seem to work if you have 'a'->4, 'b'->2, and 'c'->1. Because the first step is "abc", leaving 'a'->3 'b'->1. But there is an answer: "ababaca". – user3386109

Case 1 : Build the basic algorithm

  1. use a hashmap (key being the character and its occurance being the value) to count the occurances. This will give us buckets like if we have "cbaaba" will give 3 buckets with 'c' with value 1, 'a' with value 3 and 'b' with value 2.

  2. Sort the buckets based on the occurances with element with most occurancr first.
    so now we have

'a' -> 3 , 'b' -> 2 , 'c' -> 1


  1. Get the element from max occurance bucket, decrease its count by 1 in map and put it in result array. Follow this for subsequent occuance buckets based on the sorted occurance buckets.

result array will start with taking one each from 3 buckets in sorted fashion.

"abc" and now we have our buckets as 'a'->2 , 'b'-> 1 and 'c'-> 0

next we again try to get elemet each from sorted buckets (ignoring the buckets with 0 elements)

"abcab" now our buckets state become as : 'a'-> 1 , 'b'- > 0 and 'c'-> 0

next as above we proceed to have our result as

=> "abcaba".

Case 2 : if string is like "aaaabbbcccdd"

We will have buckets as

'a'--> 4
'b'--> 3
'c'--> 3
'd'--> 2

Here we have bucket of b and c having same size. When ever such situation occurs we have to perform an operation of JoinBuckets, It will join 'b' and 'c' in single bucket and 'bc' will be considered as a single element.

Now our buckets will be

'a'--> 4
'bc'--> 3
'd'--> 2

Now proceeding ahead in same manner as done in case 1, we try to build the result

=>result = "abcd"

'a'--> 3
'bc'--> 2
'd'--> 1

=>result = "abcdabcd"

'a'--> 2
'bc'--> 1
'd'--> 0

=>result = "abcdabcdabc"

'a'--> 1
'bc'--> 0
'd'--> 0

=>Final Result = "abcdabcdabca"



Related Topics



Leave a reply



Submit