merrymonk has asked for the wisdom of the Perl Monks concerning the following question:
use strict; my (@fr, $fr_num, %fr_cur, %dis, $row_num, $col_num, $jr, $jc, $random +_fr, $stored); #======================================== # # sub print_out_display # # this prints out to the screen a comma seperated list of the fruits i +n each row # # argument 1 referecne to the hash holding the fruit positions # #========================================= sub print_out_display($) { my ($ref_dis) = @_; my ($jr, $jc); print "\nPositions of fruit\n\n"; print ","; foreach $jc (sort {$a <=> $b} keys %{$ref_dis->{0}}) { print "$jc,"; } print "\n"; foreach $jr (sort {$a <=> $b} keys %$ref_dis) { print "$jr,"; foreach $jc (sort {$a <=> $b} keys %{$ref_dis->{$jr}}) { print "$ref_dis->{$jr}{$jc},"; } print "\n"; } } #======================================== # # sub store_display # # this prints out to the screen a comma seperated list of the hash and + its values # so this could be used repeatedly as standard data # # argument 1 reference to the hash holding the fruit positions # #========================================= sub store_display($) { my ($ref_dis) = @_; my ($jr, $jc); print "\nHash giving the positions of fruit\n"; foreach $jr (sort {$a <=> $b} keys %$ref_dis) { foreach $jc (sort {$a <=> $b} keys %{$ref_dis->{$jr}}) { print "\$dis{$jr}{$jc} = '$ref_dis->{$jr}{$jc}';\n"; } } } # this is the list of fruit there can only be one of each fruit in any + one row # b is a blank - there can be more that one of these in a row $fr[0] = 'Apple'; $fr[1] = 'Hawthorn'; $fr[2] = 'Pear'; $fr[3] = 'Apricot'; $fr[4] = 'Peach'; $fr[5] = 'Nectarines'; $fr[6] = 'Plum'; $fr[7] = 'Cherry'; $fr[8] = 'Currant'; $fr[9] = 'Gooseberry'; $fr[10] = 'Grapefruit'; $fr[11] = 'Kiwi'; $fr[12] = 'Rhubarb'; $fr[13] = 'Pawpaw'; $fr[14] = 'Melon'; $fr[15] = 'Figs'; $fr[16] = 'b'; $fr_num = scalar(@fr); # set the number of columns - this must be less than the number of rea +l fruits + 1 for a blank # with the data above it must be less than 17 $col_num = 10; # set the number of rows $row_num = 8; # load the intial position of the fruit # do this row by row for($jr = 0; $jr < $row_num; $jr ++) { # for each column in the row randomly select a fruit # undef the hash that holds the fruit used in the current row - blnaks + are not stored in this hash as there can be more than one undef %fr_cur; for($jc = 0; $jc < $col_num; $jc ++) { $stored = 'no'; while($stored eq 'no') { $random_fr = $fr[rand @fr]; if($random_fr ne 'b') { if(! exists($fr_cur{$random_fr})) { $dis{$jr}{$jc} = $random_fr; $fr_cur{$random_fr} = 1; $stored = 'yes'; } } else { $dis{$jr}{$jc} = $random_fr; $stored = 'yes'; } } } } print_out_display(\%dis); store_display(\%dis);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: A 2D Sorting problem
by shmem (Chancellor) on Jul 14, 2010 at 12:34 UTC | |
|
Re: A 2D Sorting problem
by jwkrahn (Abbot) on Jul 14, 2010 at 12:24 UTC |