Here is a simple OO solution with fixed non-overlapping data. It keeps an array of triplets
beginning, end, value. It sorts this array at the end to make the retrieval possible. You might need to implement a faster searching algorithm (e.g. binary search) if your data are large and time is critical.
#!/usr/bin/perl
use warnings;
use strict;
use feature qw(say);
{ package Triplets;
sub new {
return bless [], shift;
}
sub add {
my $self = shift;
push @$self, \@_;
}
sub sort {
my $self = shift;
@$self = sort { $a->[0] <=> $b->[0] } @$self;
}
sub retrieve {
my $self = shift;
my $value = shift;
my $idx = 0;
$idx++ while $idx <= $#$self and $self->[$idx][0] <= $value;
return $self->[$idx-1][-1] if $idx and $self->[$idx-1][1] >= $
+value;
return;
}
}
my $triplets = 'Triplets'->new;
while (<DATA>) {
my ($int, $value) = split;
my ($from, $to) = split /-/, $int, 3;
$triplets->add($from, $to, $value);
}
$triplets->sort;
say "$_: ", $triplets->retrieve($_) // 'Undefined' for 1 .. 135;
__DATA__
23-45 12
11-17 2
46-134 23 fixed here!!!
10-10 65
1-1 45
19-20 10
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.