Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Checking the Ascendency/Descendency of Numeric Array of Any Size

by roboticus (Chancellor)
on Mar 23, 2007 at 12:10 UTC ( [id://606214]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://606214]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2024-04-25 19:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found