There's more than one way to do things PerlMonks

### Re: Determine steps between two numbers

by hbm (Hermit)
 on Sep 05, 2012 at 13:12 UTC ( #991839=note: print w/replies, xml ) Need Help??

in reply to Determine steps between two numbers

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";

Replies are listed 'Best First'.
Re^2: Determine steps between two numbers
by grizzley (Chaplain) on Sep 05, 2012 at 13:32 UTC
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.

Not too confident in the one-line generator you have there, but it'd be a nice touch anyway.
Why? Don't you trust mathematics?

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

My blog: Imperial Deltronics

Create A New User
Node Status?
node history
Node Type: note [id://991839]
help
Chatterbox?
and the voices are still...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (12)
As of 2017-09-20 13:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
During the recent solar eclipse, I:

Results (236 votes). Check out past polls.

Notices?