No such thing as a small change 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.

Replies are listed 'Best First'.
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.

Create A New User
Node Status?
node history
Node Type: CUFP [id://991822]
Approved by Corion
Front-paged by Arunbear
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2017-07-26 21:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
I came, I saw, I ...

Results (402 votes). Check out past polls.