On topic: The Wednesday Challenge
Yitzchak Scott-Thoennes
sthoenna at efn.org
Wed Aug 15 22:47:23 BST 2007
On Wed, August 15, 2007 7:01 am, Andy Armstrong wrote:
> Given a 64 Mbyte file containing random binary data write a perl
> program such that
>
> $ perl myprog.pl < 64m.bin > 64m.sorted.bin
>
>
> outputs a file 64m.sorted.bin with all the bytes sorted in ascending
> order. Marks will be given for speed, brevity and parsimonious use of
> memory.
Everyone so far has failed on that last point. My solution (written before
reading the responses):
#!/usr/bin/perl -w
use strict;
binmode(STDIN);
$/ = \1024;
my %byte;
map ++$byte{$_}, unpack "(Z)*", $_ while <>;
for my $ch (sort keys %byte) {
print($ch x ($byte{$ch} % 1024));
print($ch x 1024) for 1 .. $byte{$ch} / 1024;
}
(Previous version had unpack "C", @byte instead of %byte, and the ugly
next that cost someone else a point. Though maybe the sort costs a point
too.)
More information about the london.pm
mailing list