0

I have this profoundly embarrassing code, that takes a phrase of 8 words, and then generates every combination of the letters of those words. Later it compares them to a dictionary and returns back a list of the true words.

Yes, you can see my problem, I can only take 8 words, how do I make it more dynamic to take as many words as suitable? I realise I can count the array of words and use the count to make a recursive method that runs to that number, but for the life of me can't see how it works.

 private List<string> CreateAnagrams(string phrase)
    {
        phrase = phrase.ToLower();
        string[] GeneratedWords = phrase.Split(' ');

        List<string> AllGenWords = new List<string>();

        foreach (var letter0 in GeneratedWords[0]) {
          foreach (var letter1 in GeneratedWords[1]) {
                foreach (var letter2 in GeneratedWords[2]) {
                    foreach (var letter3 in GeneratedWords[3]) {
                        foreach (var letter4 in GeneratedWords[4]) {
                            foreach (var letter5 in GeneratedWords[5]) {
                                foreach (var letter6 in GeneratedWords[6]) {
                                    foreach (var letter7 in GeneratedWords[7]) {
                                        AllGenWords.Add(letter0.ToString() + letter1.ToString() + letter2.ToString() + letter3.ToString() + letter4.ToString() + letter5.ToString() + letter6.ToString() + letter7.ToString());
                                        }
                                }
                            }
                        }
                    }
                }
            }

        }
        return AllGenWords;
    }
netchicken
  • 355
  • 2
  • 7
  • 20
  • 1
    See http://stackoverflow.com/a/3098381/88656 – Eric Lippert Oct 28 '16 at 20:47
  • Sorry Eric, this may be a duplicate, and the answer may be in the other thread, but I find it hard to parse, and wonder if someone has a clearer example. – netchicken Oct 28 '16 at 21:02
  • A word is a sequence of chars. Make a sequence of words. So that is an `IEnumerable>`. Feed that into my `CartesianProduct` helper. That gives you back a *different* `IEnumerable>`. If you give it `{{A, B}, {C, D, E}}` it gives you back `{ {A, C}, {A, D}, {A, E}, {B, C}, ...` etc. – Eric Lippert Oct 28 '16 at 21:17
  • So put it all together. `var generatedWords = phrase.Split(' ').CartesianProduct().Select(s => string.Join("", s)).ToList();`. It's *one line of code*. – Eric Lippert Oct 28 '16 at 21:22
  • Here: https://dotnetfiddle.net/zXFbgg is that sufficiently clear? – Eric Lippert Oct 28 '16 at 21:30
  • Thanks so much!!!!! I really appreciate the time you took to help a less experienced programmer like me to understand it. – netchicken Oct 29 '16 at 01:11

0 Answers0