将字符赋值为字符串中的随机整数



所以我试图在java中制作一个变位工具,您可以在其中插入一个单词/字符串,并为该单词吐出一个变位。可能有比我将要展示的更简单或更好的方法来做到这一点,但我仍然很好奇。下面是我想要做的:

假设单词是:apple

我要做的是给字符串中的每个字符分配一个randomInt(100)。例如

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

之后,我希望我的程序将数字从最小到最大排序,然后打印带有数字分配字符的"new"字符串,从最小到最大。在我的例子中,这个字谜应该是: eaplp

说了这么多,做了这么多,我卡住的地方是我如何从字符串数组中给一个字符分配一个随机数,而不实际地将该字符更改为该数字,然后像我在上面所说的那样打印出新的修改字符串。伪代码或真正的代码将是伟大的。

谢谢

使用TreeMap<Integer, Character>。基本思想如下:

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();

TreeMap自动按键对条目进行排序;因此,您不必执行单独的排序。


编码字谜的一种更简单的方法是将字符串转换为字符列表,然后使用Collections.shuffle()。基本思想:

List<Character> myLst = new ArrayList<Character>(myString.toCharArray());
Collections.shuffle(myLst);
for (Character c : myLst)
  System.out.print(c);
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);

这可以通过一个中间的Map来完成,但它有点尴尬和难以遵循:

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);

最新更新