Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^3: Simple but thought-provoking programming tasks [OT]

by GrandFather (Saint)
on Apr 16, 2007 at 05:38 UTC ( [id://610265]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Simple but thought-provoking programming tasks [OT]
in thread Simple but thought-provoking programming tasks [OT]

use strict; use warnings; while (<DATA>) { chomp; next unless length; print "$_ is not a number that I can handle\n" unless /^\d+$/; print "$_ = ", toWords("00$_"), "\n"; } sub toWords { my ($leftBit, $groups) = @_; return '' unless $leftBit; $groups ||= 0; my $group = substr $leftBit, -3, 3, ''; return toWords ($leftBit, $groups + 1) unless $group; if ($groups > 4) { print "Argh, I can't deal with numbers that big!\n"; print "The part I can deal with is: "; return ''; } my %digits = ( 0 => '', 1 => 'one ', 2 => 'two ', 3 => 'three ', 4 => 'four ' +, 5 => 'five ', 6 => 'six ', 7 => 'seven ', 8 => 'eight ', 9 => +'nine ' ); my %teens = ( 10 => 'ten ', 11 => 'eleven ', 12 => 'twelve ', 13 => 'thirtee +n ', 14 => 'fourteen ', 15 => 'fifteen ', 16 => 'sixteen ', 17 => 'seventeen ', 18 => 'eighteen ', 19 => 'nineteen ' ); my %tens = ( 2 => 'twenty ', 3 => 'thirty ', 4 => 'fourty ', 5 => 'fifty ', 6 => 'sixty ', 7 => 'seventy ', 8 => 'eighty ', 9 => 'ninety ' ); my $groupStr = ''; # Deal with last two digits my $tensStr = $group % 100; $groupStr = $tens{int ($tensStr / 10)} if $tensStr >= 20; if (int ($tensStr / 10) == 1) { $groupStr .= $teens{int $tensStr}; } else { $groupStr .= $digits{$tensStr % 10} unless $tensStr > 10 and $tensStr % 10 == 0; } my $hundreds = int ($group / 100); if ($hundreds) { my $prefix = "$digits{$hundreds}hundred "; $prefix .= 'and ' if $groupStr; $groupStr = "$prefix$groupStr"; } my $prefix = toWords ($leftBit, $groups + 1); $prefix .= qw(thousand million billion trillion)[$groups] . ' ' if + $prefix; $groupStr = "$prefix$groupStr"; $groupStr = 'zero' unless $groupStr or $groups; return $groupStr; } __DATA__ 0 1 10 11 20 21 99 100 901 98012785623123

Prints:

0 = zero 1 = one 10 = ten 11 = eleven 20 = twenty 21 = twenty one 99 = ninety nine 100 = one hundred 901 = nine hundred and one 98012785623123 = ninety eight trillion twelve billion seven hundred an +d eighty five million six hundred and twenty three thousand one hundr +ed and twenty three

looks recursive to me, but it would be easy to make it iterative instead (left as an exercise for the reader).


DWIM is Perl's answer to Gödel

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://610265]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (7)
As of 2024-04-19 10:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found