in reply to Padding search results with context

In the interest of using only one iteration to produce the desired results, I rewrote my solution as follows. Note the use of two hashes: one to check for highlighted-ness, and one to check for already-printed-ness.

#!/usr/bin/perl use strict; my ($min,$max) = (0,21); my @nums = (1, 5, 6, 8, 15, 20); my $pad = 1; my (%printed,%nums); map { $nums{$_}++ } @nums; for my $i (@nums) { for my $n ($i-$pad .. $i+$pad) { if ( ! $printed{$n} && $min <= $n && $n <= $max ) { print exists $nums{$n} ? "Highlighted: " : ""; print $n, "\n"; $printed{$n}++; } } }

Prints the same as before, but unfortunately it has to iterate once to build %nums and again to do the rest. I've tried several ways, but couldn't get shorter than two iterations. It is, however, of O(N) instead of O(N^2). I also believe this solution is easier to follow than my last one.

Replies are listed 'Best First'.
Re^2: Padding search results with context
by moritz (Cardinal) on Aug 14, 2007 at 07:03 UTC
    In fact your previous solution was O(N log N) for N = $pad*@nums because of the sort, not O(Nē) (or did I miss something)?

    However your current solution stores some amount of data twice in a hash where pointer is sufficient because @nums is already sorted.