in reply to Re: Nested loops and if
in thread Nested loops and if

I'm sorry to trouble again, but I am wondering how I record the $y with the lowest $new for each $x and place this in a file ready for a CRT calculation, given by the "push" command in the program below. For the CRT calculation I only need one $y for each $x, otherwise the CRT calculation will not work. For example, running this code produces 0,11 as well as 5,11 in @results and it is only the last value at for each prime that I need to keep (i.e. 5,11

#!/usr/bin/env perl use warnings; foreach my $x (@primes){ my @best = @start; my $count = scalar @best; use strict; my @primes = (2,3,5,7,11,13,17) ; my @start = (0..209); my @results =(); print "\nprime $x $count\n"; foreach my $y (0..$x-1){ my @new = grep { ($_+$y) % $x } @best; my $new = scalar @new; print " ${y}mod${x} = $new\n"; if ($new < @start){ @start = @new; push ( @results, ("[","$y",",","$x","],")); } } } foreach (@start) { print "$_\n"; } print "@results\n";

Replies are listed 'Best First'.
Re^3: Nested loops and if
by poj (Abbot) on Feb 21, 2016 at 19:03 UTC

    Move the push down outside the y loop, use another variable like y0 to hold the minimum value

    #!/usr/bin/env perl use strict; use warnings; my @primes = (2,3,5,7,11,13,17) ; my @start = (0..209); my @results =(); foreach my $x (@primes){ my $y0=0; my @best = @start; my $count = scalar @best; print "\nprime $x $count\n"; foreach my $y (0..$x-1){ my @new = grep { ($_+$y) % $x } @best; my $new = scalar @new; print " ${y}mod${x} = $new\n"; if ($new < @start){ @start = @new; $y0 = $y; } } push @results, "[$y0,$x]"; } print "$_\n" for @start; print join(',',@results),"\n";
    poj

      Again, poj, thank you for your guidance!