views:

269

answers:

2

The question is :

How to generate a list of all possible 3-chars strings in c# ?

+25  A: 
IEnumerable<string> GetAllStrings(params char[] inputCharacterSet) {
    return from n in inputCharacterSet
           from m in inputCharacterSet
           from k in inputCharacterSet
           select new string(new [] { n, m, k });
}
Mehrdad Afshari
Much more elegant that what I would have wrote (3 for loops, spitting out strings to stdout :D)
Mark
This is correct, so I'll toss in a point, but I think it might be clearer as nested for loops.
Steven Sudit
@Mark: LINQ is certainly fancier, but given that this looks like a homework question, I'm concerned that it might be overkill.
Steven Sudit
Steven: LINQ is rarely suitable for doing homework... and that's why it's perfectly suited for answering them ;)
Mehrdad Afshari
@Mehrdad: I can only agree.
Steven Sudit
+7  A: 
public IEnumerable<String> Get3CharStrings(char[] domain)
{
    foreach(char a in domain)
     foreach(char b in domain)
      foreach(char c in domain)
       yield return "" + a + b + c;
}

EDIT: This is actually quite a bit slower than the LINQ solution posted by Mehrdad, although most of the difference lies in the use of return "" + a + b + c instead of return new string(new[] { a, b, c}).

Actual statistics (26-character alphabet, 10k iterations:

Mehrdad's code: 72.983 seconds
My code: 127.205 seconds
My code with Mehrdad's return statement: 75.055 seconds

Yuliy
This is less elegant than the LINQ, and the way the letters are concatenated is particularly ugly.
Steven Sudit
Eh: it's readable, and I'd expect the jit-optimizer to fix the normal problems with string concatentation here.
Joel Coehoorn
@Joel: Apparently not.
Steven Sudit
I liked the Linq solution, but actually this one is easier to read, which makes it better
Thomas Levesque
If the concatenation were better, I'd say it was about the same.
Steven Sudit