【问题标题】:How to Find All Possible Anagrams?如何找到所有可能的字谜?
【发布时间】:2019-02-04 15:44:37
【问题描述】:

所以我想做一个字谜解码器,我想知道是否有更好的方法来做到这一点。我目前的代码是这样的:

Random random = new Random();
char[] splitAnagram = chosenAnagram.toCharArray();
int[] presetNumbers = new int[chosenAnagram.length()];
int i = 0;
while (true) {
    TimeUnit.MILLISECONDS.sleep(10);
    int thisRandom = random.nextInt(chosenAnagram.length());
    if (Arrays.asList(presetNumbers).contains(thisRandom) == true)
        presetNumbers[i] = thisRandom;
    else
        continue;
    i++;
    if (i > chosenAnagram.length())
        break;
}
for (int l = 0; l < chosenAnagram.length(); l++) {
    System.out.println(splitAnagram[presetNumbers[l]]);
}

基本上,它会为每个字母生成随机数,以便“打乱”单词。它是有缺陷的,因为它甚至不应该循环,只需进行一次争夺,但总的来说它看起来真的很慢并且容易出错(我睡了 10 毫秒,因为它只能在每次系统时间更改时生成随机数)。

我想知道是否有其他算法可以解决这个问题,或者我可以使用一个可能的 API。谢谢!

P.S 我正在运行 Eclipse Photon,以防你知道它的插件。

【问题讨论】:

  • Arrays.asList(presetNumbers).contains(thisRandom) 始终为假。仔细查看类型(尝试将列表分配给变量)。
  • 你为什么要使用随机数?要为给定单词列出所有可能的字谜,不需要随机。它只会在嵌套循环中重新排列。可能是我误会了,你能帮我解决一下吗?
  • @Yunnosch 我正在使用随机数,因为我不知道如何在没有它们的情况下重新排列数组。
  • 有一种更简单的方法来查找字谜。将您的字典(即单词列表)转换为一个数组,其中每个元素都是一个字谜列表,并且每个键都是通过按字母顺序对这些单词的字母进行排序来生成的。例如,字典 ["act", "cat", "dog", "fish", "god"] 将被转换为 ["act" => ["act", "cat"], "dgo" = > [“狗”,“神”],“ifhs” => [“鱼”]]。您只需执行一次。然后找到一个单词的所有字谜,按字母顺序对其字母进行排序,并使用结果访问这个数组。

标签: java random anagram


【解决方案1】:

我从this Stackoverflow 帖子中找到了使用Fisher--Yates Shuffle 的方法。以下是代码的结果:

@SuppressWarnings("unchecked")
private void beginDecoding(String chosenAnagram) throws InterruptedException {
    Random random = new Random();
    List madeAnagrams = new ArrayList();
    int factorial = 1;
    for (int i = chosenAnagram.length(); i > 0; i--) {
        factorial = i * factorial;
    }
    System.out.println(factorial);
    while (true) {
        if (madeAnagrams.size() == factorial) {
            break;
        }
        TimeUnit.MILLISECONDS.sleep(10);
        char[] splitAnagram = chosenAnagram.toCharArray();
        for (int i = chosenAnagram.length() - 1; i > 0; i--) {
            int index = random.nextInt(i + 1);
            char letter = splitAnagram[index];
            splitAnagram[index] = splitAnagram[i];
            splitAnagram[i] = letter;
        }
        String returnAnagram = new String(splitAnagram);
        if (!madeAnagrams.contains(returnAnagram)) {
            madeAnagrams.add(returnAnagram);
            System.out.println(returnAnagram);
        }
        else
            continue;
    }
}

【讨论】:

  • 不要自己写shuffle,使用语言内置的。
猜你喜欢
  • 2019-10-20
  • 2022-12-05
  • 2017-12-04
  • 2013-12-29
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
相关资源
最近更新 更多