代码之家  ›  专栏  ›  技术社区  ›  Vishnu Pradeep

C#程序通过添加“.”来查找单词中不能生成的单词在角色之间?

  •  2
  • Vishnu Pradeep  · 技术社区  · 15 年前

    我在聊天室里问了这个问题。但没有答案,所以我把问题贴在这里。

    它有4个字符。通过添加“.”在两个字符之间,你可以写为a.b.c.d

    规则
    字符之间只能使用一个点
    可以在单词中使用多个点
    可以有没有“.”的字符在他们中间。例如(ab或abcd)

    一些答案
    a、 公元前
    a、 密件抄送
    ab.cd公司

    a、 光盘
    a、 公元前

    abc.d.公司

    有多少字是可能的。如何编写一个用c语言查找的程序?

    编辑

    4 回复  |  直到 15 年前
        1
  •  3
  •   Guffa    15 年前

    你可以递归地做。

    (abcd)的所有可能组合是:

    a + . + all combinations of (bcd)
    ab + . + all combinations of (cd)
    abc + . + all combinations of (d)
    abcd
    

    public static IEnumerable<string> GetCombinations(string str) {
      for (int i = 1; i < str.Length; i++) {
        foreach (string s in GetCombinations(str.Substring(i))) {
          yield return str.Substring(0, i) + "." + s;
        }
      }
      yield return str;
    }
    

    用法:

    foreach (string s in GetCombinations("abcd")) Console.WriteLine(s);
    
        2
  •  8
  •   Jon Skeet    15 年前

    你不需要为此编写程序。

    对于n个字符的单词,有n-1个位置可以有一个点(即在每对字符之间)。每个位置要么有点要么没有。

    n-1号 可能的话。

    如果你 真正地

    using System;
    
    class Test
    {
        static void Main(string[] args)
        {
            // Argument validation left as an exercise for the reader
            string word = args[0];
            Console.WriteLine("Word {0} has {1} possibilities",
                              word, Math.Pow(2, word.Length - 1));
        }
    }
    

    编辑:注意,这假设原始单词(没有点)仍然有效。如果你不想数数,从结果中减去一。

    编辑:我已将计算更改为使用 Math.Pow 以便:

    • 更清楚了
        3
  •  2
  •   Paolo Tedesco    15 年前

    组合数:

    string s = "abcd";
    int len = s.Length;
    int combinations = 1 << (len - 1);
    

    编辑

    int combinations = 1 << (len - 1) - 1;
    

    如果不是有效的组合,则删除不包含点的单词。

        4
  •  0
  •   The Archetypal Paul    15 年前

    如果字符串的长度为n,则可以在n-1个位置放置a。

    在任何地方,都可能有一个。或者不,也就是说,有两种选择。