如何在字符串中混洗字符

时间:2010-07-23 08:50:51

标签: java

如何将字符串中的字符混洗(例如hello可能是ehlol或lleoh或......)。我不想使用Collections.shuffle(...)方法,有什么更简单的吗?

17 个答案:

答案 0 :(得分:30)

我不知道更简单的事情。但是你可以使用Math.rand()函数在字符长度范围内生成一个随机数而不用替换,这样就可以得到一个随机输出

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
*/

答案 1 :(得分:12)

性能不佳,但在我看来相当可读:

public static String shuffleString(String string)
{
  List<String> letters = Arrays.asList(string.split(""));
  Collections.shuffle(letters);
  String shuffled = "";
  for (String letter : letters) {
    shuffled += letter;
  }
  return shuffled;
}

答案 2 :(得分:7)

这个怎么样:

public static String shuffle(String text) {
    char[] characters = text.toCharArray();
    for (int i = 0; i < characters.length; i++) {
        int randomIndex = (int)(Math.random() * characters.length);
        char temp = characters[i];
        characters[i] = characters[randomIndex];
        characters[randomIndex] = temp;
    }
    return new String(characters);
}

答案 3 :(得分:3)

class ShuffleString
{

    public static String shuffle(String s)
    {

        String shuffledString = ""; 

        while (s.length() != 0)
        {
            int index = (int) Math.floor(Math.random() * s.length());
            char c = s.charAt(index);
            s = s.substring(0,index)+s.substring(index+1);
            shuffledString += c;
        }

        return shuffledString;

    }

}


public class foo{
    static public void main(String[] args)
    {

        String test = "hallo";
        test = ShuffleString.shuffle(test);
        System.out.println(test);
    }
}

输出: ahlol

答案 4 :(得分:2)

多么烦人的问题。我终于结束了这个:

import java.util.Collections;
import com.google.common.primitives.Chars;
import org.apache.commons.lang3.StringUtils;

String shuffle(String s) {
    List<Character> chars = Chars.asList(s.toCharArray());
    Collections.shuffle(chars);
    return StringUtils.join(chars.stream().toArray());
}

是的,两个图书馆:)

答案 5 :(得分:1)

E.g:

static String shuffle(String text){
    if (text.length()<=1)
        return text;

    int split=text.length()/2;

    String temp1=shuffle(text.substring(0,split));
    String temp2=shuffle(text.substring(split));

    if (Math.random() > 0.5) 
        return temp1 + temp2;
    else 
        return temp2 + temp1;
}    

答案 6 :(得分:1)

不确定为什么你不想使用shuffle,除非它是为了学校。 ;)

如果你关注性能,你绝对不能使用任何用“+”连接字符串的解决方案。

这是我能提出的最紧凑的解决方案:

public static String shuffle(String string) {
    if (StringUtils.isBlank(string) {
        return string;
    }

    final List<Character> randomChars = new ArrayList<>();
    CollectionUtils.addAll(randomChars, ArrayUtils.toObject(string.toCharArray()));
    Collections.shuffle(randomChars);
    return StringUtils.join(randomChars, "");
}

答案 7 :(得分:1)

没有外部库,对于那些不介意使用Collections.shuffle()的人:

static String shuffle(String string){

    List<Character> list = string.chars().mapToObj(c -> new Character((char) c))
                                         .collect(Collectors.toList());
    Collections.shuffle(list);
    StringBuilder sb = new StringBuilder();
    list.forEach(c -> sb.append(c));

    return sb.toString();
}

答案 8 :(得分:0)

        String shuffled;
        do {
            shuffled = Stream.of(text.split("")).sorted((o1, o2) -> ThreadLocalRandom.current().nextInt(3) - 1).collect(Collectors.joining());
        }while(shuffled.equals(text));

答案 9 :(得分:0)

另一个使用 Stream API 的简短实现:

 String shuffle(String str) {       
    return new Random().ints(0, str.length()).distinct().limit(str.length()) // shuffle indexes
            .mapToObj(i->""+str.charAt(i)).collect(Collectors.joining());    // collect letters
 }

答案 10 :(得分:0)

使用 commons-lang3

import org.apache.commons.lang3.ArrayUtils;

String shuffle(String text) {
    char[] chars = text.toCharArray();
    ArrayUtils.shuffle(chars);
    return String.valueOf(chars);
}

答案 11 :(得分:0)

在 Kotlin 中,您可以执行以下操作。

val helloCharArray = "hello".toCharArray()
helloCharArray.shuffle()
val shuffledHello = helloCharArray.concatToString()

答案 12 :(得分:0)

在Java 8+中,可以使用Collectors.shuffle(...)分三行完成,如下所示:

  1. Convert the String into a List of Characters
  2. Shuffle the list
  3. Convert the shuffled List of Characters back into a String

代码:

public static String shuffle(final String str) {
    List<Character> chars = str.chars().mapToObj(e->(char)e).collect(Collectors.toList());
    Collections.shuffle(chars);
    return chars.stream().map(e->e.toString()).collect(Collectors.joining());
}

演示:

Rextester demo

答案 13 :(得分:0)

如果您仍希望稍后恢复原始String,请尝试以下操作:

public static class ShuffledString
{
    private List<Integer> indices;
    private String string;

    public ShuffledString(List<Integer> indices, String string)
    {
        this.indices = indices;
        this.string = string;
    }

    public List<Integer> getIndices()
    {
        return indices;
    }

    public String getRegularString()
    {
        StringBuilder stringBuilder = new StringBuilder();

        for (int stringIndex = 0; stringIndex < indices.size(); stringIndex++)
        {
            int characterIndex = indices.indexOf(stringIndex);
            stringBuilder.append(string.charAt(characterIndex));
        }

        return stringBuilder.toString();
    }
}

public static ShuffledString shuffle(String input)
{
    List<Integer> indices = new ArrayList<>();

    StringBuilder output = new StringBuilder(input.length());
    while (indices.size() < input.length())
    {
        int randomIndex;

        while (indices.contains(randomIndex = (int) (Math.random() * input.length())))
        {

        }

        indices.add(randomIndex);
        output.append(input.charAt(randomIndex));
    }

    return new ShuffledString(indices, output.toString());
}

答案 14 :(得分:0)

这里的代码既不需要递归,也不需要转换为Collection。

public static String shuffle(String string) {
    StringBuilder sb = new StringBuilder(string.length());
    double rnd;
    for (char c: string.toCharArray()) {
        rnd = Math.random();
        if (rnd < 0.34)
            sb.append(c);
        else if (rnd < 0.67)
            sb.insert(sb.length() / 2, c);
        else
            sb.insert(0, c);
    }       
    return sb.toString();
}

答案 15 :(得分:0)

您可以迭代所有角色,将每个角色与下一个角色进行比较。然后如果Math.rand()&gt; 0.5将此字符与下一个字符交换,否则转到下一个字符。

答案 16 :(得分:-1)

import java.util.Random;

public class carteRecharge {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String characters = "AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn1234567890";

        Random rand = new Random();

        //Nombre de caratère à tirer 
        int length = 20;

        //La variable qui contiendra le mot tire
        String randomString = "";

        //
        char[] text = new char[length];

        for(int i = 0; i < length; i++) {
            text[i] = characters.charAt(rand.nextInt(characters.length()));

        }


        for(int i=0; i<text.length; i++) {
            randomString += text[i];
        }

        System.out.print(randomString);


    }

}