vijesh has asked for the wisdom of the Perl Monks concerning the following question:
Hello Experts. I am trying to get an program to reach a number with minimum number of iteration. what I wrote is given below. Is there a better way? <\p>
eg: I want to reach 1000 starting from 30. script output ------------- start with 30 Find 1000 ASCENT 130 230 330 430 530 630 730 830 930 1030 DESCENT 1442 1186 1058 994 1026 1010 1002 998 1000 GOT IT...$newScale == $dest --> 1000 == 1000 Total Iteration taken is 21
my $dest = 1000; my $start = 30; my $steps = 100; my $newScale = $start; my $ascent = 1; my $descent = 0; my $n = 9; # n is power of 2 to reach $steps my $i=1; print "start with $start\n"; print "Find $dest\n"; print "\n\nASCENT\n"; while ($ascent) { if ($newScale < $dest) { $i++; $newScale = $newScale + $steps; print "$newScale\n"; } else { $ascent = 0; $descent = 1; $newScale = $newScale - $steps; $i++; } } print "\n\nDESCENT\n"; while ($descent) { if ( $n < 0 ) { last; } if ($newScale > $dest) { $newScale = $newScale - 2**$n; print "$newScale\n"; $i++; } else { $newScale = $newScale + 2**$n; $i++; print "$newScale\n"; } if ($newScale == $dest) { print "\n\nGOT IT...\$newScale == \$dest --> $newScale == $des +t \nTotal Iteration taken is $i \n"; last; } $n--; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: search algo to reach a number
by Laurent_R (Canon) on Sep 27, 2013 at 17:39 UTC | |
|
Re: search algo to reach a number
by davido (Cardinal) on Sep 27, 2013 at 15:18 UTC | |
by vijesh (Novice) on Sep 27, 2013 at 15:34 UTC | |
by davido (Cardinal) on Sep 27, 2013 at 17:50 UTC |