Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Numbers to Words

by the_slycer (Chaplain)
on May 22, 2001 at 21:31 UTC ( [id://82313]=CUFP: print w/replies, xml ) Need Help??

Like from a phone number..

Just for fun (and well, my wife asked me for it).
Easily converted to CGI
#!/usr/bin/perl -w #Numbers to letters v2 use strict; my $count = 0; my $wlist = "/usr/dict/words"; open (WLIST, "<$wlist") || die "Unable to open $wlist: $!"; my @words = <WLIST>; my %nums =( #numbers to letters 1 => ["L"], 2 => ["A","B","C"], 3 => ["D","E","F"], 4 => ["G","H","I"], 5 => ["J","K","L"], 6 => ["M","N","O"], 7 => ["P","Q","R","S"], 8 => ["T","U","V"], 9 => ["W","X","Y","Z"], 0 => ["O"], ); print "Please enter the numbers - between 2 and 9\n"; print "Note that 1's will convert to L's and 0's to O's\n: "; chomp (my $key=<STDIN>); my @keys=split "",$key; my $length = scalar @keys; #call the sub, let it know which letter in the word we are looking at, #which letters we are looking for and the wordlist - #this keeps going until there are no more numbers to check #this is seperate to give it the "first" list (faster this way) my $words = &get_wrds($count,$nums{shift @keys},\@words,$length); ++$count; foreach (@keys){ $words=&get_wrds($count,$nums{$_},$words); ++$count; } foreach (@{$words}){ #there should only be a couple of N letter words left.. print "Found $_\n"; } sub get_wrds{ my $pos = shift; #position in the word my $list = shift; #list of letters my $wlist = shift; #list of words my $lng = shift; #length my @words; #temp storage foreach my $let(@{$list}){ foreach (@{$wlist}){ chomp; if ($lng){ #get rid of irrelevant words next unless length $_ == $lng; } if ( index(uc $_,$let,$pos) == $pos){ push @words,$_; } } } return \@words; #return matches }
FWIW this is a revisit of a very early script of mine. That one was plain ugly - due to indentation the foreach loops were marching right off the page :-) - plus it only did 4 numbers. I was curious when I first finished this as to which of the 2 was faster. Imagine my surprise when I discovered that the ugly bad code that I had written before was much quicker. Hence some of the optimizations (ie: passing references instead of arrays, skipping non N length words etc). This code now runs faster :-).

Replies are listed 'Best First'.
Re: Numbers to Words
by merlyn (Sage) on May 22, 2001 at 21:37 UTC

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (8)
As of 2024-03-28 11:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found