题目如下:
排列是一个物体的有序安排。例如3124是1,2,3,4的一种排列。如果所有的排列按照数值或者字母序排序,我们称其为一个字典序。0,1,2的字典排列有:
012 021 102 120 201 210
0, 1, 2, 3, 4, 5, 6, 7, 8,9的第100万个字典排列是什么?
首先声明,我是用笔算出来的。用了一页纸,还算好了。
然后到那个外国的论坛里看有没有用perl写的程序,还好,有个高手在第一页就有一个了,也就认识了有这么一个模块,Algorithm::FastPermute。下载安装一下就OK了。
我先 把代码贴下来:
use strict; use warnings; use Algorithm::FastPermute qw/permute/; my $star_time=time; my @digital = qw/0 1 2 3 4 5 6 7 8 9/; my @all; permute{push(@all,join('',@digital))}@digital; print ((sort@all)[999999]."\n"); my $long=time-$star_time; print "$long\n";
C:\WINDOWS\system32\cmd.exe /c perl "C:\Documents and Settings\Administrator 面\a.pl" 2783915460 9 Hit any key to close this window...
效率还是可以的。
然后我们再来仔细的看一下这个模块的用法:(官方网址如下)
http://search.cpan.org/~robin/Algorithm-FastPermute-0.999/FastPermute.pm
里面附带了一个程序,我们简单的修改,然后运行:
use Algorithm::FastPermute ('permute'); my @array = (1..3); permute { print "@array\n"; } @array;
C:\WINDOWS\system32\cmd.exe /c perl "C:\Documents and Settings\Administrator\桌 面\b.pl" 1 2 3 1 3 2 3 1 2 2 1 3 2 3 1 3 2 1 Hit any key to close this window...
use Algorithm::FastPermute ('permute'); my @array = (1..3); permute { push(@all,join'',@array); } @array; print "$all[0]";
C:\WINDOWS\system32\cmd.exe /c perl "C:\Documents and Settings\Administr 面\b.pl" 123 Hit any key to close this window...
程序如下:
use Algorithm::FastPermute ('permute'); my @array = (1..3); permute { push(@all,join'',@array); } @array; @sort_all= sort @all; foreach$all(@all) { print "$all\n"; }
C:\WINDOWS\system32\cmd.exe /c perl "C:\Documents and Settings\Administrator\桌 面\b.pl" 123 132 312 213 231 321 Hit any key to close this window...