【问题标题】:word permutation with repetition where words are used multiple times带有重复的单词排列,其中单词被多次使用
【发布时间】:2014-09-21 15:37:27
【问题描述】:

我正在尝试从一组单词中生成一个组合列表。

我一直在使用http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G 来生成组合

var words = File.ReadAllLines(@"C:\words.txt");
var allCombinations = new List<string>();

var combis = new Combinations<string>(words, 3, GenerateOption.WithRepetition);
allCombinations.AddRange(combis.Select(c => c.Aggregate((j, k) => j + "-" + k)));

给定 3 个单词“Word1”、“Word2”和“Word3”,我得到一个组合列表,例如

"Word1-Word1-Word1"
"Word1-Word1-Word2"
"Word1-Word1-Word3"

等等

但我缺少一个单词多次使用的组合

"Word1-Word2-Word1"
"Word1-Word3-Word1"
"Word2-Word1-Word2"

如何获得多次使用单词的单词组合?

【问题讨论】:

    标签: c# permutation


    【解决方案1】:

    你的情况基本上就像以3为底数:

    0 0 0
    0 0 1
    0 0 2
    0 1 0
    0 1 1
    0 1 2
    0 2 0
    // and so on..
    

    如果您使用的库没有实现您需要的逻辑,您可以自己实现。思路如下:

    public static IEnumerable<string> Permutate(string[] words)
    {
        // 0 0 0
        int[] indices = new int[words.Length];
    
        // yield 0 0 0
        yield return string.Join("-", indicies.Select(x => words[x]));
    
        // moves to 0 0 1 and so on, returns false after 3 3 3
        while (CountStep(indicies))
        {
            // yield next permutation
            yield return string.Join("-", indicies.Select(x => words[x]));
        }
    }
    

    实现 CountStep 也不难:

    public static bool CountStep(int[] arr)
    {
        // assumes we count in base N for an N sized array
        var maxDigit = arr.Length - 1;
    
        for (var i = arr.Length - 1; i >= 0; i--)
        {
            if (arr[i] < maxDigit)
            {
                arr[i]++;
    
                for (var j = i + 1; j < arr.Length; j++)
                {
                    arr[j] = 0;
                }
    
                return true;
            }
        }
    
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多