in reply to Checking the Ascendency/Descendency of Numeric Array of Any Size

monkfan:

Here's a snippet of code that will check the monotonicity of a series and return the direction, too. If you only want 0/1, you can simply wrap the final return value with abs(...).

#!/usr/bin/perl -w use strict; use warnings; sub check_monotonicity { # Return 0 if series is non-monotonic, +1 if it's # an increasing series, -1 if it decreases. my $dir = shift; $dir = shift if ! $dir; return 0 if ! $dir; my $next = shift; return 0 if ! ($next - $dir); my $sign = ($next - $dir) / abs($next - $dir); $dir = $next; while ($next = shift) { return 0 unless ($next - $dir) * $sign > 0; $dir = $next; } return $sign; } my @a = (0, 0, 0); print check_monotonicity(@a), ": ", join(', ',@a), "\n"; @a = (0, 2, 4, 6, 8); print check_monotonicity(@a),": ", join(', ',@a), "\n"; @a = (1, 3, 5, 7, 9, 11); print check_monotonicity(@a),": ", join(', ',@a), "\n"; @a = (10, 9, 8, 7, 6, 5); print check_monotonicity(@a),": ", join(', ',@a), "\n"; @a = (5, 3, 1, -1, -3, -5); print check_monotonicity(@a), ": ", join(', ',@a), "\n"; @a = (1, 2, 3, 3, 4); print check_monotonicity(@a), ": ", join(', ',@a), "\n";
This code produces:
root@swill ~/PerlMonks $ ./AscDesc.pl 0: 0, 0, 0 1: 0, 2, 4, 6, 8 1: 1, 3, 5, 7, 9, 11 -1: 10, 9, 8, 7, 6, 5 -1: 5, 3, 1, -1, -3, -5 0: 1, 2, 3, 3, 4 root@swill ~/PerlMonks $
--roboticus