char数组,制作句子,并检查单词列表中是否存在单词

时间:2017-05-17 05:54:24

标签: c# linq

我一直试图制作一个Anagram解算器。我在一个句子中读到的,我分裂为字符,也允许空格。然后将它们存储在Char数组中。我有一个列表单词,我也读过。但是我想知道在char数组中是否有一个很好的方法来随机化序列,它必须考虑不将空间放在索引0或索引最大值。 我已经将wordlist读入像这样的

字符串数组中
String[] gh = File.ReadAllLines("words.txt");

这只是一个简单的控制台应用程序,它只是帮助我解决晨报问题。

编辑: 我想要的是一个交换字符串中字符的好方法吗?

EDIT2: 也许我应该更具体,我不希望它完全随机。有什么方法可以循环并重新排列字符,所以我不会两次得到相同的单词/单词。

1 个答案:

答案 0 :(得分:1)

你想要的是排列,而不是随机化。要计算列表的所有排列,最简单的方法是通过递归:

private static void Swap(ref char a, ref char b)
{
    if (a == b) return;

    a ^= b;
    b ^= a;
    a ^= b;
}

public static void GetPer(char[] list)
{
    int x = list.Length - 1;
    GetPer(list, 0, x);
}

private static void GetPer(char[] list, int k, int m)
{
    if (k == m)
    {
        Console.WriteLine(list);
    }
    else
    {
        for (int i = k; i <= m; i++)
        {
            Swap(ref list[k], ref list[i]);
            GetPer(list, k + 1, m);
            Swap(ref list[k], ref list[i]);
        }
    }
}

static void Main()
{
    string str = "sagiv";
    char[] arr = str.ToCharArray();
    GetPer(arr);
}

(来自Peter's answer