This has been a recurring dilemma down the years.
Given a contiguous input and a set of break points, find the highest breakpoint lower than the input value and return the associated value.
sub lookup { my( $v ) = shift; if( $v < 25000 ) return 2500; if( $v < 50000 ) return 5000; if( $v < 150000 ) return 12500; if( $v < 225000 ) return 25000; if( $v < 300000 ) return 37500; if( $v < 600000 ) return 60000; if( $v < 1200000 ) return 120000; if( $v < 3600000 ) return 300000; if( $v < 5400000 ) return 600000; if( $v < 10800000 ) return 900000; if( $v < 21600000 ) return 1800000; if( $v < 43200000 ) return 3600000; if( $v < 64800000 ) return 7200000; if( $v < 129600000 ) return 10800000; if( $v < 216000000 ) return 21600000; if( $v < 432000000 ) return 43200000; if( $v < 864000000 ) return 86400000; if( $v < 1728000000 ) return 172800000; if( $v < 3024000000 ) return 345600000; if( $v < 6048000000 ) return 604800000; if( $v < 12096000000 ) return 1209600000; if( $v < 31557600000 ) return 2629800000; if( $v < 63115200000 ) return 5259600000; if( $v < 78894000000 ) return 7889400000; if( $v < 157788000000 ) return 15778800000; return 31557600000; }
Simple. Efficient. Not very pretty. Is there a better way?
but that requires either sorting the keys each time or keeping a sorted array of the keys and duplicating memory.
but ... parallel arrays?
But looping over the double indirection isn't particularly efficient.
Then there's the search method. Most time the set isn't big enough to warrant coding a binary search in place of a linear one. Most times efficiency isn't a particular concern, but in this case, the routine is called as part of a redraw function when rotating stuff on screen, so it can be called many times a second.
Basically, there are several ways of doing it, but none of them are particularly satisfying, and I'm wondering if anyone has discovered a nice way that I haven't covered?
(The final twist is that this is destined for JavaScript; so if any JS guys know of a good method that language supports; I'd be happy to hear of it. Perhaps off-line.)
In reply to A better way of lookup? by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |