Hi all, just wondering if anyone had an algorithm lying around that printed all possible combos from 0000 to 9999 (trying to crack code into old phone and new to learning C#)...Million thanks. Bela
Why complicate matters?
for (Int32 index = 0; index < 10000; index++)
Console.Out.WriteLine(index.ToString("0000"));
Since you're commenting that you're outputting to a label, with linefeeds between each value, here's a better way:
List<String> values = new List<String>();
for (Int32 index = 0; index < 10000; index++)
values.Add(index.ToString("0000"));
label1.Text = String.Join(
Environment.NewLine,
values.ToArray());
Try that and see if it gives you what you want.
Like Lasse said, simply print them in sequence. But you can do even simpler with Linq;
Enumerable.Range(0, 9999).ToList().ForEach(Console.WriteLine);
You could avoid the "ToList" as well, if you had a helper function (which I normally would have in a Utilities class);
public static void ForEach<T>(this IEnumerable<T> elements, Action<T> action)
{
foreach (var element in elements) { action(element); }
}
Note that this utility method is not strictly required for it to work, but would greatly diminish the memory requirements (since ToList actcually creates a list of all the numbers in memory).
Console.WriteLine("0000");
Console.WriteLine("0001");
Console.WriteLine("0002");
Console.WriteLine("0003");
// snip everything in the middle
Console.WriteLine("9998");
Console.WriteLine("9999");
For those of you who are lacking of humor, don't try this at home.
if you want to print the leading zeros too:
for(int iC1 = 0; iC1 < 10000; iC1++)
{
if(iC1 < 10)
{
Console.WriteLine("000" + iC1.ToString());
}
else if(iC1 < 100)
{
Console.WriteLine("00" + iC1.ToString());
}
else if(iC1 < 1000)
{
Console.WriteLine("0" + iC1.ToString());
}
else
{
Console.WriteLine(iC1.ToString());
}
}
I know this solution is not elegant, but it's easyer to understand this way.
btw: you have to compile this as C# Console Application, not as Windows Forms Application.
I think Digitalex's solution is the most elegant but too memory-consuming.
Here's a better option:
foreach (var number in Enumerable.Range(0, 10000).Select(i => i.ToString("0000")))
Console.WriteLine(number);