http://www.perlmonks.org?node_id=1002584


in reply to min and mindex

The first problem here is that you haven't asked a question! Perhaps ...

Please read the guidelines in: How do I post a question effectively?

The code you've provided outputs:

1 Statistics::Descriptive::Sparse=HASH(0x7fa3510457f0)

Presumably you want:

1 0

Checking the documentation for Statistics::Descriptive, you can achieve this by changing

my $min_index = Statistics::Descriptive::Sparse->new(); $min_index -> mindex(@array1);

to

my $stat = Statistics::Descriptive::Sparse->new(); $stat->add_data(@array1); my $min_index = $stat->mindex();

See also ++Khen1950fx's response (above) which has similar code changes.

I see a number of alternative ways of doing this (without using Statistics::Descriptive) have already been provided. Here's another one that doesn't use any modules at all and handles non-unique values and arrays of uneven lengths.

#!/usr/bin/env perl use strict; use warnings; my @data = ( [ [ 1 .. 7 ], [ qw{a b c d e f g} ] ], [ [ 1 .. 7, 0 ], [ qw{a b c d e f g} ] ], [ [ 1 .. 7, 0 ], [ qw{a b c d e f g h} ] ], [ [ 1 .. 7, -1, 0 ], [ qw{a b c d e f g h} ] ], [ [ 1 .. 7, 1 .. 7 ], [ qw{a b c d e f g} ] ], ); for (@data) { my @array1 = @{$_->[0]}; my @array2 = @{$_->[1]}; my $pos = -1; my $min_pos = ( sort { $a->[0] <=> $b->[0] } map { [$_ => ++$pos] } @array1 )[0]; print "Array1: @array1\n"; print "Min value: $min_pos->[0]\n"; print "Min index: $min_pos->[1]\n"; print "Array2: @array2\n"; if ($min_pos->[1] > $#array2) { print "Min index outside \@array2 bounds!\n"; } else { print 'Min index position in @array2 has value: ', "$array2[$min_pos->[1]]\n"; } print '-' x 60, "\n"; }

Output:

$ pm_min_mindex.pl Array1: 1 2 3 4 5 6 7 Min value: 1 Min index: 0 Array2: a b c d e f g Min index position in @array2 has value: a ------------------------------------------------------------ Array1: 1 2 3 4 5 6 7 0 Min value: 0 Min index: 7 Array2: a b c d e f g Min index outside @array2 bounds! ------------------------------------------------------------ Array1: 1 2 3 4 5 6 7 0 Min value: 0 Min index: 7 Array2: a b c d e f g h Min index position in @array2 has value: h ------------------------------------------------------------ Array1: 1 2 3 4 5 6 7 -1 0 Min value: -1 Min index: 7 Array2: a b c d e f g h Min index position in @array2 has value: h ------------------------------------------------------------ Array1: 1 2 3 4 5 6 7 1 2 3 4 5 6 7 Min value: 1 Min index: 0 Array2: a b c d e f g Min index position in @array2 has value: a ------------------------------------------------------------

You may find Benchmark useful for comparing the alternative solutions supplied.

-- Ken