Quiz

Jason Holt jason at lunkwill.org
Tue Mar 14 02:03:16 MST 2006


On Mon, 13 Mar 2006, Bryan Sant wrote:

> On 3/10/06, Jason Holt <jason at lunkwill.org> wrote:
>> Here's another fun one: print a bar graph (optionally text-only) of letter
>> frequency for any given input text file.  We made that one of the first
>> programming labs in the data security class -- I think the longest of the
>> entries was over 250 lines of Java or C# code.  In class we got one down to,
>> IIRC, 5 (short) lines of perl.
>
> Could you please post that code?

Let's see, how did it go?  Here's the one-liner:

perl -e '$_=join("", <>); map { $h{$_}++ } split(//); print("$_: ", \
   "*" x $h{$_}, "\n") foreach(sort keys %h);'

Or, as a more nicely formatted program:

#!/usr/bin/perl
$_=join("", <>); s/\n//g;
map { $h{$_}++ } split(//);
print("$_: ", "*" x $h{$_}, "\n") foreach(sort keys %h);

I guess it was 4 lines.  If you want relative frequency (or just want to
ensure that the bars don't get too long), you can do this:

#!/usr/bin/perl
$_=join("", <>); s/\n//g;
map { $h{$_}++ } split(//);
$max = (sort { $a <=> $b } (values %h))[-1];
print("$_: ", "*" x (70*$h{$_}/$max), "\n") foreach(sort keys %h);

But I dunno if it's worth it, since it's 25% more lines of code.  No sense in 
keeping around a lot of bloated code.  Think of the disk space.

 						-J



More information about the PLUG mailing list