Textonyms: Difference between revisions

60,333 bytes added ,  3 months ago
m
m (C code modified to use GLib I/O functions to load the dictionary)
m (→‎{{header|Wren}}: Minor tidy)
 
(45 intermediate revisions by 17 users not shown)
Line 30:
#{3} is the number of #{2} which represent more than one word.
 
At your discretion show a couple of examples of your solution displaying TextonysTextonyms.
 
E.G.:
Line 39:
;Extra credit:
Use a word list and keypad mapping other than English.
 
 
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">[Char = String] CH2NUM
L(chars) ‘abc def ghi jkl mno pqrs tuv wxyz’.split(‘ ’)
V num = L.index + 2
L(ch) chars
CH2NUM[ch] = String(num)
 
F mapnum2words(words)
DefaultDict[String, [String]] number2words
V reject = 0
L(word) words
X.try
number2words[word.map(ch -> :CH2NUM[ch]).join(‘’)].append(word)
X.catch KeyError
reject++
R (number2words, reject)
 
V words = File(‘unixdict.txt’).read().rtrim("\n").split("\n")
print(‘Read #. words from 'unixdict.txt'’.format(words.len))
V wordset = Set(words)
V (num2words, reject) = mapnum2words(words)
 
F interactiveconversions()
L(inp) (‘rosetta’, ‘code’, ‘2468’, ‘3579’)
print("\nType a number or a word to get the translation and textonyms: "inp)
I all(inp.map(ch -> ch C ‘23456789’))
I inp C :num2words
print(‘ Number #. has the following textonyms in the dictionary: #.’.format(inp, (:num2words[inp]).join(‘, ’)))
E
print(‘ Number #. has no textonyms in the dictionary.’.format(inp))
E I all(inp.map(ch -> ch C :CH2NUM))
V num = inp.map(ch -> :CH2NUM[ch]).join(‘’)
print(‘ Word #. is#. in the dictionary and is number #. with textonyms: #.’.format(inp, (I inp C :wordset {‘’} E ‘n't’), num, (:num2words[num]).join(‘, ’)))
E
print(‘ I don't understand '#.'’.format(inp))
 
V morethan1word = sum(num2words.keys().filter(w -> :num2words[w].len > 1).map(w -> 1))
V maxwordpernum = max(num2words.values().map(values -> values.len))
print(‘
There are #. words in #. which can be represented by the Textonyms mapping.
They require #. digit combinations to represent them.
#. digit combinations represent Textonyms.’.format(words.len - reject, ‘'unixdict.txt'’, num2words.len, morethan1word))
 
print("\nThe numbers mapping to the most words map to #. words each:".format(maxwordpernum))
V maxwpn = sorted(num2words.filter((key, val) -> val.len == :maxwordpernum))
L(num, wrds) maxwpn
print(‘ #. maps to: #.’.format(num, wrds.join(‘, ’)))
 
interactiveconversions()</syntaxhighlight>
 
{{out}}
<pre>
Read 25104 words from 'unixdict.txt'
 
There are 24978 words in 'unixdict.txt' which can be represented by the Textonyms mapping.
They require 22903 digit combinations to represent them.
1473 digit combinations represent Textonyms.
 
The numbers mapping to the most words map to 9 words each:
269 maps to: amy, any, bmw, bow, box, boy, cow, cox, coy
729 maps to: paw, pax, pay, paz, raw, ray, saw, sax, say
 
Type a number or a word to get the translation and textonyms: rosetta
Word rosetta is in the dictionary and is number 7673882 with textonyms: rosetta
 
Type a number or a word to get the translation and textonyms: code
Word code is in the dictionary and is number 2633 with textonyms: bode, code, coed
 
Type a number or a word to get the translation and textonyms: 2468
Number 2468 has the following textonyms in the dictionary: ainu, chou
 
Type a number or a word to get the translation and textonyms: 3579
Number 3579 has no textonyms in the dictionary.
</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}} Uses the Algol 68G specific "to upper" procedure.
<langsyntaxhighlight lang="algol68"># find textonyms in a list of words #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
Line 179 ⟶ 258:
 
FI
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 191 ⟶ 270:
Encodings with this length are:
3532876362374256472749 encodes electroencephalography
</pre>
 
=={{header|AppleScript}}==
===Vanilla===
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later.
-- https://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Straightforward
use sorter : script "Quicksort"
use scripting additions
 
on textonyms(posixPath, query)
set digits to "23456789"
set keys to {"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
set {mv, LF} to {missing value, linefeed}
-- Check input.
try
set reporting to (query's class is not text)
if (not reporting) then
repeat with chr in query
if (chr is not in digits) then error "Invalid digit input"
end repeat
set digitCount to (count query)
end if
script o
property |words| : (do shell script ("cat " & posixPath))'s paragraphs
property combos : mv
end script
on error errMsg
display alert "Textonyms handler: parameter error" message ¬
errMsg as critical buttons {"Stop"} default button 1
error number -128
end try
ignoring case
-- Lose obvious no-hope words.
set alphabet to join(keys's rest, "")
repeat with i from 1 to (count o's |words|)
set wrd to o's |words|'s item i
if ((reporting) or (wrd's length = digitCount)) then
repeat with chr in wrd
if (chr is not in alphabet) then
set o's |words|'s item i to mv
exit repeat
end if
end repeat
else
set o's |words|'s item i to mv
end if
end repeat
set o's |words| to o's |words|'s every text
set wordCount to (count o's |words|)
-- Derive digit combinations from the rest.
set txt to join(o's |words|, LF)
repeat with d in digits
set d to d's contents
repeat with letter in keys's item d
set txt to replaceText(txt, letter's contents, d)
end repeat
end repeat
set o's combos to txt's paragraphs
end ignoring
-- Return the appropriate result
considering case -- Case insensitivity not needed with digits.
if (reporting) then
tell sorter to sort(o's combos, 1, wordCount)
set {previousCombo, comboCount, textonymCount, counting} to ¬
{"", wordCount, 0, true}
repeat with i from 1 to wordCount
set thisCombo to o's combos's item i
if (thisCombo = previousCombo) then
set comboCount to comboCount - 1
if (counting) then
set textonymCount to textonymCount + 1
set counting to false
end if
else
set previousCombo to thisCombo
set counting to true
end if
end repeat
set output to (wordCount as text) & " words in '" & ¬
(do shell script ("basename " & posixPath)) & ¬
"' can be represented by the digit key mapping." & ¬
(LF & comboCount & " digit combinations are required to represent them.") & ¬
(LF & textonymCount & " of the digit combinations represent Textonyms.")
else
set output to {}
repeat with i from 1 to wordCount
if (o's combos's item i = query) then set output's end to o's |words|'s item i
end repeat
if ((count output) = 1) then set output to {}
end if
end considering
return output
end textonyms
 
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
 
on replaceText(mainText, searchText, replacementText)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to searchText
set textItems to mainText's text items
set AppleScript's text item delimiters to replacementText
set mainText to textItems as text
set AppleScript's text item delimiters to astid
return mainText
end replaceText
 
on task()
set posixPath to "~/Desktop/www.rosettacode.org/unixdict.txt"
set report to textonyms(posixPath, missing value)
set output to {report, "", "Examples:"}
repeat with digitCombo in {"729", "723353", "25287876746242"}
set foundWords to textonyms(posixPath, digitCombo's contents)
set output's end to digitCombo & " --> {" & join(foundWords, ", ") & "}"
end repeat
return join(output, linefeed)
end task
 
task()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"24978 words in 'unixdict.txt' can be represented by the digit key mapping.
22903 digit combinations are required to represent them.
1473 of the digit combinations represent Textonyms.
 
Examples:
729 --> {paw, pax, pay, paz, raw, ray, saw, sax, say}
723353 --> {paddle, raffle, saddle}
25287876746242 --> {claustrophobia, claustrophobic}"</syntaxhighlight>
 
===AppleScriptObjC===
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
 
on textonyms(posixPath, query)
set digits to "23456789"
set keys to {"", "[abc]", "[def]", "[ghi]", "[jkl]", "[mno]", "[pqrs]", "[tuv]", "[wxyz]"}
set {mv, LF} to {missing value, linefeed}
-- Check input.
try
set reporting to (query's class is not text)
if (not reporting) then
repeat with chr in query
if (chr is not in digits) then error "Invalid digit input"
end repeat
set digitCount to (count query)
end if
set || to current application
set pathStr to (||'s NSString's stringWithString:(posixPath))'s ¬
stringByExpandingTildeInPath()
set {txt, err} to ||'s NSMutableString's stringWithContentsOfFile:(pathStr) ¬
usedEncoding:(mv) |error|:(reference)
if (err ≠ mv) then error (err's localizedDescription() as text)
on error errMsg
display alert "Textonyms handler: parameter error" message ¬
errMsg as critical buttons {"Stop"} default button 1
error number -128
end try
-- Lose obvious no-hope words.
set regex to ||'s NSRegularExpressionSearch
txt's replaceOccurrencesOfString:("\\R") withString:(LF) ¬
options:(regex) range:({0, txt's |length|()})
set |words| to txt's componentsSeparatedByString:(LF)
if ((reporting) or (digitCount > 9)) then
set predFormat to "(self MATCHES '(?i)[a-z]++')"
else
set predFormat to "(self MATCHES '(?i)[a-z]{" & digitCount & "}+')"
end if
set predicate to ||'s NSPredicate's predicateWithFormat:(predFormat)
set |words| to |words|'s filteredArrayUsingPredicate:(predicate)
set wordCount to |words|'s |count|()
-- Derive digit combinations from the rest.
set txt to (|words|'s componentsJoinedByString:(LF))'s mutableCopy()
set range to {0, txt's |length|()}
repeat with d in digits
(txt's replaceOccurrencesOfString:("(?i)" & keys's item d) withString:(d) ¬
options:(regex) range:(range))
end repeat
set combos to txt's componentsSeparatedByString:(LF)
-- Return the appropriate result.
if (reporting) then
set comboSet to ||'s NSSet's setWithArray:(combos)
set comboCount to comboSet's |count|()
set textonymSet to ||'s NSCountedSet's alloc()'s initWithArray:(combos)
textonymSet's minusSet:(comboSet)
set textonymCount to textonymSet's |count|()
set output to (wordCount as text) & " words in '" & ¬
(pathStr's lastPathComponent()) & ¬
"' can be represented by the digit key mapping." & ¬
(LF & comboCount & " digit combinations are required to represent them.") & ¬
(LF & textonymCount & " of the digit combinations represent Textonyms.")
else
set output to {}
set range to {0, wordCount}
set i to combos's indexOfObject:(query) inRange:(range)
repeat until (i > wordCount)
set output's end to (|words|'s objectAtIndex:(i)) as text
set range to {i + 1, wordCount - (i + 1)}
set i to combos's indexOfObject:(query) inRange:(range)
end repeat
if ((count output) = 1) then set output to {}
end if
return output
end textonyms
 
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
 
on task()
set posixPath to "~/Desktop/www.rosettacode.org/unixdict.txt"
set report to textonyms(posixPath, missing value)
set output to {report, "", "Examples:"}
repeat with digitCombo in {"729", "723353", "25287876746242"}
set foundWords to textonyms(posixPath, digitCombo's contents)
set output's end to digitCombo & " --> {" & join(foundWords, ", ") & "}"
end repeat
return join(output, linefeed)
end task
 
task()</syntaxhighlight>
 
{{output}}
Same as for the "vanilla" solution.
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">words: read.lines relative "unixdict.txt" | select => [match? & {/^[a-z]+$/}]
 
nums: "22233344455566677778889999"
 
phone: $ => [
join map &'c -> nums\[sub to :integer c 97]
]
 
textonyms: #[]
tcount: 0
 
loop words 'w [
p: phone w
if? key? textonyms p [
textonyms\[p]: textonyms\[p] ++ w
if 2 = size textonyms\[p] -> 'tcount + 1
]
else -> textonyms\[p]: @[w]
]
 
print ~{
There are |size words| words in unixdict.txt which can be represented by the digit key mapping.
They require |size keys textonyms| digit combinations to represent them.
|tcount| digit combinations represent Textonyms.
 
7325 -> |textonyms\["7325"]|
}</syntaxhighlight>
 
{{out}}
 
<pre>There are 24978 words in unixdict.txt which can be represented by the digit key mapping.
They require 22903 digit combinations to represent them.
1473 digit combinations represent Textonyms.
 
7325 -> [peak peal peck real reck seal]</pre>
 
=={{header|AWK}}==
{{works with|gawk|5.1.0 }}
<syntaxhighlight lang="awk">
#!/usr/bin/env -S gawk -E
 
BEGIN { # user's configuration area
 
KEYMAP="2 abc 3 def 4 ghi 5 jkl 6 mno 7 pqrs 8 tuv 9 wxyz"
FNAME="/usr/share/dict/american-english" # 0.5 MB; 102775 words;
 
#KEYMAP="2 αβγά 3 δεζέ 4 ηθιήίϊΐ 5 κλμ 6 νξοό 7 πρσς 8 τυφύϋΰ 9 χψωώ"
#FNAME="/usr/share/dict/greek" # 19.5MB; 828808 words;
 
# where generated data will be written,
# or comment out a line if you don’t need it.
EXPORT_TXN="/tmp/textonyms"
EXPORT_ALL="/tmp/phonewords"
EXPORT_BAD="/tmp/invalidwords" #also the line ‘BUFF_ERRW = BUFF_...’
}
BEGIN { # main
delete ARGV; ARGC=1 # do not accept command line arguments
delete XEK # reserve id for use only as a hash table
delete TXN # reserve id ...
AZ="" # generated Alphabet
EE=0 # invalid word Counter
KK=0 # valid word Counter
TT=0 # textonym groups in the table TXN
BUFF_ERRW="" # invalid word buffer
TOTAL=1 # enum
COUNT=2 # enum
 
STDERR="/dev/stderr"
OLD_RS=RS
OLD_FS=FS
processFile()
generateReport()
userQuery()
}
function processFile( ii,jj,nn,errW,ss,aKey,aGroup,qqq){
$0=KEYMAP
AZ=" "
for (ii=1; ii<=NF; ii=ii+2) {
aKey=$ii; aGroup=$(ii+1)
nn=split(aGroup, qqq, //)
for (jj=1; jj<=nn; jj++) {ss=qqq[jj]; XEK[ss]=aKey; AZ = AZ ss " " }
}
AZ = AZ " "
######################
RS="^$" #
FS="[\n\t ]+" #
######################
if ((getline <FNAME) <= 0) {
printf "unexpected EOF or error: ‘%s’ %s\n",FNAME,ERRNO >STDERR
exit 1
} else printf "total words in the file ‘%s’: %s\n", FNAME,NF
for (ii=1; ii<=NF; ii++) {
errW=0
ss=tolower($ii)
nn=split(ss, qqq, //)
nmb=""
for (jj=1; jj<=nn; jj++) {
lchr=qqq[jj]
if (index(AZ," "lchr" ")>0) { nmb = nmb XEK[lchr] }
else {
EE++
errW=1
BUFF_ERRW = BUFF_ERRW $ii "\n"
break
}
}
if (errW) { continue }
T9=TXN[nmb][TOTAL]
if (index(T9" "," "ss" ")==0) {
TXN[nmb][TOTAL] = T9 " " ss
TXN[nmb][COUNT]++
}
KK++
}
}
function generateReport( elm){
for (elm in TXN) { if (TXN[elm][COUNT]>1) { TT++ } }
printf "valid words: %9s\n", KK
printf "invalid words: %9s\n", EE
printf "table indices for valid words: %9s\n", length(TXN)
printf "textonym groups in the table: %9s\n", TT
exportData()
close(EXPORT_BAD); close(EXPORT_TXN); close(EXPORT_ALL)
}
function exportData( elm){
if (EXPORT_BAD != "") print BUFF_ERRW >EXPORT_BAD
 
if (EXPORT_TXN != "" && EXPORT_ALL != "") {
printf "%s\n",
"number-of-textonyms\tword's-length\tkeys\tlist-of-textonyms" >EXPORT_ALL
printf "%s\n",
"number-of-textonyms\tword's-length\tkeys\tlist-of-textonyms" >EXPORT_TXN
for (elm in TXN) {
printf "%s\t%s\t%s\t%s\n",
TXN[elm][COUNT], length(elm), elm, TXN[elm][TOTAL] >EXPORT_ALL
if (TXN[elm][COUNT]>1) {
printf "%s\t%s\t%s\t%s\n",
TXN[elm][COUNT], length(elm), elm, TXN[elm][TOTAL] >EXPORT_TXN
}
}
return ## return ## return ## return ##
} else if (EXPORT_ALL != "") {
printf "%s\n",
"number-of-textonyms\tword's-length\tkeys\tlist-of-textonyms" >EXPORT_ALL
for (elm in TXN) {
printf "%s\t%s\t%s\t%s\n",
TXN[elm][COUNT], length(elm), elm, TXN[elm][TOTAL] >EXPORT_ALL
}
}
else if (EXPORT_TXN != "") {
printf "%s\n",
"number-of-textonyms\tword's-length\tkeys\tlist-of-textonyms" >EXPORT_TXN
for (elm in TXN) {
if (TXN[elm][COUNT]>1) {
printf "%s\t%s\t%s\t%s\n",
TXN[elm][COUNT], length(elm), elm, TXN[elm][TOTAL] >EXPORT_TXN
}
}
}
}
function userQuery( userasks,ss,ss1,nn,key,words){
printf "txn>> "
RS=OLD_RS
FS=OLD_FS
while ((getline ) > 0) {
userasks=$1
if (NF==0){ printf "txn>> ", ""; continue }
else if (userasks ~ /^-e|--ex|--exit$/) { exit }
else if (userasks ~ /^[0-9]+$/) {
nn=TXN[userasks][COUNT]+0
words=TXN[userasks][TOTAL]
if (nn == 0) { printf "%s -> %s\n", userasks,"no matching words" }
else { printf "%s -> (%s) %s\n", userasks,nn,words }
}
else {
ss=tolower(userasks)
if ((key=keySeq_orElse_zero(ss))>0) {
ss1=(index((TXN[key][TOTAL]" ") , " "ss" ")>0) ?
", and the word is in" : ", but the word is not in"
printf "%s -> %s; the key is%s in the table%s\n", ss,key,
((key in TXN) ?"":" not"),ss1
}
else {
printf "%s -> not a valid word for the alphabet:\n%s\n", userasks,AZ
}
}
printf "txn>> "
}
printf "\n"
}
function keySeq_orElse_zero(aWord, qqq,lchr,nn,jj,buf){
nn=split(aWord, qqq, //)
for (jj=1; jj<=nn; jj++) {
lchr=qqq[jj]
if (index(AZ," "lchr" ")>0) { buf = buf XEK[lchr] } else { return 0 }
}
return buf
}
</syntaxhighlight>
 
{{out}}
<pre>
# Run, assuming the code is in the txn.awk
$ LANG=en_US.UTF-8 ./txn.awk
total words in the file ‘/usr/share/dict/american-english’: 102775
valid words: 73318
invalid words: 29457
table indices for valid words: 65817
textonym groups in the table: 4670
txn>> cafe
cafe -> 2233; the key is in the table, but the word is not in
txn>> 2233
2233 -> (3) abed aced bade
txn>> café
café -> not a valid word for the alphabet:
a b c d e f g h i j k l m n o p q r s t u v w x y z
txn>> --exit
$
$
$ egrep 'café' "/tmp/invalidwords"
café
café's
cafés
$
$ sort -n -b -k 1 "/tmp/textonyms" | tail -n 7
8 6 782537 quaker pucker quakes rubles stakes staler stales sucker
9 3 269 amy bmw cox coy any bow box boy cow
9 4 2273 case acre bard bare barf base cape card care
9 4 7277 parr sars paps pars pass raps rasp saps sass
9 4 7867 pump puns rump rums runs stop sump sums suns
9 5 46637 homer goner goods goofs homes hones hoods hoofs inner
12 5 22737 acres bards barer bares barfs baser bases caper capes cards cares cases
$
$
$ sort -n -b -k 2 "/tmp/phonewords" | tail -n 5
1 20 86242722837478422559 uncharacteristically
1 21 353287636237425647267 electroencephalograms
1 21 353287636237425647274 electroencephalograph
1 22 2686837738658846627437 counterrevolutionaries
1 22 3532876362374256472747 electroencephalographs
$
</pre>
 
=={{header|C}}==
{{libheader|GLib}}
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
Line 369 ⟶ 935:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 393 ⟶ 959:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <fstream>
<lang cpp>
#include <fstream>
#include <iostream>
#include <unordered_map>
Line 431 ⟶ 996:
 
public:
Textonym_Checker(void) : total(0), elements(0), textonyms(0), max_found(0) { }
 
~Textonym_Checker(void) { }
 
void add(const std::string &str) {
std::string mapping;
total += 1+;
 
if (!get_mapping(mapping, str)) return;
Line 443 ⟶ 1,008:
const int num_strings = values[mapping].size();
 
textonyms +=if (num_strings == 1) ? 1 : 0textonyms++;
elements += 1+;
 
if (num_strings > max_found) {
Line 451 ⟶ 1,016:
max_found = num_strings;
}
else if (num_strings == max_found) {
max_strings.push_back(mapping);
}
 
values[mapping].push_back(str);
Line 469 ⟶ 1,033:
std::cout << max_found + 1 << " words each:\n";
 
for (auto it1 =: max_strings.begin(); it1 != max_strings.end(); ++it1) {
std::cout << '\t' << *it1 << " maps to: ";
for (auto it2 =: values[*it1].begin(); it2 != values[*it1].end(); ++it2) {
std::cout << *it2 << " ";
}std::cout << '\n';
std::cout << "\n";
}
std::cout << '\n';
Line 487 ⟶ 1,050:
else {
std::cout << "Key '" << str << "' matches: ";
for (auto it =: values[str].begin(); it != values[str].end(); ++it)
std::cout << *it << " ";
std::cout << '\n';
}
Line 494 ⟶ 1,057:
};
 
int main(void)
{
std::stringauto filename = "unixdict.txt";
std::ifstream input(filename);
Textonym_Checker tc;
Line 513 ⟶ 1,076:
tc.match("27484247");
tc.match("7244967473642");
}</syntaxhighlight>
}
</lang>
{{out}}
<pre>Read 25104 words from unixdict.txt
<pre>
Read 25104 words from unixdict.txt
 
There are 24988 words in unixdict.txt which can be represented by the digit key mapping.
Line 536 ⟶ 1,097:
The [[Textonyms#Tcl|Tcl example]] counts all the words which share a digit sequence with another word. Like the other
examples, this considers a textonym to be a digit sequence which maps to more than one word.
<syntaxhighlight lang="clojure">
<lang Clojure>
(def table
{\a 2 \b 2 \c 2 \A 2 \B 2 \C 2
Line 561 ⟶ 1,122:
(count mapping) " digit combinations to represent them. "
(count textonyms) " digit combinations represent Textonyms.")))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 569 ⟶ 1,130:
=={{header|D}}==
{{trans|Raku}}
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.string, std.range, std.algorithm, std.ascii;
 
Line 595 ⟶ 1,156:
foreach (p; textonyms.schwartzSort!(p => -p[0].length).take(5))
writefln(" %s => %-(%s %)", p[]);
}</langsyntaxhighlight>
{{out}}
<pre>There are 24978 words in unixdict.txt which can be represented by the digit key mapping.
Line 614 ⟶ 1,175:
49376746242 => hydrophobia hydrophobic
6388537663 => mettlesome nettlesome</pre>
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Classes}}
{{libheader| System.Generics.Collections}}
{{libheader| System.Character}}
{{Trans|C++}}
<syntaxhighlight lang="delphi">
program Textonyms;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Classes,
System.Generics.Collections,
System.Character;
 
const
TEXTONYM_MAP = '22233344455566677778889999';
 
type
TextonymsChecker = class
private
Total, Elements, Textonyms, MaxFound: Integer;
MaxStrings: TList<string>;
Values: TDictionary<string, TList<string>>;
FFileName: TFileName;
function Map(c: Char): Char;
function GetMapping(var return: string; const Input: string): Boolean;
public
constructor Create(FileName: TFileName);
destructor Destroy; override;
procedure Add(const Str: string);
procedure Load(FileName: TFileName);
procedure Test;
function Match(const str: string): Boolean;
property FileName: TFileName read FFileName;
end;
 
{ TextonymsChecker }
 
procedure TextonymsChecker.Add(const Str: string);
var
mapping: string;
num_strings: Integer;
 
procedure AddValues(mapping: string; NewItem: string);
begin
if not Values.ContainsKey(mapping) then
Values.Add(mapping, TList<string>.Create);
 
Values[mapping].Add(NewItem);
end;
 
begin
inc(total);
 
if not GetMapping(mapping, Str) then
Exit;
 
if Values.ContainsKey(mapping) then
num_strings := Values[mapping].Count
else
num_strings := 0;
 
inc(Textonyms, ord(num_strings = 1));
inc(Elements);
 
if (num_strings > maxfound) then
begin
MaxStrings.Clear;
MaxStrings.Add(mapping);
MaxFound := num_strings;
end
else if num_strings = MaxFound then
begin
MaxStrings.Add(mapping);
end;
 
AddValues(mapping, Str);
end;
 
constructor TextonymsChecker.Create(FileName: TFileName);
begin
MaxStrings := TList<string>.Create;
Values := TDictionary<string, TList<string>>.Create;
Total := 0;
Textonyms := 0;
MaxFound := 0;
Elements := 0;
Load(FileName);
end;
 
destructor TextonymsChecker.Destroy;
var
key: string;
begin
for key in Values.Keys do
Values[key].Free;
 
Values.Free;
MaxStrings.Free;
inherited;
end;
 
function TextonymsChecker.GetMapping(var return: string; const Input: string): Boolean;
var
i: Integer;
begin
return := Input;
for i := 1 to return.Length do
begin
if not return[i].IsLetterOrDigit then
exit(False);
 
if return[i].IsLetter then
return[i] := Map(return[i]);
end;
Result := True;
end;
 
procedure TextonymsChecker.Load(FileName: TFileName);
var
i: Integer;
begin
if not FileExists(FileName) then
begin
writeln('File "', FileName, '" not found');
exit;
end;
 
with TStringList.Create do
begin
LoadFromFile(FileName);
for i := 0 to count - 1 do
begin
self.Add(Strings[i]);
end;
Free;
end;
end;
 
function TextonymsChecker.Map(c: Char): Char;
begin
Result := TEXTONYM_MAP.Chars[Ord(UpCase(c)) - Ord('A')];
end;
 
function TextonymsChecker.Match(const str: string): Boolean;
var
w: string;
begin
Result := Values.ContainsKey(str);
 
if not Result then
begin
writeln('Key "', str, '" not found');
end
else
begin
write('Key "', str, '" matches: ');
for w in Values[str] do
begin
write(w, ' ');
end;
writeln;
end;
end;
 
procedure TextonymsChecker.Test;
var
i, j: Integer;
begin
writeln('Read ', Total, ' words from ', FileName, #10);
writeln(' which can be represented by the digit key mapping.');
writeln('They require ', Values.Count, ' digit combinations to represent them.');
writeln(textonyms, ' digit combinations represent Textonyms.', #10);
write('The numbers mapping to the most words map to');
writeln(MaxFound + 1, ' words each:');
 
for i := 0 to MaxStrings.Count - 1 do
begin
write(^I, MaxStrings[i], ' maps to: ');
for j := 0 to Values[MaxStrings[i]].Count - 1 do
begin
write(Values[MaxStrings[i]][j], ' ');
end;
Writeln;
end;
 
end;
 
var
Tc: TextonymsChecker;
 
begin
Tc := TextonymsChecker.Create('unixdict.txt');
Tc.Test;
 
tc.match('001');
tc.match('228');
tc.match('27484247');
tc.match('7244967473642');
 
Tc.Free;
readln;
end.
 
</syntaxhighlight>
 
{{out}}
<pre>
Read 25104 words from
 
which can be represented by the digit key mapping.
They require 22905 digit combinations to represent them.
1477 digit combinations represent Textonyms.
 
The numbers mapping to the most words map to9 words each:
269 maps to: amy any bmw bow box boy cow cox coy
729 maps to: paw pax pay paz raw ray saw sax say
Key "001" not found
Key "228" matches: aau act bat cat
Key "27484247" not found
Key "7244967473642" matches: schizophrenia schizophrenic
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-07-03}}
<langsyntaxhighlight lang="factor">USING: assocs assocs.extras interpolate io io.encodings.utf8
io.files kernel literals math math.parser prettyprint sequences
unicode ;
Line 643 ⟶ 1,430:
${} digit combinations represent Textonyms.I] nl nl
 
"7325 -> " write words textonyms 7325 of .</langsyntaxhighlight>
{{out}}
<pre>
Line 658 ⟶ 1,445:
Like the [[Textonyms#Python|Phython example]],
the examples shown are the numbers that map to the most words.
<langsyntaxhighlight lang="go">package main
 
import (
Line 798 ⟶ 1,585:
fmt.Fprintln(w, "\t", k, "maps to:", strings.Join(v, ", "))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 820 ⟶ 1,607:
 
=={{header|Haskell}}==
<syntaxhighlight lang ="haskell">import Data.MaybeChar (isJust, isNothing, fromMaybetoUpper)
import Data.Char (toUpper)
import Data.List (sortBy, groupBy)
import Data.Function (on)
import Data.List (groupBy, sortBy)
import Data.Maybe (fromMaybe, isJust, isNothing)
 
toKey :: Char -> Maybe Char
toKey ch
| ch < 'A' = Nothing
| ch < 'D' = Just '2'
| ch < 'G' = Just '3'
| ch < 'J' = Just '4'
| ch < 'M' = Just '5'
| ch < 'P' = Just '6'
| ch < 'T' = Just '7'
| ch < 'W' = Just '8'
| ch <= 'Z' = Just '9'
| otherwise = Nothing
 
toKeyString :: String -> Maybe String
toKeyString st =
| any letisNothing mch = map (toKey.toUpper) st Nothing
| otherwise = Just $ map (fromMaybe '!') mch
in if any isNothing mch then Nothing
where
else Just $ map (fromMaybe '!') mch
mch = map (toKey . toUpper) st
 
showTextonym :: [(String, String)] -> IO ()String
showTextonym ts = do
let keyCode = fst $ (head ts)
++ " => "
putStrLn $ keyCode ++ " => " ++ concat [w ++ " " | (_,w) <- ts ]
++ concat
[ w ++ " "
| (_, w) <- ts
]
 
main :: IO ()
main = do
let src = "unixdict.txt"
contents <- readFile src
let wordList = lines contents
 
keyedList =
let wordList = lines contents
[ (key, word)
keyedList = [(key, word) | (Just key, word) <- filter (isJust.fst) $ zip (map toKeyString wordList) wordList]
| (Just key, word) <-
groupedList = groupBy ((==) `on` fst) $ sortBy (compare `on` fst) keyedList
textonymList = filter ((>1)isJust . lengthfst) groupedList$
zip (map toKeyString wordList) wordList
 
]
putStrLn $ "There are " ++ show (length keyedList) ++ " words in " ++ src ++ " which can be represented by the digit key mapping."
groupedList =
putStrLn $ "They require " ++ show (length groupedList) ++ " digit combinations to represent them."
groupBy ((==) `on` fst) $
putStrLn $ show (length textonymList) ++ " digit combinations represent Textonyms."
sortBy (compare `on` fst) keyedList
putStrLn ""
textonymList = filter ((> 1) . length) groupedList
putStrLn "Top 5 in ambiguity:"
mapM_ putStrLn $
mapM_ showTextonym $ take 5 $ sortBy (flip compare `on` length) textonymList
putStrLn[ "There are "
putStrLn "Top 5 in ++ show (length:" keyedList)
++ " words in "
mapM_ showTextonym $ take 5 $ sortBy (flip compare `on` (length.fst.head)) textonymList </lang>
++ src
++ " which can be represented by the digit key mapping.",
"They require "
++ show (length groupedList)
++ " digit combinations to represent them.",
show (length textonymList) ++ " digit combinations represent Textonyms.",
"",
"Top 5 in ambiguity:"
]
++ fmap
showTextonym
( take 5 $
sortBy (flip compare `on` length) textonymList
)
++ ["", "Top 5 in length:"]
++ fmap
showTextonym
(take 5 $ sortBy (flip compare `on` (length . fst . head)) textonymList)</syntaxhighlight>
{{out}}
<pre style="font-size:80%">There are 24978 words in unixdict.txt which can be represented by the digit key mapping.
Line 887 ⟶ 1,697:
2668368466 => contention convention </pre>
 
=={{header|Io}}==
 
Or, in terms of ''Data.Map'' and ''traverse'':
<lang Io>main := method(
 
<syntaxhighlight lang="haskell">import Data.Function (on)
import Data.List (groupBy, maximum, sortBy, sortOn)
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import Data.Ord (comparing)
 
------------------------ TEXTONYMS -----------------------
 
digitEncoded ::
M.Map Char Char ->
[String] ->
[(String, String)]
digitEncoded dict =
mapMaybe $
((>>=) . traverse (`M.lookup` dict))
<*> curry Just
 
charDict :: M.Map Char Char
charDict =
M.fromList $
concat $
zipWith
(fmap . flip (,))
(head . show <$> [2 ..])
(words "abc def ghi jkl mno pqrs tuv wxyz")
 
definedSamples ::
Int ->
[[(String, String)]] ->
[[(String, String)] -> Int] ->
[[[(String, String)]]]
definedSamples n xs fs =
[take n . flip sortBy xs] <*> (flip . comparing <$> fs)
 
--------------------------- TEST -------------------------
main :: IO ()
main = do
let fp = "unixdict.txt"
s <- readFile fp
let encodings = digitEncoded charDict $ lines s
codeGroups =
groupBy
(on (==) snd)
. sortOn snd
$ encodings
textonyms = filter ((1 <) . length) codeGroups
mapM_
putStrLn
[ "There are "
<> show (length encodings)
<> " words in "
<> fp
<> " which can be represented\n"
<> "by the digit key mapping.",
"\nThey require "
<> show (length codeGroups)
<> " digit combinations to represent them.",
show (length textonyms)
<> " digit combinations represent textonyms.",
""
]
let codeLength = length . snd . head
[ambiguous, longer] =
definedSamples
5
textonyms
[length, codeLength]
[wa, wl] =
maximum . fmap codeLength
<$> [ambiguous, longer]
mapM_ putStrLn $
"Five most ambiguous:" :
fmap (showTextonym wa) ambiguous
<> ( "" :
"Five longest:" :
fmap
(showTextonym wl)
longer
)
 
------------------------- DISPLAY ------------------------
showTextonym :: Int -> [(String, String)] -> String
showTextonym w ts =
concat
[ rjust w ' ' (snd (head ts)),
" -> ",
unwords $ fmap fst ts
]
where
rjust n c = (drop . length) <*> (replicate n c <>)</syntaxhighlight>
{{Out}}
<pre>There are 24978 words in unixdict.txt which can be represented
by the digit key mapping.
 
They require 22903 digit combinations to represent them.
1473 digit combinations represent textonyms.
 
Five most ambiguous:
269 -> amy any bmw bow box boy cow cox coy
729 -> paw pax pay paz raw ray saw sax say
2273 -> acre bard bare base cape card care case
726 -> pam pan ram ran sam san sao scm
426 -> gam gao ham han ian ibm ibn
 
Five longest:
25287876746242 -> claustrophobia claustrophobic
7244967473642 -> schizophrenia schizophrenic
666628676342 -> onomatopoeia onomatopoeic
49376746242 -> hydrophobia hydrophobic
2668368466 -> contention convention</pre>
 
=={{header|Io}}==
<syntaxhighlight lang="io">main := method(
setupLetterToDigitMapping
 
Line 992 ⟶ 1,915:
)
 
main</langsyntaxhighlight>
{{output}}
<pre>There are 24978 words in unixdict.txt which can be represented by the digit key mapping.
Line 1,028 ⟶ 1,951:
 
=={{header|J}}==
<syntaxhighlight lang="j">require'regex strings web/gethttp'
 
<lang J>require'regex strings web/gethttp'
 
strip=:dyad define
Line 1,066 ⟶ 1,988:
reps=. {&digits@(letters&i.)&.> valid NB. reps is digit seq
reporttext report (#valid);y;(#~.reps);+/(1<#)/.~reps
)</langsyntaxhighlight>
 
Required example:
 
<langsyntaxhighlight Jlang="j"> keys textonymrpt 'http://rosettacode.org/wiki/Textonyms/wordlist'
There are 13085 words in http://rosettacode.org/wiki/Textonyms/wordlist which can be represented by the digit key mapping.
They require 11932 digit combinations to represent them.
661 digit combinations represent Textonyms.</langsyntaxhighlight>
 
In this example, the intermediate results in textonymrpt would look like this (just looking at the first 5 elements of the really big values:
 
<langsyntaxhighlight Jlang="j"> digits
22233344455566677778889999
letters
Line 1,088 ⟶ 2,010:
┌─┬──┬───┬───┬──┐
│2│22│222│226│22│
└─┴──┴───┴───┴──┘</langsyntaxhighlight>
 
Here's another example:
 
<langsyntaxhighlight Jlang="j"> keys textonymrpt 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
There are 24978 words in http://www.puzzlers.org/pub/wordlists/unixdict.txt which can be represnted by the digit key mapping.
They require 22903 digit combinations to represent them.
1473 digit combinations represent Textonyms.</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|c++}}
<langsyntaxhighlight lang="java">
import java.io.IOException;
import java.nio.charset.StandardCharsets;
Line 1,262 ⟶ 2,184:
}
}
</syntaxhighlight>
</lang>
{{out|Output with "java RTextonyms ./unixdict.txt"}}
<pre>
Line 1,282 ⟶ 2,204:
=={{header|jq}}==
The following requires a version of jq with "gsub".
<langsyntaxhighlight lang="jq">def textonym_value:
gsub("a|b|c|A|B|C"; "2")
| gsub("d|e|f|D|E|F"; "3")
Line 1,321 ⟶ 2,243:
;
 
explore</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -R -r -c -s -f textonyms.jq textonyms.txt
There are 13085 words in the Textonyms/wordlist word list that can be represented by the digit-key mapping.
They require 11932 digit combinations to represent them.
Line 1,331 ⟶ 2,253:
The longest Textonyms in the word list have length 11:
26456746242 maps to: ["Anglophobia","Anglophobic"]
24636272673 maps to: ["CinemaScope","Cinemascope"]</langsyntaxhighlight>
 
=={{header|Julia}}==
This solution uses an <tt>aspell</tt> dictionary on the local machine as its word source. The character to number mapping is done via regular expressions and Julia's <tt>replace</tt> function. Because this list contains accented characters, the matching expressions were expanded to include such characters. Words are case sensitive, but the mapping is not, so for example both "Homer" and "homer" are included in the tabulation, each coded as "46637".
'''Function'''
<langsyntaxhighlight Julialang="julia">using Printf
 
const tcode = (Regex=>Char)[r"A|B|C|Ä|Å|Á|Â|Ç" => '2',
Line 1,360 ⟶ 2,282:
return tnym
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
dname = "/usr/share/dict/american-english"
DF = open(dname, "r")
Line 1,403 ⟶ 2,325:
println(@sprintf "%7s (%2d) %s" k length(v) join(v, ", "))
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,449 ⟶ 2,371:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
import java.io.File
Line 1,511 ⟶ 2,433:
fun main(args: Array<String>) {
processList()
}</langsyntaxhighlight>
 
{{out}}
Line 1,545 ⟶ 2,467:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Global variables
http = require("socket.http")
keys = {"VOICEMAIL", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
Line 1,599 ⟶ 2,521:
 
-- Main procedure
showReport(textonyms(http.request(dictFile)))</langsyntaxhighlight>
{{out}}
<pre>There are 24983 words in http://www.puzzlers.org/pub/wordlists/unixdict.txt
Line 1,605 ⟶ 2,527:
They require 22908 digit combinations to represent them.
1473 digit combinations represent Textonyms.</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[Numerify,rls]
rls={"A"->2,"B"->2,"C"->2,"D"->3,"E"->3,"F"->3,"G"->4,"H"->4,"I"->4,"J"->5,"K"->5,"L"->5,"M"->6,"N"->6,"O"->6,"P"->7,"Q"->7,"R"->7,"S"->7,"T"->8,"U"->8,"V"->8,"W"->9,"X"->9,"Y"->9,"Z"->9};
Numerify[s_String]:=Characters[ToUpperCase[s]]/.rls
dict=Once[Import["http://www.rosettacode.org/wiki/Textonyms/wordlist","XML"]];
dict=Cases[dict,XMLElement["pre",{},{x_}]:>x,\[Infinity]];
dict=TakeLargestBy[dict,ByteCount,1][[1]];
dict=DeleteDuplicates[StringTrim/*ToUpperCase/@StringSplit[dict]];
dict=Select[dict,StringMatchQ[(Alternatives@@Keys[rls])..]];
Print["Number of words from Textonyms/wordlist are: ",Length[dict]]
grouped=GroupBy[dict[[;;;;10]],Numerify];
Print["Number of unique numbers: ",Length[grouped]]
grouped=Select[grouped,Length/*GreaterThan[1]];
Print["Most with the same number:"]
KeyValueMap[List,TakeLargestBy[grouped,Length,1]]//Grid
Print["5 longest words with textonyms:"]
List@@@Normal[ReverseSortBy[grouped,First/*Length][[;;5]]]//Grid</syntaxhighlight>
{{out}}
<pre>Number of words from Textonyms/wordlist are: 71125
Number of unique numbers: 7030
Most with the same number:
{2,6,6,6} {AMON,COMO,CONN,ANON}
5 longest words with textonyms:
{2,4,6,6,4,7,4,6,4} {CHONGQING,AGONISING}
{3,5,3,2,8,4,6,6} {EJECTION,ELECTION}
{2,8,7,8,4,3,7,8} {BUSTIEST,CURVIEST}
{2,8,7,3,8,8,3,7} {BURETTES,CURETTES}
{3,7,8,2,8,3,7} {EQUATES,ESTATES}</pre>
 
=={{header|MiniScript}}==
This solution assumes the Mini Micro environment (providing the listUtil and mapUtil modules, as well as the englishWords.txt file).
<syntaxhighlight lang="miniscript">import "listUtil"
import "mapUtil"
 
groups = "abc def ghi jkl mno pqrs tuv wxyz".split
charToNum = {}
for i in groups.indexes
for ch in groups[i]
charToNum[ch] = i + 2
end for
end for
 
words = file.readLines("/sys/data/englishWords.txt")
 
wordToNum = function(word)
parts = word.split("")
parts.apply function(ch)
return charToNum[ch]
end function
return parts.join("")
end function
 
numToWords = {}
moreThan1Word = 0
for word in words
num = wordToNum(word.lower)
if numToWords.hasIndex(num) then
numToWords[num].push word
else
numToWords[num] = [word]
end if
if numToWords[num].len == 2 then moreThan1Word = moreThan1Word + 1
end for
 
print "There are " + words.len + " words in englishWords.txt which can be represented by the digit key mapping."
print "They require " + numToWords.len + " digit combinations to represent them."
print moreThan1Word + " digit combinations represent Textonyms."
 
while true
print
inp = input("Enter a word or digit combination: ")
if not inp then break
if val(inp) > 0 then
print inp + " -> " + numToWords.get(inp)
else
num = wordToNum(inp.lower)
print "Digit key combination for """ + inp + """ is: " + num
print num + " -> " + numToWords.get(num)
end if
end while</syntaxhighlight>
{{out}}
<pre>There are 64664 words in englishWords.txt which can be represented
by the digit key mapping.
They require 59148 digit combinations to represent them.
4028 digit combinations represent Textonyms.
 
Enter a word or digit combination: 2877464
2877464 -> ["burping", "bussing", "cupping", "cursing", "cussing"]
 
Enter a word or digit combination: phoning
Digit key combination for "phoning" is: 7466464
7466464 -> ["phoning", "pinning", "rimming", "shooing", "sinning"]</pre>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import algorithm, sequtils, strformat, strutils, tables
 
const
 
WordList = "unixdict.txt"
Url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt"
 
Digits = "22233344455566677778889999"
 
proc processList(wordFile: string) =
 
var mapping: Table[string, seq[string]]
var countValid = 0
 
for word in wordFile.lines:
var valid = true
var key: string
for c in word.toLowerAscii:
if c notin 'a'..'z':
valid = false
break
key.add Digits[ord(c) - ord('a')]
if valid:
inc countValid
mapping.mgetOrPut(key, @[]).add word
 
let textonyms = toSeq(mapping.pairs).filterIt(it[1].len > 1)
echo &"There are {countValid} words in '{Url}' ",
&"which can be represented by the digit key mapping."
echo &"They require {mapping.len} digit combinations to represent them."
echo &"{textonyms.len} digit combinations represent Textonyms.\n"
 
let longest = textonyms.sortedByIt(-it[0].len)
let ambiguous = longest.sortedByIt(-it[1].len)
echo "Top 8 in ambiguity:\n"
echo "Count Textonym Words"
echo "====== ======== ====="
for a in ambiguous[0..7]:
echo &"""{a[1].len:4} {a[0]:>8} {a[1].join(", ")}"""
 
echo "\nTop 6 in length:\n"
echo "Length Textonym Words"
echo "====== ============== ====="
for l in longest[0..5]:
echo &"""{l[0].len:4} {l[0]:>14} {l[1].join(", ")}"""
 
processList(WordList)</syntaxhighlight>
 
{{out}}
<pre>There are 24978 words in 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' which can be represented by the digit key mapping.
They require 22903 digit combinations to represent them.
1473 digit combinations represent Textonyms.
 
Top 8 in ambiguity:
 
Count Textonym Words
====== ======== =====
9 729 paw, pax, pay, paz, raw, ray, saw, sax, say
9 269 amy, any, bmw, bow, box, boy, cow, cox, coy
8 2273 acre, bard, bare, base, cape, card, care, case
8 726 pam, pan, ram, ran, sam, san, sao, scm
7 4663 gone, good, goof, home, hone, hood, hoof
7 7283 pate, pave, rate, rave, saud, save, scud
7 782 pta, pub, puc, pvc, qua, rub, sub
7 426 gam, gao, ham, han, ian, ibm, ibn
 
Top 6 in length:
 
Length Textonym Words
====== ============== =====
14 25287876746242 claustrophobia, claustrophobic
13 7244967473642 schizophrenia, schizophrenic
12 666628676342 onomatopoeia, onomatopoeic
11 49376746242 hydrophobia, hydrophobic
10 2668368466 contention, convention
10 6388537663 mettlesome, nettlesome</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">module IntMap = Map.Make(Int)
 
let seq_lines ch =
let rec repeat () =
match input_line ch with
| s -> Seq.Cons (s, repeat)
| exception End_of_file -> Nil
in repeat
 
(* simply use bijective numeration in base 8 for keys *)
 
let key_of_char = function
| 'a' .. 'c' -> Some 1
| 'd' .. 'f' -> Some 2
| 'g' .. 'i' -> Some 3
| 'j' .. 'l' -> Some 4
| 'm' .. 'o' -> Some 5
| 'p' .. 's' -> Some 6
| 't' .. 'v' -> Some 7
| 'w' .. 'z' -> Some 8
| _ -> None
 
let keys_of_word =
let next k c =
Option.bind (key_of_char c) (fun d -> Option.map (fun k -> k lsl 3 + d) k)
in String.fold_left next (Some 0)
 
let update m k =
IntMap.update k (function Some n -> Some (succ n) | None -> Some 1) m
 
let map_from ch =
seq_lines ch |> Seq.filter_map keys_of_word |> Seq.fold_left update IntMap.empty
 
let count _ n (words, keys, txtns) =
words + n, succ keys, if n > 1 then succ txtns else txtns
 
let show src (words, keys, txtns) = Printf.printf "\
There are %u words in %s which can be represented by the digit key mapping.\n\
They require %u digit combinations to represent them.\n\
%u digit combinations represent Textonyms.\n" words src keys txtns
 
let () =
show "stdin" (IntMap.fold count (map_from stdin) (0, 0, 0))</syntaxhighlight>
{{out}}
<pre>
There are 24978 words in stdin which can be represented by the digit key mapping.
They require 22903 digit combinations to represent them.
1473 digit combinations represent Textonyms.
</pre>
...when being feeded with unixdict.txt
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my $src = 'unixdict.txt';
 
# filter word-file for valid input, transform to low-case
Line 1,623 ⟶ 2,769:
print "There are @{[scalar @words]} words in '$src' which can be represented by the digit key mapping.
They require @{[scalar @dials]} digit combinations to represent them.
@{[scalar @textonyms]} digit combinations represent Textonyms.";</langsyntaxhighlight>
{{out}}
<pre>There are 24978 words in 'unixdict.txt' which can be represented by the digit key mapping.
Line 1,630 ⟶ 2,776:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence digit = repeat(-1,255)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
digit['a'..'c'] = '2'
<span style="color: #004080;">sequence</span> <span style="color: #000000;">digit</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">255</span><span style="color: #0000FF;">)</span>
digit['d'..'f'] = '3'
<span style="color: #000000;">digit</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'c'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'2'</span>
digit['g'..'i'] = '4'
<span style="color: #000000;">digit</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'d'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'f'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'3'</span>
digit['j'..'l'] = '5'
<span style="color: #000000;">digit</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'g'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'i'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'4'</span>
digit['m'..'o'] = '6'
<span style="color: #000000;">digit</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'j'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'l'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'5'</span>
digit['p'..'s'] = '7'
<span style="color: #000000;">digit</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'m'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'o'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'6'</span>
digit['t'..'v'] = '8'
<span style="color: #000000;">digit</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'p'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'s'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'7'</span>
digit['w'..'z'] = '9'
<span style="color: #000000;">digit</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'t'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'v'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'8'</span>
 
<span style="color: #000000;">digit</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'w'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'z'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'9'</span>
function digits(string word)
for i=1 to length(word) do
<span style="color: #008080;">function</span> <span style="color: #000000;">digits</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">)</span>
integer ch = word[i]
<span style="color: #004080;">string</span> <span style="color: #000000;">keycode</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">))</span>
if ch<'a' or ch>'z' then return "" end if
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
word[i] = digit[ch]
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
end for
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'a'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'z'</span><span style="color: #0000FF;">)</span>
return word
<span style="color: #000000;">keycode</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">digit</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">]</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">keycode</span><span style="color: #0000FF;">,</span><span style="color: #000000;">word</span><span style="color: #0000FF;">}</span>
sequence words = {}, last=""
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
object word, keycode
integer keycode_count = 0, textonyms = 0,
<span style="color: #008080;">function</span> <span style="color: #000000;">az</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)>=</span><span style="color: #008000;">'a'</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)<=</span><span style="color: #008000;">'z'</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
this_count = 0, max_count = 0, max_idx
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">unix_dict</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">az</span><span style="color: #0000FF;">),</span><span style="color: #000000;">digits</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">max_idx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">long_idx</span>
integer fn = open("demo\\unixdict.txt","r")
<span style="color: #004080;">string</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">keycode</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">last</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
while 1 do
<span style="color: #004080;">integer</span> <span style="color: #000000;">keycode_count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">textonyms</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
word = trim(gets(fn))
<span style="color: #000000;">this_count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">max_count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">longest</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
if atom(word) then exit end if
keycode = digits(word)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"There are %d words in unixdict.txt which can be represented by the digit key mapping.\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)})</span>
if length(keycode) then
words = append(words, {keycode, word})
<span style="color: #000080;font-style:italic;">-- Sort by keycode: while words are ordered we get
end if
-- eg {"a","ab","b","ba"} -&gt; {"2","22","2","22"}</span>
end while
<span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">))</span>
close(fn)
printf(1,"There are %d words in unixdict.txt which can be represented by the digit key mapping.\n",{length(words)})
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
 
<span style="color: #0000FF;">{</span><span style="color: #000000;">keycode</span><span style="color: #0000FF;">,</span><span style="color: #000000;">word</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
words = sort(words)
<span style="color: #008080;">if</span> <span style="color: #000000;">keycode</span><span style="color: #0000FF;">=</span><span style="color: #000000;">last</span> <span style="color: #008080;">then</span>
for i=1 to length(words) do
<span style="color: #000000;">textonyms</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">this_count</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
{keycode,word} = words[i]
<span style="color: #000000;">this_count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if keycode=last then
<span style="color: #008080;">if</span> <span style="color: #000000;">this_count</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">max_count</span> <span style="color: #008080;">then</span>
textonyms += this_count=1
<span style="color: #008080;">if</span> <span style="color: #000000;">this_count</span><span style="color: #0000FF;">></span><span style="color: #000000;">max_count</span> <span style="color: #008080;">then</span>
this_count += 1
<span style="color: #000000;">max_idx</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">}</span>
if this_count>max_count then
max_count <span style="color: this_count#008080;">else</span>
<span style="color: #000000;">max_idx</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</span>
max_idx = i
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">max_count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">this_count</span>
else
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
keycode_count += 1
<span style="color: #008080;">else</span>
last = keycode
<span style="color: #000000;">keycode_count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
this_count = 1
<span style="color: #000000;">last</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">keycode</span>
end if
<span style="color: #000000;">this_count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)>=</span><span style="color: #000000;">longest</span> <span style="color: #008080;">then</span>
printf(1,"They require %d digit combinations to represent them.\n",{keycode_count})
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)></span><span style="color: #000000;">longest</span> <span style="color: #008080;">then</span>
printf(1,"%d digit combinations represent Textonyms.\n",{textonyms})
<span style="color: #000000;">long_idx</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">}</span>
 
<span style="color: #008080;">else</span>
sequence dups = {}
<span style="color: #000000;">long_idx</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</span>
for i=max_idx-max_count+1 to max_idx do
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
dups = append(dups,words[i][2])
<span style="color: #000000;">longest</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"The maximum number of textonyms for a particular digit key mapping is %d:\n",{max_count})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"They require %d digit combinations to represent them.\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">keycode_count</span><span style="color: #0000FF;">})</span>
printf(1," %s encodes %s\n",{words[max_idx][1],join(dups,"/")})</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d digit combinations represent Textonyms.\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">textonyms</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The maximum number of textonyms for a particular digit key mapping is %d:\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">max_count</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">max_idx</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">max_idx</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">-</span><span style="color: #000000;">max_count</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">dups</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">vslice</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">],</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"/"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %s encodes %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">dups</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The longest words are %d characters long\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">longest</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Encodings with this length are:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">long_idx</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %s encodes %s\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">long_idx</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{Out}}
<small>(my unixdict.txt seems to have grown by 4 entries sometime in the past couple of years...)</small>
<pre>
There are 2497924981 words in unixdict.txt which can be represented by the digit key mapping.
They require 2290422906 digit combinations to represent them.
1473 digit combinations represent Textonyms.
The maximum number of textonyms for a particular digit key mapping is 9:
269 encodes amy/any/bmw/bow/box/boy/cow/cox/coy
729 encodes paw/pax/pay/paz/raw/ray/saw/sax/say
The longest words are 22 characters long
Encodings with this length are:
3532876362374256472749 encodes electroencephalography
</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
$url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt"
$file = "$env:TEMP\unixdict.txt"
Line 1,749 ⟶ 2,913:
 
Remove-Item -Path $file -Force -ErrorAction SilentlyContinue
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,779 ⟶ 2,943:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from collections import defaultdict
import urllib.request
 
Line 1,840 ⟶ 3,004:
print(" %s maps to: %s" % (num, ', '.join(wrds)))
 
interactiveconversions()</langsyntaxhighlight>
 
{{out}}
Line 1,869 ⟶ 3,033:
 
=={{header|Racket}}==
 
This version allows digits to be used (since you can usually enter them through an SMS-style keypad).
 
<code>unixdict.txt</code> has words like <q>2nd</q> which would not be valid using letters only, but is textable.
 
<langsyntaxhighlight lang="racket">#lang racket
(module+ test (require tests/eli-tester))
(module+ test
Line 1,954 ⟶ 3,117:
 
(module+ main
(report-on-file "data/unixdict.txt"))</langsyntaxhighlight>
 
{{out}}
Line 1,988 ⟶ 3,151:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>my $src = 'unixdict.txt';
 
my @words = slurp($src).lines.grep(/ ^ <alpha>+ $ /);
Line 2,009 ⟶ 3,172:
 
say "\nTop 5 in length:";
say " ",$_ for @textonyms.sort(-*.key.chars)[^5];</langsyntaxhighlight>
{{out}}
<pre>There are 24978 words in unixdict.txt which can be represented by the digit key mapping.
Line 2,032 ⟶ 3,195:
Extra code was added detect and display a count illegal words &nbsp; (words not representable by the ''key digits''), &nbsp; and
<br>also duplicate words in the dictionary.
<langsyntaxhighlight lang="rexx">/*REXX program counts and displays the number of textonyms that are in a dictionary file*/
parse arg iFID . /*obtain optional fileID from the C.L. */
if iFID=='' | iFID=="," then iFID='UNIXDICT.TXT' /*Not specified? Then use the default.*/
Line 2,046 ⟶ 3,209:
 
do while lines(iFID)\==0; x= linein(iFID) /*keep reading the file until exhausted*/
y= x; upper x /*save a copy of X; uppercase X. */
if \datatype(x, 'U') then do; ills= ills + 1; iterate; end /*Not legal? Skip.*/
if $.x==. then do; dups= dups + 1; iterate; end /*Duplicate? Skip.*/
$.x= . /*indicate that it's a righteous word. */
#word= #word + 1 /*bump the word count (for the file). */
Line 2,055 ⟶ 3,218:
!.z= !.z y; _= words(!.z) /*build list of equivalent digit key(s)*/
 
if _>most then do; mostus= z; most= _; end /*remember the "mostus" digit keys. */
 
if @.z==2 then do; #= # + 1 /*bump the count of the textonyms. */
Line 2,067 ⟶ 3,230:
if @.z==1 then digKey= digKey + 1 /*bump the count of digit key words. */
end /*while*/
 
@dict= 'in the dictionary file' /*literal used for some displayed text.*/
@dict= 'in the dictionary file' /*literal used for some displayed text.*/
L= length(commas(max(#word,ills,dups,digKey,#))) /*find length of max # being displayed.*/
say 'The dictionary file being used is: ' iFID
say
call tell #word, 'words' @dict "which can be represented by digit key mapping"
if ills>0 then call tell ills#word, 'wordwords's(ills) "that contain illegal characters" @dict,
"which can be represented by digit key mapping"
if dups>0 then call tell dups, 'duplicate word's(dups) "detected" @dict
if ills>0 then call tell ills, 'word's(ills) "that contain illegal characters" @dict
if dups>0 then call tell dups, 'duplicate word's(dups) "detected" @dict
call tell digKey, 'combination's(digKey) "required to represent them"
call tell #, 'digit combination's(#) "that can represent Textonyms"
say
say; if first\==. then say ' first digit key=' !.first
if first last\== . then say ' lastfirst digit key=' !.lastfirst
if last if long\==0 . then say ' longest last digit key=' !.longlast
if long if most\== 0 then say ' numerous longest digit key=' !.mostus " ("most 'words)'long
if most \== 0 then say ' numerous digit key=' !.mostus " ("most 'words)'
exit # /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _
tell: arg ##; say 'There are ' right(commas(##), L)' ' arg(2).; return /*commatize #*/
s: if arg(1)==1 then return ''; return "s" /*a simple pluralizer.*/</langsyntaxhighlight>
 
{{out|output|text=&nbsp; when using the default input file:}}
<pre>
The dictionary file being used is: UNIXDICT.TXT
 
There are 24,978 words in the dictionary file which can be represented by digit key mapping.
There are 126 words that contain illegal characters in the dictionary file.
Line 2,102 ⟶ 3,270:
<pre>
The dictionary file being used is: TEXTONYMS.TXT
 
There are 12,990 words in the dictionary file which can be represented by digit key mapping.
There are 95 duplicate words detected in the dictionary file.
Line 2,114 ⟶ 3,283:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">
CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Textonyms = Hash.new {|n, g| n[g] = []}
NUMS = "22233344455566677778889999" * 2
File.open("Textonyms.txt") do |file|
dict = "unixdict.txt"
file.each_line {|line|
Textonyms[(n=line.chomp).gsub(/a|b|c|A|B|C/, '2').gsub(/d|e|f|D|E|F/, '3').gsub(/g|h|i|G|H|I/, '4').gsub(/p|q|r|s|P|Q|R|S/, '7')
.gsub(/j|k|l|J|K|L/, '5').gsub(/m|n|o|M|N|O/, '6').gsub(/t|u|v|T|U|V/, '8').gsub(/w|x|y|z|W|X|Y|Z/, '9')] += [n]
}
end
</lang>
{{out}}
<pre>
puts "There are #{Textonyms.inject(0){|n,g| n+g[1].length}} words in #{"Wordlist"} which can be represnted by the Textonyms mapping."
puts "They require #{Textonyms.length} digit combinations to represent them."
puts "#{Textonyms.inject(0){|n,g| g[1].length > 1 ? n+1 : n}} digit combinations correspond to a Textonym"
 
textonyms = File.open(dict){|f| f.map(&:chomp).group_by {|word| word.tr(CHARS, NUMS) } }
There are 132916 words in Wordlist which can be represnted by the Textonyms mapping.
They require 117868 digit combinations to represent them.
9579 digit combinations correspond to a Textonym
</pre>
<pre>
puts Textonymes["7353284667"]
 
puts "There are #{File.readlines(dict).size} words in #{dict} which can be represented by the digit key mapping.
rejections
They require #{textonyms.size} digit combinations to represent them.
selections
#{textonyms.count{|_,v| v.size > 1}} digit combinations represent Textonyms."
</pre>
 
puts "\n25287876746242: #{textonyms["25287876746242"].join(", ")}"
</syntaxhighlight>
{{out}}
<pre>
There are 25104 words in unixdict.txt which can be represented by the digit key mapping.
puts Textonymes["736672"]
They require 23003 digit combinations to represent them.
1485 digit combinations represent Textonyms.
 
25287876746242: claustrophobia, claustrophobic
remora
senora
</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufRead};
Line 2,236 ⟶ 3,395:
Err(error) => eprintln!("{}: {}", args[1], error),
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,261 ⟶ 3,420:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">var words = ARGF.grep(/^[[:alpha:]]+\z/);
 
var dials = words.group_by {
Line 2,280 ⟶ 3,439:
 
say "\nTop 5 in length:";
say textonyms.sort_by { |k,_| -k.len }.first(5).join("\n");</langsyntaxhighlight>
{{out}}
<pre>
Line 2,303 ⟶ 3,462:
</pre>
 
=={{header|TclSwift}}==
<syntaxhighlight lang="swift">import Foundation
 
func textCharacter(_ ch: Character) -> Character? {
<lang Tcl>set keymap {
switch (ch) {
case "a", "b", "c":
return "2"
case "d", "e", "f":
return "3"
case "g", "h", "i":
return "4"
case "j", "k", "l":
return "5"
case "m", "n", "o":
return "6"
case "p", "q", "r", "s":
return "7"
case "t", "u", "v":
return "8"
case "w", "x", "y", "z":
return "9"
default:
return nil
}
}
 
func textString(_ string: String) -> String? {
var result = String()
result.reserveCapacity(string.count)
for ch in string {
if let tch = textCharacter(ch) {
result.append(tch)
} else {
return nil
}
}
return result
}
 
func compareByWordCount(pair1: (key: String, value: [String]),
pair2: (key: String, value: [String])) -> Bool {
if pair1.value.count == pair2.value.count {
return pair1.key < pair2.key
}
return pair1.value.count > pair2.value.count
}
 
func compareByTextLength(pair1: (key: String, value: [String]),
pair2: (key: String, value: [String])) -> Bool {
if pair1.key.count == pair2.key.count {
return pair1.key < pair2.key
}
return pair1.key.count > pair2.key.count
}
 
func findTextonyms(_ path: String) throws {
var dict = Dictionary<String, [String]>()
let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
var count = 0
for line in contents.components(separatedBy: "\n") {
if line.isEmpty {
continue
}
let word = line.lowercased()
if let text = textString(word) {
dict[text, default: []].append(word)
count += 1
}
}
var textonyms = Array(dict.filter{$0.1.count > 1})
print("There are \(count) words in '\(path)' which can be represented by the digit key mapping.")
print("They require \(dict.count) digit combinations to represent them.")
print("\(textonyms.count) digit combinations represent Textonyms.")
 
let top = min(5, textonyms.count)
print("\nTop \(top) by number of words:")
textonyms.sort(by: compareByWordCount)
for (text, words) in textonyms.prefix(top) {
print("\(text) = \(words.joined(separator: ", "))")
}
 
print("\nTop \(top) by length:")
textonyms.sort(by: compareByTextLength)
for (text, words) in textonyms.prefix(top) {
print("\(text) = \(words.joined(separator: ", "))")
}
}
 
do {
try findTextonyms("unixdict.txt")
} catch {
print(error.localizedDescription)
}</syntaxhighlight>
 
{{out}}
<pre>
There are 24978 words in 'unixdict.txt' which can be represented by the digit key mapping.
They require 22903 digit combinations to represent them.
1473 digit combinations represent Textonyms.
 
Top 5 by number of words:
269 = amy, any, bmw, bow, box, boy, cow, cox, coy
729 = paw, pax, pay, paz, raw, ray, saw, sax, say
2273 = acre, bard, bare, base, cape, card, care, case
726 = pam, pan, ram, ran, sam, san, sao, scm
426 = gam, gao, ham, han, ian, ibm, ibn
 
Top 5 by length:
25287876746242 = claustrophobia, claustrophobic
7244967473642 = schizophrenia, schizophrenic
666628676342 = onomatopoeia, onomatopoeic
49376746242 = hydrophobia, hydrophobic
2668368466 = contention, convention
</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">set keymap {
2 -> ABC
3 -> DEF
Line 2,372 ⟶ 3,645:
}
 
puts [main $keymap $url]</langsyntaxhighlight>
 
{{out}}
Line 2,386 ⟶ 3,659:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1)
Line 2,432 ⟶ 3,705:
objMoreThanOneWord.Count & " digit combinations represent Textonyms."
 
objInFile.Close</langsyntaxhighlight>
{{out}}
<pre>There are 24978 words in "unixdict.txt" which can be represented by the digit key mapping.
They require 22903 digit combinations to represent them.
1473 digit combinations represent Textonyms.</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-str}}
{{libheader|Wren-sort}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "io" for File
import "./str" for Char, Str
import "./sort" for Sort
import "./fmt" for Fmt
 
var wordList = "unixdict.txt"
var DIGITS = "22233344455566677778889999"
var map = {}
var countValid = 0
var words = File.read(wordList).trimEnd().split("\n")
for (word in words) {
var valid = true
var sb = ""
for (c in Str.lower(word)) {
if (!Char.isLower(c)) {
valid = false
break
}
sb = sb + DIGITS[Char.code(c) - 97]
}
if (valid) {
countValid = countValid + 1
if (map.containsKey(sb)) {
map[sb].add(word)
} else {
map[sb] = [word]
}
}
}
var textonyms = map.toList.where { |me| me.value.count > 1 }.toList
var report = "There are %(countValid) words in '%(wordList)' " +
"which can be represented by the digit key mapping.\n" +
"They require %(map.count) digit combinations to represent them.\n" +
"%(textonyms.count) digit combinations represent Textonyms.\n"
System.print(report)
 
var longest = Sort.merge(textonyms) { |i, j| (j.key.count - i.key.count).sign }
var ambiguous = Sort.merge(longest) { |i, j| (j.value.count - i.value.count).sign }
 
System.print("Top 8 in ambiguity: \n")
System.print("Count Textonym Words")
System.print("====== ======== =====")
var f = "$4d $-8s $s"
for (a in ambiguous.take(8)) Fmt.print(f, a.value.count, a.key, a.value)
 
f = f.replace("8", "14")
System.print("\nTop 6 in length:\n")
System.print("Length Textonym Words")
System.print("====== ============== =====")
for (l in longest.take(6)) Fmt.print(f, l.key.count, l.key, l.value)</syntaxhighlight>
 
{{out}}
<pre>
There are 24978 words in 'unixdict.txt' which can be represented by the digit key mapping.
They require 22903 digit combinations to represent them.
1473 digit combinations represent Textonyms.
 
Top 8 in ambiguity:
 
Count Textonym Words
====== ======== =====
9 269 amy any bmw bow box boy cow cox coy
9 729 paw pax pay paz raw ray saw sax say
8 2273 acre bard bare base cape card care case
8 726 pam pan ram ran sam san sao scm
7 4663 gone good goof home hone hood hoof
7 7283 pate pave rate rave saud save scud
7 782 pta pub puc pvc qua rub sub
7 426 gam gao ham han ian ibm ibn
 
Top 6 in length:
 
Length Textonym Words
====== ============== =====
14 25287876746242 claustrophobia claustrophobic
13 7244967473642 schizophrenia schizophrenic
12 666628676342 onomatopoeia onomatopoeic
11 49376746242 hydrophobia hydrophobic
10 2668368466 contention convention
10 6388537663 mettlesome nettlesome
</pre>
 
=={{header|zkl}}==
{{trans|Python}}
Like the Python example, this solution uses the Unix Dictionary, rather than the textonyms word list as I don't want to parse the HTML.
<langsyntaxhighlight lang="zkl">URL:="http://www.puzzlers.org/pub/wordlists/unixdict.txt";
var ZC=Import("zklCurl");
var keypad=Dictionary(
Line 2,470 ⟶ 3,830:
foreach k,v in (wcnt.filter('wrap([(k,v)]){ v.len()==maxWordPerNum })){
println(" %s is the textonym of: %s".fmt(k,v.concat(", ")));
}</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits