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;
}
}
-
\$\begingroup\$ users.telenet.be/vdmoortel/dirk/Maths/permutations.html \$\endgroup\$Dave Jarvis– Dave Jarvis2013年06月05日 16:54:29 +00:00Commented Jun 5, 2013 at 16:54
1 Answer 1
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.
-
\$\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– Eoin Campbell2013年06月05日 08:55:25 +00:00Commented Jun 5, 2013 at 8:55