Java Program to Shuffle Characters in a String Without Using Shuffle()
Last Updated :
01 Feb, 2024
Rearranging the order of characters, in a string can be done by shuffling them. Although the shuffle() method provided by Java’s Collections class is handy there are situations where you might require approaches. In this article, we will explore techniques, for shuffling characters in a string without using the shuffle() method.
Methods to shuffle characters in a String
1. Using a Fisher-Yates Algorithm
Below is the illustration of the Fisher-Yates Algorithm to shuffle characters in a String.
Java
import java.util.Random;
public class GFG {
public static String
shuffleStringFisherYates(String str)
{
char [] chars = str.toCharArray();
Random random = new Random();
for ( int i = chars.length - 1 ; i > 0 ; i--) {
int j = random.nextInt(i + 1 );
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
return new String(chars);
}
public static void main(String[] args)
{
String originalString = "GeeksForGeeks" ;
String shuffledString
= shuffleStringFisherYates(originalString);
System.out.println( "Original string: "
+ originalString);
System.out.println(
"Shuffled string (Fisher-Yates): "
+ shuffledString);
}
}
|
Output
Original string: GeeksForGeeks
Shuffled string (Fisher-Yates): GkoGressekeFe
Explanation of the above Program:
- The shuffleStringFisherYates() method convert the string to a character array.
- After that it shuffles the string and returns the result.
- In the main() method, the original string shuffles and it prints both the original and shuffled string.
2. Using StringBuilder
We can shuffle characters in a String using StringBuilder method.
Java
import java.util.Random;
public class GFG {
public static String shuffleStringStringBuilder(String str) {
StringBuilder sb = new StringBuilder(str);
Random random = new Random();
for ( int i = sb.length() - 1 ; i > 0 ; i--)
{
int j = random.nextInt(i + 1 );
char temp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, temp);
}
return sb.toString();
}
public static void main(String[] args) {
String originalString = "GeeksForGeeks" ;
String shuffledString = shuffleStringStringBuilder(originalString);
System.out.println( "Original string: " + originalString);
System.out.println( "Shuffled string (StringBuilder): " + shuffledString);
}
}
|
Output
Original string: GeeksForGeeks
Shuffled string (StringBuilder): kFreessGGokee
Explanation of the above Program:
- The shuffleStringStringBuilder() method takes a string as input and shuffles this using StringBuilder.
- The method iterates through the StringBuilder from end to begining.
- In the main() method, the original string shuffled and it prints both the original and shuffled string.
Share your thoughts in the comments
Please Login to comment...