This wasn't as straight forward as I had guessed. I asked around in the CB if there was something I was missing which apparently I wasn't. diotalevi indicated that this was one of the first problems he tried solving in Perl. Traditional compression techniques fail because with short strings they end up being bigger than the original. When you can afford the runtime cost but not the disk space (apparently every MB had to be justified during the campaign he was working), 7bit strings start to look appealing.
I mentioned on Monday (today) that I would try to provide a more straight forward solution as well as multiple implementations. One for runtime speed (assuming RAM isn't a factor), one for RAM, and one that balances both.
I didn't do very well. I was hoping others would find the task fun and provide better solutions. Here is my solution optimized for memory.
sub shrink { my $str = ''; for ( 0 .. length( $_[0] ) - 1 ) { my $bit = 7 * $_; vec($str, $bit++, 1) = $_ for split //, unpack('b8', substr($_ +[0], $_, 1)); } return $str; } sub grow { my ($str, $chr) = ('', ''); my $end = length( $_[0] ) * 8; $end -= ($end % 7) + 1; for ( 0 .. $end ) { vec($chr, $_ % 7, 1) = vec($_[0], $_, 1); if ( $_ % 7 == 6 ) { vec($chr, 7, 1) = 0; $str .= $chr; $chr = ''; } } return $str; }
Cheers - L~R
In reply to Efficient 7bit compression by Limbic~Region
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |