On Mon, 13 Mar 2006, Bryan Sant wrote:

On 3/10/06, Jason Holt <[EMAIL PROTECTED]> 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

/*
PLUG: http://plug.org, #utah on irc.freenode.net
Unsubscribe: http://plug.org/mailman/options/plug
Don't fear the penguin.
*/

Reply via email to