Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Determine steps between two numbers

by thmsdrew (Scribe)
on Sep 05, 2012 at 12:22 UTC ( #991822=CUFP: print w/ replies, xml ) Need Help??

The following program will find the steps between two numbers. Give it two numbers to find steps between, and the number of steps you want it to find, and it'll list them for you.

Example:

$ steps.pl 1 10 5 1, 3.25, 5.5, 7.75, 10 $ steps.pl 10.5 -10.7 4 10.5, 3.43333333333333, -3.63333333333333, -10.7

steps.pl

#!/usr/bin/perl use strict; use warnings; my ($first, $second, $steps) = @ARGV; $steps = int $steps; my $increment = ($second - $first) / ($steps - 1); my @array = ($first); for (2..$steps) { push @array, $first += $increment; } print join(", ", @array) . "\n";

Updated to make a bit more sense. I don't always need to list it in a specific order. It makes more sense for the order to be determined by the input.

Comment on Determine steps between two numbers
Select or Download Code
Re: Determine steps between two numbers
by hbm (Hermit) on Sep 05, 2012 at 13:12 UTC

    Since you always assemble your steps in increasing order, you could do this:

    #!/usr/bin/perl use strict; use warnings; my ($first, $second, $steps) = @ARGV; $steps = int $steps; if ($first > $second) { ($first,$second) = ($second,$first); } my $increment = ($first - $second) / ($steps - 1); my @array = ($first); for (2..$steps) { push @array, $first -= $increment; } print join(", ", @array) . "\n";
      IMHO in such case the variable name should be changed from 'increment' to 'decrement'. Or better - change algorithm to more intuitive:
      my $increment = ($second - $first) / ($steps - 1); ... push @array, $first += $increment;
      And one-line @array generator as alternative:

      my @array = map { $first + $increment * $_ } 0 .. $steps - 1;

        Thanks. I transferred this over from my Java implementation of it and didn't quite get it right, so I did some stuff to make it work. You helped me get it back to what it was originally. Not too confident in the one-line generator you have there, but it'd be a nice touch anyway.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://991822]
Approved by Corion
Front-paged by Arunbear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2014-07-29 01:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (211 votes), past polls