#!/usr/bin/perl # grid of fruits. my @grid = ( [ qw( Grapefruit b Apple Currant Cherry Hawthorn Pawpaw Plum Rhubarb Nectarines ) ], [ qw( Currant Grapefruit Rhubarb Plum Cherry Pear Nectarines Kiwi Hawthorn Pawpaw ) ], [ qw( Apple Cherry Currant Apricot Hawthorn Pear Plum Kiwi Peach b ) ], [ qw( Gooseberry Kiwi Cherry Apple Pawpaw Peach Hawthorn Pear Melon Currant ) ], [ qw( Pear Hawthorn Gooseberry Apricot Plum Melon Cherry Nectarines Apple Grapefruit ) ], [ qw( b Figs Cherry Rhubarb Melon Apple Plum Peach Gooseberry b ) ], [ qw( Hawthorn Rhubarb Figs Plum Melon Pear Nectarines Apricot Cherry Kiwi ) ], [ qw( b Plum Cherry Rhubarb Kiwi Nectarines Currant Pear Gooseberry Pawpaw ) ], ); # remeber each fruits row ocurrence in a hash keyed upon fruit name my %fruitpos; for my $row (0..$#grid) { for my $col (0..$#{$grid[$row]}) { push @{$fruitpos{$grid[$row][$col]}}, $row; } } my @fruits = sort { @{$fruitpos{$b}} <=> @{$fruitpos{$a}} } keys %fruitpos; # let's see how many fruits of each type we have print "$_: ",scalar @{$fruitpos{$_}}, "\n" for @fruits; # move the blanks to the end of the array { my $c; for (0..$#fruits) { $fruits[$_] eq 'b' and $c = $_ and last; } push @fruits, splice @fruits,$c,1; } # ok, let's abstract away the fruits into letters to make the grid look nice. my $c = 'A'; my @letters; for (@fruits) { my $ary = delete $fruitpos{$_}; # substitue 'b' with '_' my $key = $_ eq 'b' ? '_' : $c; $fruitpos{$key} = $ary; push @letters, $key; $c++; # string increment } # put them back into a new grid. # But let's see first what the letter columns would look like; my @out; for my $col (0..$#letters) { my $ary = $fruitpos{$letters[$col]}; $out[$_][$col] = $letters[$col] for @$ary; } # substitute undefined elements in that grid with blanks for my $ary (@out) { $ary->[$_] ||= ' ' for 0..$#$ary } # mark the boundary of the original grid with a vertical bar splice(@$_,@{$grid[0]},0,'|') for @out; # output grid print join(" ",@$_),"\n" for @out; __END__ Cherry: 8 Plum: 7 Hawthorn: 6 Pear: 6 Kiwi: 5 Currant: 5 Nectarines: 5 Apple: 5 Rhubarb: 5 b: 5 Gooseberry: 4 Pawpaw: 4 Melon: 4 Peach: 3 Grapefruit: 3 Apricot: 3 Figs: 2 A B C F G H I | K N _ A B C D E F G I | K N A B C D E F H | M O _ A C D E F H J | K L M A B C D G H J | L N O A B H I J | L M P _ A B C D E G I | L O P A B D E F G I J | K _