Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从字符串中为字符指定一个随机整数_Java_Arrays_String_Random_Character - Fatal编程技术网

Java 从字符串中为字符指定一个随机整数

Java 从字符串中为字符指定一个随机整数,java,arrays,string,random,character,Java,Arrays,String,Random,Character,因此,我试图用java制作一个字谜工具,在其中插入一个单词/字符串,它会为该单词生成一个字谜。可能有比我将要展示的更简单或更好的方法来做到这一点,但我仍然很好奇。以下是我想做的: 让我们说这个词是:苹果 我想做的是给该字符串中的每个字符分配一个randomInt100。让我们举个例子 a-35、p-54、p-98、l-75、e-13 之后,我希望我的程序将数字从最小到最大排序,然后用数字的指定字符打印新字符串,从最小到最大。在我的情况下,字谜应该是: eaplp 说了这么多,我陷入困境的地方是如

因此,我试图用java制作一个字谜工具,在其中插入一个单词/字符串,它会为该单词生成一个字谜。可能有比我将要展示的更简单或更好的方法来做到这一点,但我仍然很好奇。以下是我想做的:

让我们说这个词是:苹果

我想做的是给该字符串中的每个字符分配一个randomInt100。让我们举个例子

a-35、p-54、p-98、l-75、e-13

之后,我希望我的程序将数字从最小到最大排序,然后用数字的指定字符打印新字符串,从最小到最大。在我的情况下,字谜应该是: eaplp

说了这么多,我陷入困境的地方是如何从字符串数组中为一个字符分配一个随机数,而不实际将该字符更改为该数字,然后像我在顶部所说的那样打印出新修改的字符串。伪代码或真实代码都很好

谢谢使用树形图。基本思路如下:

TreeMap<Integer, Character> myMap = new TreeMap<Integer, Character>();
for (int i = 0; i < myString.length(); i++) {
  myMap.put((int)(Math.random() * 100), myString.charAt(i));
}

for (Map.Entry<Integer, Character> entry : myMap.entrySet()) {
  System.out.print(entry.getValue());
}
System.out.println();

上面可能有一些编译错误;我没有检查就写了它,但是这个过程应该可以工作。

如果您使用的是Java 8,一个简单的解决方案是索引的无序列表:

String word = "apple";
List<Integer> indices = IntStream.range(0, word.length()).collect(Collections.toList());
Collections.shuffle(indices);
indices.stream().mapToObj(word::charAt).forEach(System.out::print);
或者,您可以将其全部放在一个难以读取的流操作中:

word.chars().boxed().collect(Collectors.toMap(random::nextInt, Function.identity()))
    .entrySet().stream().sorted(Map.Entry.comparingByKey())
    .map(e -> Character.toChars(e.getValue()))
    .forEach(System.out::print);

使用某种映射。另一种实现可能是将字符串中的每个字符放入一个数组,对数组进行随机排序(即使用Knuth shuffle),然后打印数组中的每个字符。
Random random = new Random();
Map<Integer, Char> map = new TreeMap<>();
IntStream.range(0, word.length()).forEach(c -> map.put(random.nextInt(), c));
map.entrySet().stream().map(Map.Entry::getValue).forEach(System.out::print);
word.chars().boxed().collect(Collectors.toMap(random::nextInt, Function.identity()))
    .entrySet().stream().sorted(Map.Entry.comparingByKey())
    .map(e -> Character.toChars(e.getValue()))
    .forEach(System.out::print);