in reply to Padding search results with context
#!/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 |