本帖最后由 523066680 于 2017-06-25 23:20 编辑
- =info
- Code by 523066680
- 2017-06
- 排列元素的方案参考自 http://stackoverflow.com/questions/9122315/permutations-using-perl
- =cut
- use List::Util qw/sum/;
- our @a = (1..9);
- #分组,校验的下标顺序
- our @chk =
- (
- [1,2,3], [4,5,6], [7,8,9],
- [1,4,7], [2,5,8], [3,6,9],
- [1,5,9], [3,5,7],
- );
- #纯属冗余操作(为了前面直观)。统一 -1
- grep { $_ = [map { $_-1 } @$_] } @chk; #全体 -1
- #开始迭代
- for ( &permute( @a ) )
- {
- if (check($_) == 1)
- {
- print join(",", @{$_}[0,1,2]),"\n";
- print join(",", @{$_}[3,4,5]),"\n";
- print join(",", @{$_}[6,7,8]),"\n\n";
- }
- }
- sub permute
- {
- return ([]) unless (@_);
- return map
- {
- my @cdr = @_;
- my $car = splice @cdr, $_, 1;
- map { [$car, @$_] } &permute(@cdr);
- } 0 .. $#_;
- }
- sub check
- {
- my $a_ref = shift;
- my $result = 1;
- for my $ref (@chk)
- {
- if ( sum( map { $a_ref->[$_] } @$ref ) != 15 )
- {
- $result = 0;
- last;
- }
- }
- return $result;
- }
复制代码
2,7,6
9,5,1
4,3,8
2,9,4
7,5,3
6,1,8
4,3,8
9,5,1
2,7,6
4,9,2
3,5,7
8,1,6
6,1,8
7,5,3
2,9,4
6,7,2
1,5,9
8,3,4
8,1,6
3,5,7
4,9,2
8,3,4
1,5,9
6,7,2
[Finished in 7.2s]
优化肯定是有的优化的,只是想看看暴力跑法。(我的strawberry perl 安装 Algorithm:ermute 失败了,所以先借用一下别人写好的排列方案) |