【问题标题】:Assigning a character a random integer from a string从字符串中为字符分配一个随机整数
【发布时间】:2015-08-05 02:35:28
【问题描述】:

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

假设这个词是:苹果

我想做的是为该字符串中的每个字符分配一个 randomInt(100)。所以让我们说作为一个例子

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

之后,我希望我的程序将数字从小到大排序,然后打印带有数字分配字符的“新”字符串,从小到大。在我的情况下,字谜是: eapp

总而言之,我被困在的地方是我如何从字符串数组中实际为一个字符分配一个随机数,而无需实际将该字符更改为该数字,然后将新修改的字符串打印出来就像我在上面说的那样。伪代码或真实代码都会很棒。

谢谢

【问题讨论】:

  • 使用某种地图。
  • 另一种实现可能是将字符串中的每个字符放入一个数组中,对数组进行随机排序(即使用 Knuth shuffle),然后打印数组中的每个字符。

标签: java arrays string random character


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您使用的是 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-11
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-04
      相关资源
      最近更新 更多