Shuffle string in java

Programming for beginners

package com.sample.app; import java.util.Arrays; import java.util.Collections; import java.util.List; public class App  public static String shuffleString(String string)  ListString> letters = Arrays.asList(string.split("")); Collections.shuffle(letters); StringBuilder builder = new StringBuilder(); for (String letter : letters)  builder.append(letter); > return builder.toString(); > public static void main(String args[]) throws Exception  String str = "Hello Wolrd"; String result = shuffleString(str); System.out.println("Actual String : " + str); System.out.println("Shuffled String : " + result); > > 

Источник

How to shuffle a string in java

Get a couple of random indexes in the range of 0 to one less than the size of the array, say k and j, and switch the element at index k with that at index j. Do that a sufficiently large number of times. Solution: Note that a Stack is a List, and elements can therefore be accessed by index: it has methods get(x), set(x).

Shuffling strings in Java

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

Wow. Your algorithm is too complex for this problem! Try this for shuffling:

int n = array.length; char[] resChars = new char[n]; boolean flag = false; if (n % 2 != 0) < flag = true; char tmp = array[n / 2]; >for (int j = 0; j < n - 1; j += 2) < resChars[j] = array[j / 2]; resChars[j + 1] = array[n - 1 - (j / 2)] >if (flag) resChars[n - 1] = tmp; 

You can try something like this:

String str; char[] chars = str.toCharArray(); List list = new ArrayList<>(); for (char aChar : chars) < list.add(aChar); >Collections.shuffle(list); String result = list.toString().replaceAll("[\\[\\],]", ""); 

Java — How to shuffle characters in a string without using, Not sure why you wouldn’t want to use shuffle, unless it’s for school. 😉 And if you’re concerned with performance, you definitely can’t use any solution … Code samplepublic void shuffle(String input)

How to manually shuffle letters in a String

Your exception is caused by these lines of code:

 int counter = 0; while (inFile.hasNext()) < inFile.nextLine(); counter++; >//inFile no longer has next, will break when the for loop is entered String[] word = new String[counter]; for (int j = 0; j

The easy way to fix this is to redeclare the inFile and read from beginning again.

The best way to fix this is to use a dynamically sized ArrayList:

 int counter = 0; ArrayList word = new ArrayList(); while (inFile.hasNext())

This also makes your randomizing much more easy since you can do something sneaky with it.

Here’s the documentation on ArrayList.

The key, not the solution, to your second question lies add(int index, E element)

There is a way to shuffle on the fly as you read. You should figure that out, and if you get stuck, then come back.

Shuffle — Scramble a Word using Java, I wanted to scramble a String, to make it unreadable and so came up with this method: public String scrambleWord(String start_word) In other …

Shuffle middle characters of words in a string?

Let’s start by taking your existing scramble method and making it private ; we’ll also alter it to take two additional arguments (both of type char ) like

private static String scramble(char first, char last, String word) < String shuffledString = "" + first; // return shuffledString + last; //

Then we can use that method to implement a public version that scrambles the middle like

public static String scramble(String word) < if (word.length() < 3) < return word; >String middle = word.substring(1, word.length() - 1); return scramble(word.charAt(0), word.charAt(word.length() - 1), middle); > 

Edit Also, as pointed out below; you're using

String ww=inputFile.nextLine(); 

but your loop is on Scanner.hasNext() . If you change that to Scanner.next()

you should get white-space seperated tokens instead of line(s).

Step 1: I hope you understand that candidate words to be shuffled must have at least 4 characters; you omit smaller words by just returning them as they are.

Step 2: Choose a random index other than first and last one.

Step 3: flip this random selected character with the one in each right.

Performance Hint 1: You can also slightly improve in performance by omitting the semifinal index too. No need to select and flip the semifinal character as the final one (which is omitted) is in each right.

Performance Hint 2: Or you can omit the second index from random selection (index=1) and always flip with one on the left, do you see why?

This implementation is pretty easy, but I leave it to you as it is an assignment.

Java - How do I shuffle a deck? How do I make a string, I need to include the following methods. -Deck () constructor that creates an unshuffled deck. -A shuffle () method that does a perfect shuffle. -A …

Shuffle a stack of strings? [duplicate]

Note that a Stack is a List, and elements can therefore be accessed by index: it has methods get(x), set(x). Thanks to @andreas for pointing that out to me.

So, here's a very simple approach: (there are better, but I am going for simple).

Get a couple of random indexes in the range of 0 to one less than the size of the array, say k and j, and switch the element at index k with that at index j. Do that a sufficiently large number of times.

Java - Shuffle a stack of strings?, I have a simple stack of strings to represent a card deck already and I need to randomly move the cards into a new deck. I initially was going to just use …

Источник

How to Shuffle a String in Java [2 ways]

In this post I will be sharing how to shuffle a String in java with examples. There are two ways to achieve our goal. First, using shuffle method in the Collections class of util package. Second, using Random class.

1. Using Shuffle method [java.util.Collections.shuffle()]

It is a method of a Collections class that takes a list as the parameter and shuffles the elements of the list randomly. "UnsupportedOperationException" is thrown if the list given in the parameter section does not support the set operation.

1.1 Parameters of the Shuffle method

Syntax: Shuffle (List list, Random ran)
First parameter: list is the list that needs to be shuffled
Second parameter: ran is the randomness source to shuffle the list

Let us understand the functioning of the shuffle method with the help of an example before moving for our target to shuffle a string.

