字典序排列
作者:Moritz Lenz
https://projecteuler.net/problem=24
排列是指对象的有序排列。例如,3124 是数字 1、2、3 和 4 的一种可能排列。如果所有排列按数字或字母顺序排列,我们称之为字典序。0、1 和 2 的字典序排列为:
012 021 102 120 201 210
数字 0、1、2、3、4、5、6、7、8 和 9 的第百万个字典序排列是什么?
use v6;
# idea: the last 9 digits can be permuted in 9! = 362880 ways. so there are
# 9! numbers that start with a 0, 9! numbers that start with a 1 etc.
#
# So to get the first digit, divide our target by 9!, and the rounded result
# is the first digit.
#
# then we remove the first digit from the pool of available digits, divide
# the rest by 8!, round, store result in $n. Then the $n'th lowest available
# digit is the second digit that we search.
my $target = 1e6;
my $t = $target;
sub f(Int $x){
[*] 1..$x;
}
my @f = map &f, 0..9;
my @available = 0 .. 9;
say gather {
for reverse(0..9) -> $marker {
my $n = ceiling($t / @f[$marker])- 1;
$t -= $n * @f[$marker];
take @available[$n];
@available.splice($n, 1);
}
}.join('')
Perl 6 示例