The problem may have been asked else where but i cannot find the solution to my problem. The problem is not language specific, the same problem can be asked in python. The task is algorithm to generate a list of strings like Enumerable.Range
, but the chars are not only limited to 1, 2, 3... but can be any sequence of characters. The simplest sample is:
TestCase 1:
input:
baseChars: ['a','b'],
required string length: 2
output:
['aa','ab','ba','bb']
TestCase 2:
baseChars: ['a','b']
required string length: 1
output:
['a','b']
The function is working well:
static IList<string> baseChars = new List<string>() { "0", "1", "2", "3" };
static void CharsRange1(string prefix, int pos)
{
if (pos == 1)
{
foreach (string s in baseChars)
{
Console.WriteLine(prefix + s);
}
}
else
{
foreach (string s in baseChars)
{
CharsRange1(prefix + s, pos - 1);
}
}
}
Expected and actual output(newlines replaced with comma to save space):
000, 001, 002, 003, 010, 011, 012, 013, 020, 021, 022, 023, 030, 031, 032, 033, 100, 101, 102, 103, 110, 111, 112, 113, 120, 121, 122, 123, 130, 131, 132, 133, 200, 201, 202, 203, 210, 211, 212, 213, 220, 221, 222, 223, 230, 231, 232, 233, 300, 301, 302, 303, 310, 311, 312, 313, 320, 321, 322, 323, 330, 331, 332, 333
The problem is encapsule this function as a library, so return type should be IEnumerable<string>
, so memory won't explode even for large input. but my code cannot return anything:
static IEnumerable<string> CharsRange2(string prefix, int pos)
{
if (pos == 1)
{
foreach (string s in baseChars)
{
yield return prefix + s;
}
}
else
{
foreach (string s in baseChars)
{
// here if i yield return then won't compile
// i thought at the end of recursive loop it will return
CharsRange2(prefix + s, pos - 1);
}
}
}
the main:
static void Main(string[] args)
{
//CharsRange1("", 3);//working
foreach (string s in CharsRange2("", 3))
{
Console.WriteLine(s);//nothing
}
Console.WriteLine("end");
Console.ReadKey();
}
Can anybody help? I've put my code in github. Also appreicated if you can change my implementation to non-recursive but keep the function return type.
CharsRange2(prefix + s, pos - 1);
So you are calling the function recursively and, umm, ignoring the results? I suspect you meant toforeach
over that and useyield return
. – mjwills