c# - 如何在for循环中生成尽可能多的for循环?

标签 c# algorithm linq

我正在尝试使用 List<string> 生成所有可能的单词组合.例如,如果我想生成 2 的所有可能的单词组合,该函数将如下所示:

public static List<string> GenerateWordsOf2(List<string> uniqueWords)
{
    List<string> unique2Words = new();
    for (int i = 0; i < uniqueWords.Count; i++)
    {
        for (int j = 0; j < uniqueWords.Count; j++)
        {
            if (i != j)
            {
                unique2Words.Add(uniqueWords[i] + " " + uniqueWords[j]);
            }
        }
    }
    return unique2Words;
}

这按预期工作,但是当我想生成例如 3 的唯一单词时,我需要为此编写一个新函数,在其中创建另一个循环。也许有更有效的方法来做到这一点,比如制作一个函数,它接受一个数字并生成那么多独特的单词列表?

最佳答案

您可以使用一个 for 循环迭代地执行此操作,如下所示。

  • 从仅包含“空句”的列表开始。
  • 在每个步骤中,将每个单词添加到每个先前构建的句子中。

假设 uniqueWords 是“a”、“b”、“c”。

  • 一开始,您将有 {""}。
  • 在第一步之后,您将拥有 {"a", "b", "c"}
  • 在第二步之后,你将有 { "a+a", "a+b", "a+c", "b+a", "b+b", "b+c", "c +a", "c+b", "c+c"
  • 经过第三步,你会得到{ "a+a+a", "a+b+a", ... }

唯一需要的修改是过滤掉重复项。这导致类似这样的(未优化的)示例:

使用系统; 使用 System.Collections.Generic;

public class SentenceGenerator
{
    public static List<List<string>> ExpandSentences(List<List<string>> partialSentences, List<string> uniqueWords)
    {
        var newSentences = new List<List<string>>();
        foreach(var sentence in partialSentences)
        {
            foreach(var word in uniqueWords)
            {
                if(sentence.Contains(word))
                {
                    continue;
                }
                
                // Make a copy of the old sentence
                var newSentence = new List<string>(sentence);
            
                // Add a new word
                newSentence.Add(word);
                
                newSentences.Add(newSentence);
            }
        }
        
        return newSentences;
    }
    
    public static void Main()
    {
        var uniqueWords = new List<string>() {
            "hello",
            "beautiful",
            "world", 
            "full",
            "of",
            "people" };
        
        var sentences = new List<List<string>>() { 
            // Start with an empty sentence
            new List<string>() 
        };
        
        for(int i = 1; i <= 3; i++)
        {
            sentences = ExpandSentences(sentences, uniqueWords);
        }
        
        System.Console.WriteLine("Generated " + sentences.Count + " sentences.");
        foreach(var sentence in sentences)
        {
            System.Console.WriteLine(string.Join(" ", sentence));
        }
    }
}

Run it online (IDEOne)

关于c# - 如何在for循环中生成尽可能多的for循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72641581/

相关文章:

c# - 如何从 Span<T> 创建 Memory<T>?

algorithm - 在图中选择最佳可能的初始位置以最大化潜在邻居

c# - 自托管wcf服务的调用功能

algorithm - 最小化插入、删除和部分和的成本的整数列表的数据结构

java - 插入排序无法正常工作

c# - 如果我在不同时间使用同一 Linq 查询的不同字段, Entity Framework 是否会多次查询数据库?

c# - 为什么 Enumerable 不继承自 IEnumerable<T>

c# - Case 语句中的 Linq 表达式

c# - C#属性类的继承

c# - 在 Unity 中的类型之间共享生命周期管理器?