2
\$\begingroup\$

A Base10 Pandigital Number is a number which uses all the digits 0-9 once:

  • 1234567890
  • 2468013579
  • etc...

My naive solution was just to use a bunch of nested loops to do this but it's quite slow. And I'm blanking on a more efficient way to do it? The following takes ~6 seconds.

IEnumerable<long> GeneratePandigital()
{
    var other=Enumerable.Range(0,10);

foreach(var a in other)
foreach(var b in other.Except(new int [] {a}))
foreach(var c in other.Except(new int [] {a,b}))
foreach(var d in other.Except(new int [] {a,b,c}))
foreach(var e in other.Except(new int [] {a,b,c,d}))
foreach(var f in other.Except(new int [] {a,b,c,d,e}))
foreach(var g in other.Except(new int [] {a,b,c,d,e,f}))
foreach(var h in other.Except(new int [] {a,b,c,d,e,f,g}))
foreach(var i in other.Except(new int [] {a,b,c,d,e,f,g,h}))
foreach(var j in other.Except(new int [] {a,b,c,d,e,f,g,h,i}))
{
    yield return a * 1000000000L + 
    b * 100000000L+
    c * 10000000L+
    d * 1000000+
    e * 100000+
    f * 10000+
    g * 1000+
    h * 100+
    i * 10+
    j;
}       
}
\$\endgroup\$
2
\$\begingroup\$

The easiest way to do this is to note that each value that is generated will be a permutation of the values 0 - 9. This will generate 10! = 3628800 possibilities. There are a number of algorithms to generate permutations, the easiest in this case would simply be to generate them in lexicographic order.

Wiki has a rundown of some algorithms you can use to generate permutations.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ sigh how did I not spot this... and I actually curate a combinatorics library on Nuget that's perfect for this. nuget.org/packages/Combinatorics - I blame the early hour. Thanks \$\endgroup\$ – Eoin Campbell Jun 5 '13 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.