in reply to chapters,sentences, and arrays

If you are going to be looking for multiple sentences it might pay off to construct a lookup hash mapping sentences to chapters.

use strict; use warnings; my @chapters = ( 15, 24, 23, 110, 30, 58, 3, 22, 79, 6 ); my $base = 1; my %sentenceToChapter = map { my $chapter = $_; my @range = ( $base .. $base + $chapters[ $chapter ] - 1 +); $base += scalar @range; map { $_ => $chapter + 1 } @range; } 0 .. $#chapters; print qq{Sentence $_ is in chapter $sentenceToChapter{ $_ }\n} for qw{ 250 15 16 98 };

The output.

Sentence 250 is in chapter 6 Sentence 15 is in chapter 1 Sentence 16 is in chapter 2 Sentence 98 is in chapter 4

I hope this is useful.

Cheers,

JohnGG

Replies are listed 'Best First'.
A lookup array would be simpler: Re^2: chapters,sentences, and arrays
by Narveson (Chaplain) on Oct 21, 2008 at 17:30 UTC
    construct a lookup hash mapping sentences to chapters

    The keys of this hash turn out to be the consecutive numbers from one up to the total number of sentences. The lookup could just as well be an array.

    my @chapters = ( 15, 24, 23, 110, 30, 58, 3, 22, 79, 6 ); my $chapter = 1; my @sentenceToChapter = ( undef, # start counting at 1 map { ($chapter++) x $_ } @chapters, ); print qq{Sentence $_ is in chapter $sentenceToChapter[ $_ ]\n} for qw{ 250 15 16 98 };