Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Perl Number range lookup question

by AnomalousMonk (Canon)
on Jun 18, 2012 at 04:01 UTC ( #976735=note: print w/replies, xml ) Need Help??

in reply to Perl Number range lookup question

jwkrahn's approach is pretty good all on its own, but if you want a hash-based solution (calculations done just once):

>perl -wMstrict -le "my %tiers = map { $_ => int($_ % 50 / 10) } 0 .. 99; ;; for my $n (-1, 0, 11, 22, 33, 44, 55, 66, 77, 88, 99, 100, 101) { print qq{tier $n }, exists $tiers{$n} ? qq{== $tiers{$n}} : 'out of range'; } " tier -1 out of range tier 0 == 0 tier 11 == 1 tier 22 == 2 tier 33 == 3 tier 44 == 4 tier 55 == 0 tier 66 == 1 tier 77 == 2 tier 88 == 3 tier 99 == 4 tier 100 out of range tier 101 out of range

Replies are listed 'Best First'.
Re^2: Perl Number range lookup question
by dsheroh (Prior) on Jun 18, 2012 at 14:21 UTC
    I'd definitely benchmark this vs. calculating the tier on the fly each time (i.e., in this case, run it against print int( ( $x % 50 ) / 10 );). Especially with a simple tier calculation, I would expect the hash lookup to take longer than (re)calculating on demand.

    Using the precalculated hash would also be slower if the number of lookups isn't substantially larger than the number of precalculated values. If fewer lookups would be done, but the calculation is slower than a hash lookup, the better option would be to do no precalculation and instead do your lookups with

    my $tier = $tiers{$n} //= calculate_tier($n);
    which will calculate the tier for a value the first time it's requested, then return the calculated value from the hash on subsequent requests for that value. (Note that you'll need to use ||= instead of //= if your perl is older than 5.10.)

      my $tier = $tiers{$n} //= calculate_tier($n);

      That's a rather elegant memoization technique for functions in general (provided the function parameters can't be references). If your function took two parameters, you could even do:

      my $tier = $tiers{$n, $m} //= calculate_tier($n, $m);

      ... taking advantage of Perl's rarely used multi-dimensional array fakery.

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://976735]
[RonW]: Ji, JK
[RonW]: Hi
[GotToBTru]: Down voting reap considerations.. Only time I will expend a vote on AM

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2017-02-27 23:46 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (393 votes). Check out past polls.