import java.util.*; public class ShuffleStringOne  public static void main(String[] args)  ArrayListString> list = new ArrayListString>(); list.add("cat"); list.add("dog"); list.add("cow"); list.add("bull"); list.add("snake"); list.add("goat"); // List before shuffling System.out.println("Original List : \n" + list); // Second parameter will be Random() Collections.shuffle(list, new Random()); System.out.println("\nShuffled List with Random() : \n" + list); // Second parameter will be Random(2). Collections.shuffle(list, new Random(2)); System.out.println("\nShuffled List with Random(2) : \n" + list); // Second parameter will be Random(4). Collections.shuffle(list, new Random(4)); System.out.println("\nShuffled List with Random(4) : \n" + list); > > 

Output:
Original List :
[cat, dog, cow, bull, snake, goat]

Shuffled List with Random() :
[cow, bull, goat, dog, snake, cat]

Shuffled List with Random(2) :
[cat, cow, bull, dog, goat, snake]

Shuffled List with Random(4) :
[cat, goat, cow, dog, snake, bull]

Here we can observe that the list we provided is shuffled. So for shuffling using the shuffle method, we compulsorily need a list to pass as the parameter.

In the above example, we initialized a list and added elements to that list. And with the help of Collection.shuffle() we got the shuffled list. Now for applying the shuffle method to solve the problem of shuffling a string, firstly we need a list in order to use the shuffle method. So we need to convert the string into a list with each character of the string as the individual elements of the list.

For converting a string into a list we need to use the split method for individually considering each character of the string and using the asList method to create a list out of it. To better understand this concept, the example for it is given below.

import java.util.*; public class ShuffleStringTwo  public static void main(String[] args)  String str="abcd"; ListString> letters = Arrays.asList(str.split("")); System.out.println(letters); > > Output: [a, b, c, d] 

So here in the above example, we converted the string "abcd" into the list with each character of the string as a distinct element of the list. Now we can apply the shuffle method on the list and get the shuffled form of the list and then combining the elements of the list to a string will give us our desired output.

Java Program to Shuffle a String Using shuffle() method

import java.util.*; public class ShuffleStringExample  public static void main(String[] args)  String str="abcd"; ListString> characters = Arrays.asList(str.split("")); Collections.shuffle(characters); String afterShuffle = ""; for (String character : characters)  afterShuffle += character; > System.out.println(afterShuffle); > > 

2. Using Random method

The word shuffle means to randomly arrange the characters, and for generating random values we have a random method that we can take into use for shuffling a string.

It is a class of util package. For using the random class refer to the example given below:

import java.util.Random; class RandomExample  public static void main( String args[] )  //creating an instance of random class Random rand = new Random(); //for specifying the range of the numbers int maxLimit = 25; int r1 = rand.nextInt(maxLimit); double r2=rand.nextDouble(); float r3=rand.nextFloat(); //Printing the values System.out.println("Random integer value from 0 to" + (maxLimit-1) + " : "+ r1); System.out.println("Random float value between 0.0 and 1.0 : "+r2); System.out.println("Random double value between 0.0 and 1.0 : "+r3); > > 

Output:
Random integer value from 0 to 24 : 17
Random float value between 0.0 and 1.0 : 0.9625353493043718
Random double value between 0.0 and 1.0 : 0.07440293

So using this we can generate random index numbers and access random characters of the strings through the index numbers generated by the Random class.

Java Program to Shuffle a String Using Random Class [Java 7]

import java.util.*; public class ShuffleStringExampleTwo  public static String ShuffleString(String text)  ListCharacter> alpha = new LinkedList<>(); for(char c:text.toCharArray()) alpha.add(c); > StringBuilder ans = new StringBuilder(); for (int i=0;itext.length();i++) int randomPosition = new Random().nextInt(alpha.size()); ans.append(alpha.get(randomPosition)); alpha.remove(randomPosition); > return ans.toString(); > public static void main(String[] args) System.out.println(ShuffleString("abcd")); > > 

The above code is compatible to be executed on the Java7 version but if we want to avoid the loop in the code, Java8 provide the advantage of the stream feature.

Java Program to Shuffle a String Using Random Class [Java 8]

import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; public class ShuffleStringExampleThree  public static String StringShuffle(String text)  ListCharacter> alpha = text.chars().mapToObj( c -> (char)c).collect(Collectors.toList()); StringBuilder ans = new StringBuilder(); IntStream.range(0,text.length()).forEach((index) ->  int rand = new Random().nextInt(alpha.size()); ans.append(alpha.get(rand)); alpha.remove(rand); >); return ans.toString(); > public static void main(String[] args) System.out.println(StringShuffle("abcd")); > > 

Hence, there can be different methods to solve the problem of shuffling a string, but these were two easy and basic ways to solve the problem.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

Programming for beginners

package com.sample.app; import java.util.Arrays; import java.util.Collections; import java.util.List; public class App  public static String shuffleString(String string)  ListString> letters = Arrays.asList(string.split("")); Collections.shuffle(letters); StringBuilder builder = new StringBuilder(); for (String letter : letters)  builder.append(letter); > return builder.toString(); > public static void main(String args[]) throws Exception  String str = "Hello Wolrd"; String result = shuffleString(str); System.out.println("Actual String : " + str); System.out.println("Shuffled String : " + result); > > 

Источник

Читайте также:  Caps to small in php
Оцените статью