Word wheel: Difference between revisions

58,938 bytes added ,  17 days ago
m
→‎No metatables, simple: more concise loop through characters of string
(Add 8080 assembly)
m (→‎No metatables, simple: more concise loop through characters of string)
 
(70 intermediate revisions by 30 users not shown)
Line 10:
 
 
;An example: <big><b>
::::::: {| class="wikitable"
| N
| D
Line 23:
| L
| W
|}
</b></big>
 
;Task:
Line 30 ⟶ 31:
Specifically:
:* Find all words of 3 or more letters using only the letters in the string &nbsp; '''ndeokgelw'''.
:* All words must contain the central letter &nbsp; <big>'''kK'''.</big>
:* Each letter may be used only as many times as it appears in the string.
:* For this task we'll use lowercase English letters exclusively.
Line 46 ⟶ 47:
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V GRID =
‘N D E
O K G
E L W’
 
F getwords()
V words = File(‘unixdict.txt’).read().lowercase().split("\n")
R words.filter(w -> w.len C 3..9)
 
F solve(grid, dictionary)
DefaultDict[Char, Int] gridcount
L(g) grid
gridcount[g]++
 
F check_word(word)
DefaultDict[Char, Int] lcount
L(l) word
lcount[l]++
L(l, c) lcount
I c > @gridcount[l]
R 1B
R 0B
 
V mid = grid[4]
R dictionary.filter(word -> @mid C word & !@check_word(word))
 
V chars = GRID.lowercase().split_py().join(‘’)
V found = solve(chars, dictionary' getwords())
print(found.join("\n"))</syntaxhighlight>
 
{{out}}
<pre>
eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
</pre>
 
=={{header|8080 Assembly}}==
Line 53 ⟶ 108:
(the given ~206kb <code>unixdict.txt</code> works fine).
 
<langsyntaxhighlight lang="8080asm">puts: equ 9 ; CP/M syscall to print string
fopen: equ 15 ; CP/M syscall to open a file
fread: equ 20 ; CP/M syscall to read from file
Line 163 ⟶ 218:
wheel: ds 9 ; Room for wheel
wcpy: ds 9 ; Copy of wheel (to mark characters used)
word: equ $ ; Room for current word</langsyntaxhighlight>
 
{{out}}
Line 187 ⟶ 242:
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
procedure Wordwheel is
Compulsory_Ix : constant Positive := 5;
Min_Length : constant Positive := 3;
 
function Char_Posn (Str : Unbounded_String; C : Character) return Natural is
begin
for Ix in 1 .. Length (Str) loop
if Element (Str, Ix) = C then
return Ix;
end if;
end loop;
return 0;
end Char_Posn;
 
procedure Search (Dict_Filename : String; Wheel : String) is
Dict_File : File_Type;
Allowed : constant String := To_Lower (Wheel);
Required_Char : constant String (1 .. 1) := "" & Allowed (Compulsory_Ix);
Available, Dict_Word : Unbounded_String;
Dict_Word_Len : Positive;
Matched : Boolean;
Posn : Natural;
begin
Open (File => Dict_File, Mode => In_File, Name => Dict_Filename);
while not End_Of_File (Dict_File) loop
Dict_Word := Get_Line (Dict_File);
Dict_Word_Len := Length (Dict_Word);
if Dict_Word_Len >= Min_Length and then
Dict_Word_Len <= Wheel'Length and then
Ada.Strings.Unbounded.Count (Dict_Word, Required_Char) > 0
then
Available := To_Unbounded_String (Allowed);
Matched := True;
for i in 1 .. Dict_Word_Len loop
Posn := Char_Posn (Available, Element (Dict_Word, i));
if Posn > 0 then
Delete (Source => Available, From => Posn, Through => Posn);
else
Matched := False;
exit;
end if;
end loop;
if Matched then
Put_Line (Dict_Word);
end if;
end if;
end loop;
Close (Dict_File);
end Search;
begin
Search ("unixdict.txt", "ndeokgelw");
end Wordwheel;
</syntaxhighlight>
{{out}}
<pre>
eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">wordwheel←{
words←((~∊)∘⎕TC⊆⊢) 80 ¯1⎕MAP ⍵
match←{
0=≢⍵:1
~(⊃⍵)∊⍺:0
⍺[(⍳⍴⍺)~⍺⍳⊃⍵]∇1↓⍵
}
middle←(⌈0.5×≢)⊃⊢
words←((middle ⍺)∊¨words)/words
words←(⍺∘match¨words)/words
(⍺⍺≤≢¨words)/words
}</syntaxhighlight>
{{out}}
<pre> 'ndeokgelw' (3 wordwheel) 'unixdict.txt'
eke elk keel keen keg ken keno knee kneel knew know knowledge kong leek week wok woke </pre>
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
 
--------------------------- TEST ---------------------------
on run
unlines(gridWords({"NDE", "OKG", "ELW"}, ¬
paragraphs of readFile("~/Desktop/unixdict.txt")))
end run
 
------------------------ WORD WHEEL ----------------------
 
-- wordWheelMatches :: NSString -> [String] -> String -> String
----------------------- WHEEL WORDS ------------------------
on wordWheelMatches(lexicon, wordWheelRows)
 
-- gridWords :: [String] -> [String] -> [String]
on gridWords(grid, lexemes)
set wheel to sort(characters of toLower(concat(grid)))
set mid to item (1 + ((length of wheel) div 2)) of wheel
set wheelGroups to group(sort(characters of ¬
script p
on |λ|concat(cwordWheelRows)))
wheel contains c
end |λ|
end script
script matchisWheelWord
on |λ|(w)
setscript cs to characters of wavailable
2 < length of cson and all|λ|(pa, csb) and ¬
cs contains mid and wheelFit(wheel,length cs)of a ≤ length of b
end |λ|
end script
script used
on |λ|(grp)
w contains item 1 of grp
end |λ|
end script
all(my identity, ¬
zipWith(available, ¬
group(sort(characters of w)), ¬
filter(used, wheelGroups)))
end |λ|
end script
filter(match, lexemes)
set matches to filter(isWheelWord, ¬
end gridWords
filteredLines(wordWheelPreFilter(wordWheelRows), lexicon))
(length of matches as text) & " matches:" & ¬
linefeed & linefeed & unlines(matches)
end wordWheelMatches
 
 
-- wheelFitwordWheelPreFilter :: [CharString] -> [Char] -> BoolString
on wordWheelPreFilter(wordWheelRows)
on wheelFit(wheel, w)
set pivot to item 2 of item 2 of wordWheelRows
script go
set charSet to nub(concat(wordWheelRows))
on |λ|(ws, cs)
if {} = cs then
true
else if {} = ws then
false
else if item 1 of ws = item 1 of cs then
|λ|(rest of ws, rest of cs)
else
|λ|(rest of ws, cs)
end if
end |λ|
end script
"(2 < self.length) and (self contains '" & pivot & "') " & ¬
tell go to |λ|(wheel, sort(w))
"and not (self matches '^.*[^" & charSet & "].*$') "
end wheelFit
end wordWheelPreFilter
 
 
--------------------------- TEST -------------------------
on run
set fpWordList to scriptFolder() & "unixdict.txt"
if doesFileExist(fpWordList) then
wordWheelMatches(readFile(fpWordList), ¬
{"nde", "okg", "elw"})
else
display dialog "Word list not found in script folder:" & ¬
linefeed & tab & fpWordList
end if
end run
 
 
 
----------- GENERIC :: FILTERED LINES FROM FILE ----------
 
-- doesFileExist :: FilePath -> IO Bool
on doesFileExist(strPath)
set ca to current application
set oPath to (ca's NSString's stringWithString:strPath)'s ¬
stringByStandardizingPath
set {bln, int} to (ca's NSFileManager's defaultManager's ¬
fileExistsAtPath:oPath isDirectory:(reference))
bln and (int ≠ 1)
end doesFileExist
 
 
-- filteredLines :: String -> NString -> [a]
on filteredLines(predicateString, s)
-- A list of lines filtered by an NSPredicate string
set ca to current application
set predicate to ca's NSPredicate's predicateWithFormat:predicateString
set array to ca's NSArray's ¬
arrayWithArray:(s's componentsSeparatedByString:(linefeed))
(array's filteredArrayUsingPredicate:(predicate)) as list
end filteredLines
 
 
-- readFile :: FilePath -> IO NSString
on readFile(strPath)
set ca to current application
set e to reference
set {s, e} to (ca's NSString's ¬
stringWithContentsOfFile:((ca's NSString's ¬
stringWithString:strPath)'s ¬
stringByStandardizingPath) ¬
encoding:(ca's NSUTF8StringEncoding) |error|:(e))
if missing value is e then
s
else
(localizedDescription of e) as string
end if
end readFile
 
 
-- scriptFolder :: () -> IO FilePath
on scriptFolder()
-- The path of the folder containing this script
try
tell application "Finder" to ¬
POSIX path of ((container of (path to me)) as alias)
on error
display dialog "Script file must be saved"
end try
end scriptFolder
 
 
------------------------- GENERIC ------------------------
 
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
-- Constructor for a pair of values,
-- possibly of two different types.
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
 
------------------------- GENERIC --------------------------
 
-- all :: (a -> Bool) -> [a] -> Bool
Line 274 ⟶ 500:
acc
end concat
 
 
-- eq (==) :: Eq a => a -> a -> Bool
on eq(a, b)
a = b
end eq
 
 
Line 285 ⟶ 517:
if |λ|(v, i, xs) then set end of lst to v
end repeat
if {text, string} contains class of xs then
return lst
lst as text
else
lst
end if
end tell
end filter
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
 
-- group :: Eq a => [a] -> [[a]]
on group(xs)
script eq
on |λ|(a, b)
a = b
end |λ|
end script
groupBy(eq, xs)
end group
 
 
-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
on groupBy(f, xs)
-- Typical usage: groupBy(on(eq, f), xs)
set mf to mReturn(f)
script enGroup
on |λ|(a, x)
if length of (active of a) > 0 then
set h to item 1 of active of a
else
set h to missing value
end if
if h is not missing value and mf's |λ|(h, x) then
{active:(active of a) & {x}, sofar:sofar of a}
else
{active:{x}, sofar:(sofar of a) & {active of a}}
end if
end |λ|
end script
if length of xs > 0 then
set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, rest of xs)
if length of (active of dct) > 0 then
sofar of dct & {active of dct}
else
sofar of dct
end if
else
{}
end if
end groupBy
 
 
-- identity :: a -> a
on identity(x)
-- The argument unchanged.
x
end identity
 
 
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
 
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
 
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
-- lifted into 1st class script wrapper.
if script is class of f then
f
Line 303 ⟶ 627:
 
 
-- readFilemap :: FilePath(a -> IOb) String-> [a] -> [b]
on readFilemap(strPathf, xs)
set-- caThe tolist currentobtained applicationby applying f
set e-- to referenceeach element of xs.
tell mReturn(f)
set {s, e} to (ca's NSString's ¬
set lng to length of xs
stringWithContentsOfFile:((ca's NSString's ¬
set lst to stringWithString:strPath)'s ¬{}
repeat with i from stringByStandardizingPath)1 ¬to lng
encoding:(ca'sset NSUTF8StringEncoding)end of lst to |errorλ|:(e)item i of xs, i, xs)
if missing value is eend thenrepeat
sreturn as stringlst
elseend tell
end map
(localizedDescription of e) as string
 
end if
 
end readFile
-- nub :: [a] -> [a]
on nub(xs)
nubBy(eq, xs)
end nub
 
 
-- nubBy :: (a -> a -> Bool) -> [a] -> [a]
on nubBy(f, xs)
set g to mReturn(f)'s |λ|
script notEq
property fEq : g
on |λ|(a)
script
on |λ|(b)
not fEq(a, b)
end |λ|
end script
end |λ|
end script
script go
on |λ|(xs)
if (length of xs) > 1 then
set x to item 1 of xs
{x} & go's |λ|(filter(notEq's |λ|(x), items 2 thru -1 of xs))
else
xs
end if
end |λ|
end script
go's |λ|(xs)
end nubBy
 
 
 
Line 327 ⟶ 686:
 
 
-- toLowertake :: StringInt -> String[a] -> [a]
-- take :: Int -> String -> String
on toLower(str)
on take(n, xs)
-- String in lower case.
setif ca0 to< currentn applicationthen
items 1 thru min(n, length of xs) of xs
((ca's NSString's stringWithString:(str))'s ¬
else
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
{}
end toLower
end if
end take
 
 
Line 345 ⟶ 706:
set my text item delimiters to dlm
s
end unlines</lang>
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys))
if 1 > lng then return {}
set xs_ to take(lng, xs) -- Allow for non-finite
set ys_ to take(lng, ys) -- generators like cycle etc
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith</syntaxhighlight>
{{Out}}
<pre>17 matches:
 
eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">letters := ["N", "D", "E", "O", "K", "G", "E", "L", "W"]
 
FileRead, wList, % A_Desktop "\unixdict.txt"
result := ""
for word in Word_wheel(wList, letters, 3)
result .= word "`n"
MsgBox % result
return
 
Word_wheel(wList, letters, minL){
oRes := []
for i, w in StrSplit(wList, "`n", "`r")
{
if (StrLen(w) < minL)
continue
word := w
for i, l in letters
w := StrReplace(w, l,,, 1)
if InStr(word, letters[5]) && !StrLen(w)
oRes[word] := true
}
return oRes
}</syntaxhighlight>
{{out}}
<pre>eke
elk
k
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
ok
week
wok
woke</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f WORD_WHEEL.AWK letters unixdict.txt
# the required letter must be first
#
# example: GAWK -f WORD_WHEEL.AWK Kndeogelw unixdict.txt
#
BEGIN {
letters = tolower(ARGV[1])
required = substr(letters,1,1)
size = 3
ARGV[1] = ""
}
{ word = tolower($0)
leng_word = length(word)
if (word ~ required && leng_word >= size) {
hits = 0
for (i=1; i<=leng_word; i++) {
if (letters ~ substr(word,i,1)) {
hits++
}
}
if (leng_word == hits && hits >= size) {
for (i=1; i<=leng_word; i++) {
c = substr(word,i,1)
if (gsub(c,"&",word) > gsub(c,"&",letters)) {
next
}
}
words++
printf("%s ",word)
}
}
}
END {
printf("\nletters: %s, '%s' required, %d words >= %d characters\n",letters,required,words,size)
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
eke elk keel keen keg ken keno knee kneel knew know knowledge kong leek week wok woke
letters: kndeogelw, 'k' required, 17 words >= 3 characters
</pre>
 
=={{header|BASIC}}==
<syntaxhighlight lang="basic">10 DEFINT A-Z
20 DATA "ndeokgelw","unixdict.txt"
30 READ WH$, F$
40 OPEN "I",1,F$
50 IF EOF(1) THEN CLOSE 1: END
60 C$ = WH$
70 LINE INPUT #1, W$
80 FOR I=1 TO LEN(W$)
90 FOR J=1 TO LEN(C$)
100 IF MID$(W$,I,1)=MID$(C$,J,1) THEN MID$(C$,J,1)="@": GOTO 120
110 NEXT J: GOTO 50
120 NEXT I
130 IF MID$(C$,(LEN(C$)+1)/2,1)<>"@" GOTO 50
140 C=0: FOR I=1 TO LEN(C$): C=C-(MID$(C$,I,1)="@"): NEXT
150 IF C>=3 THEN PRINT W$,
160 GOTO 50</syntaxhighlight>
{{out}}
<pre>eke elk keel keen keg
ken keno knee kneel knew
know knowledge kong leek week
wok woke
</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
// Read word from selected input
let readword(v) = valof
$( let ch = ?
v%0 := 0
$( ch := rdch()
if ch = endstreamch then resultis false
if ch = '*N' then resultis true
v%0 := v%0 + 1
v%(v%0) := ch
$) repeat
$)
 
// Test word against wheel
let match(wheel, word) = valof
$( let wcopy = vec 2+9/BYTESPERWORD
for i = 0 to wheel%0 do wcopy%i := wheel%i
for i = 1 to word%0 do
$( let idx = ?
test valof
$( for j = 1 to wcopy%0 do
if word%i = wcopy%j then
$( idx := j
resultis true
$)
resultis false
$) then wcopy%idx := 0 // we've used this letter
else resultis false // word cannot be made
$)
resultis
wcopy%((wcopy%0+1)/2)=0 & // middle letter must be used
3 <= valof // at least 3 letters must be used
$( let count = 0
for i = 1 to wcopy%0 do
if wcopy%i=0 then count := count + 1
resultis count
$)
$)
 
// Test unixdict.txt against ndeokgelw
let start() be
$( let word = vec 2+64/BYTESPERWORD
let file = findinput("unixdict.txt")
let wheel = "ndeokgelw"
selectinput(file)
while readword(word) do
if match(wheel, word) do
writef("%S*N", word)
endread()
$)</syntaxhighlight>
{{out}}
<pre>eke
elk
Line 366 ⟶ 931:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
 
Line 413 ⟶ 978:
fclose(in);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 439 ⟶ 1,004:
{{libheader|Boost}}
The puzzle parameters can be set with command line options. The default values are as per the task description.
<langsyntaxhighlight lang="cpp">#include <array>
#include <iostream>
#include <fstream>
Line 633 ⟶ 1,198:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 648 ⟶ 1,213:
claremont with central letter a
spearmint with central letter a
</pre>
 
===Without external libraries===
<syntaxhighlight lang="c++">
#include <algorithm>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
 
int main() {
const std::string word_wheel_letters = "ndeokgelw";
const std::string middle_letter = word_wheel_letters.substr(4, 1);
 
std::vector<std::string> words;
std::fstream file_stream;
file_stream.open("../unixdict.txt");
std::string word;
while ( file_stream >> word ) {
words.emplace_back(word);
}
 
std::vector<std::string> correct_words;
for ( const std::string& word : words ) {
if ( 3 <= word.length() && word.length() <= 9 &&
word.find(middle_letter) != std::string::npos &&
word.find_first_not_of(word_wheel_letters) == std::string::npos ) {
 
correct_words.emplace_back(word);
}
}
 
for ( const std::string& correct_word : correct_words ) {
std::cout << correct_word << std::endl;
}
 
int32_t max_words_found = 0;
std::vector<std::string> best_words9;
std::vector<char> best_central_letters;
std::vector<std::string> words9;
for ( const std::string& word : words ) {
if ( word.length() == 9 ) {
words9.emplace_back(word);
}
}
 
for ( const std::string& word9 : words9 ) {
std::vector<char> distinct_letters(word9.begin(), word9.end());
std::sort(distinct_letters.begin(), distinct_letters.end());
distinct_letters.erase(std::unique(distinct_letters.begin(), distinct_letters.end()), distinct_letters.end());
 
for ( const char& letter : distinct_letters ) {
int32_t words_found = 0;
for ( const std::string& word : words ) {
if ( word.length() >= 3 && word.find(letter) != std::string::npos ) {
std::vector<char> letters = distinct_letters;
bool valid_word = true;
for ( const char& ch : word ) {
std::vector<char>::iterator iter = std::find(letters.begin(), letters.end(), ch);
int32_t index = ( iter == letters.end() ) ? -1 : std::distance(letters.begin(), iter);
if ( index == -1 ) {
valid_word = false;
break;
}
letters.erase(letters.begin() + index);
}
if ( valid_word ) {
words_found++;
}
}
}
 
if ( words_found > max_words_found ) {
max_words_found = words_found;
best_words9.clear();
best_words9.emplace_back(word9);
best_central_letters.clear();
best_central_letters.emplace_back(letter);
} else if ( words_found == max_words_found ) {
best_words9.emplace_back(word9);
best_central_letters.emplace_back(letter);
}
}
}
 
std::cout << "\n" << "Most words found = " << max_words_found << std::endl;
std::cout << "The nine letter words producing this total are:" << std::endl;
for ( uint64_t i = 0; i < best_words9.size(); ++i ) {
std::cout << best_words9[i] << " with central letter '" << best_central_letters[i] << "'" << std::endl;
}
}
</syntaxhighlight>
<pre>
eke
elk
keel
keen
keg
kellogg
ken
kennel
keno
knee
kneel
knell
knew
knoll
know
knowledge
known
kong
kowloon
leek
look
nook
onlook
week
weekend
wok
woke
 
Most words found = 215
The nine letter words producing this total are:
claremont with central letter 'a'
spearmint with central letter 'a'
</pre>
 
Line 654 ⟶ 1,345:
{{libheader| System.Classes}}
{{Trans|Wren}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Word_wheel;
 
Line 707 ⟶ 1,398:
end.
 
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Word Wheel: Nigel Galloway. May 25th., 2021
let fG k n g=g|>Seq.exists(fun(n,_)->n=k) && g|>Seq.forall(fun(k,g)->Map.containsKey k n && g<=n.[k])
let wW n g=let fG=fG(Seq.item 4 g)(g|>Seq.countBy id|>Map.ofSeq) in seq{use n=System.IO.File.OpenText(n) in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(fun n->2<(Seq.length n)&&(Seq.countBy id>>fG)n)
wW "unixdict.txt" "ndeokgelw"|>Seq.iter(printfn "%s")
</syntaxhighlight>
{{out}}
<pre>
eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
</pre>
=={{header|Factor}}==
{{works with|Factor|0.99 2020-07-03}}
<langsyntaxhighlight lang="factor">USING: assocs io.encodings.ascii io.files kernel math
math.statistics prettyprint sequences sorting ;
 
Line 731 ⟶ 1,449:
[ words ] keepd [ can-make? ] curry filter ;
 
"ndeokgelw" "unixdict.txt" solve [ length ] sort-with .</langsyntaxhighlight>
{{out}}
<pre style="height:20ex">
Line 753 ⟶ 1,471:
"knowledge"
}
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
#include "file.bi"
 
Function String_Split(s_in As String,chars As String,result() As String) As Long
Dim As Long ctr,ctr2,k,n,LC=Len(chars)
Dim As boolean tally(Len(s_in))
#macro check_instring()
n=0
While n<Lc
If chars[n]=s_in[k] Then
tally(k)=true
If (ctr2-1) Then ctr+=1
ctr2=0
Exit While
End If
n+=1
Wend
#endmacro
#macro split()
If tally(k) Then
If (ctr2-1) Then ctr+=1:result(ctr)=Mid(s_in,k+2-ctr2,ctr2-1)
ctr2=0
End If
#endmacro
'================== LOOP TWICE =======================
For k =0 To Len(s_in)-1
ctr2+=1:check_instring()
Next k
if ctr=0 then
if len(s_in) andalso instr(chars,chr(s_in[0])) then ctr=1':beep
end if
If ctr Then Redim result(1 To ctr): ctr=0:ctr2=0 Else Return 0
For k =0 To Len(s_in)-1
ctr2+=1:split()
Next k
'===================== Last one ========================
If ctr2>0 Then
Redim Preserve result(1 To ctr+1)
result(ctr+1)=Mid(s_in,k+1-ctr2,ctr2)
End If
Return Ubound(result)
End Function
 
Function loadfile(file As String) As String
If Fileexists(file)=0 Then Print file;" not found":Sleep:End
Dim As Long f=Freefile
Open file For Binary Access Read As #f
Dim As String text
If Lof(f) > 0 Then
text = String(Lof(f), 0)
Get #f, , text
End If
Close #f
Return text
End Function
 
Function tally(SomeString As String,PartString As String) As Long
Dim As Long LenP=Len(PartString),count
Dim As Long position=Instr(SomeString,PartString)
If position=0 Then Return 0
While position>0
count+=1
position=Instr(position+LenP,SomeString,PartString)
Wend
Return count
End Function
 
Sub show(g As String,file As String,byref matches as long,minsize as long,mustdo as string)
Redim As String s()
Var L=lcase(loadfile(file))
g=lcase(g)
string_split(L,Chr(10),s())
For m As Long=minsize To len(g)
For n As Long=Lbound(s) To Ubound(s)
If Len(s(n))=m Then
For k As Long=0 To m-1
If Instr(g,Chr(s(n)[k]))=0 Then Goto lbl
Next k
If Instr(s(n),mustdo) Then
For j As Long=0 To Len(s(n))-1
If tally(s(n),Chr(s(n)[j]))>tally(g,Chr(s(n)[j])) Then Goto lbl
Next j
Print s(n)
matches+=1
End If
End If
lbl:
Next n
Next m
End Sub
 
dim as long matches
dim as double t=timer
show("ndeokgelw","unixdict.txt",matches,3,"k")
print
print "Overall time taken ";timer-t;" seconds"
print matches;" matches"
Sleep
</syntaxhighlight>
{{out}}
<pre>
eke
elk
keg
ken
wok
keel
keen
keno
knee
knew
know
kong
leek
week
woke
kneel
knowledge
 
Overall time taken 0.02187220007181168 seconds
17 matches
</pre>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
 
include "NSLog.incl"
 
local fn CountCharacterInString( string as CFStringRef, character as CFStringRef ) as NSUInteger
end fn = len(string) - len( fn StringByReplacingOccurrencesOfString( string, character, @"" ) )
 
local fn IsLegal( wordStr as CFStringRef ) as BOOL
NSUInteger i, count = len( wordStr )
CFStringRef letters = @"ndeokgelw"
if count < 3 || fn StringContainsString( wordStr, @"k" ) == NO then exit fn = NO
for i = 0 to count - 1
if fn CountCharacterInString( letters, mid( wordStr, i, 1 ) ) < fn CountCharacterInString( wordStr, mid( wordStr, i, 1 ) )
exit fn = NO
end if
next
end fn = YES
 
local fn ArrayOfDictionaryWords as CFArrayRef
CFURLRef url = fn URLWithString( @"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" )
CFStringRef string = lcase( fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL ) )
CFArrayRef wordArr = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet )
end fn = wordArr
 
void local fn FindWheelWords
CFArrayRef wordArr = fn ArrayOfDictionaryWords
CFStringRef wordStr
CFMutableStringRef mutStr = fn MutableStringNew
for wordStr in wordArr
if fn IsLegal( wordStr ) then MutableStringAppendFormat( mutStr, fn StringWithFormat( @"%@\n", wordStr ) )
next
NSLog( @"%@", mutStr )
end fn
 
fn FindWheelWords
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
</pre>
 
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 870 ⟶ 1,778:
fmt.Println(mostWords9[i], "with central letter", string(mostLetters[i]))
}
}</langsyntaxhighlight>
 
{{out}}
Line 900 ⟶ 1,808:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import SystemData.IOChar (readFiletoLower)
import Data.Char (toLower)
import Data.List (sort)
import System.IO (readFile)
 
------------------------ WORD WHEEL ----------------------
 
gridWords :: [String] -> [String] -> [String]
gridWords grid =
filter
filter (((&&) . (2 <) . length) <*> (((&&) . elem mid) <*> wheelFit wheel))
( ((&&) . (2 <) . length)
<*> (((&&) . elem mid) <*> wheelFit wheel)
)
where
cs = toLower <$> concat grid
Line 913 ⟶ 1,826:
 
wheelFit :: String -> String -> Bool
wheelFit wheel word = go wheel (. sort word)
where
go _ [] = True
go [] _ = False
go (w : ws) ccs@(c : cs)
| w == c = go ws cs
| otherwise = go ws ccs
 
--------------------------- TEST -------------------------
main :: IO ()
main = do
s <- readFile "unixdict.txt"
>>= ( mapM_ putStrLn
mapM_ putStrLn $ gridWords ["NDE", "OKG", "ELW"] (lines s)</lang>
. gridWords ["NDE", "OKG", "ELW"]
. lines
)</syntaxhighlight>
{{Out}}
<pre>eke
Line 943 ⟶ 1,860:
wok
woke</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j">require'stats'
wwhe=: {{
ref=. /:~each words=. cutLF tolower fread 'unixdict.txt'
y=.,y assert. 9=#y
ch0=. 4{y
chn=. (<<<4){y
r=. ''
for_i.2}.i.9 do.
target=. <"1 ~./:~"1 ch0,.(i comb 8){chn
;:inv r=. r,words #~ ref e. target
end.
}}</syntaxhighlight>
 
Task example:<syntaxhighlight lang="j"> wwhe'ndeokgelw'
eke elk keg ken wok keel keen keno knee knew know kong leek week woke kneel knowledge</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
 
public final class WordWheelExtended {
 
public static void main(String[] args) throws IOException {
String wordWheel = "N D E"
+ "O K G"
+ "E L W";
String url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt";
InputStream stream = URI.create(url).toURL().openStream();
BufferedReader reader = new BufferedReader( new InputStreamReader(stream) );
List<String> words = reader.lines().toList();
reader.close();
String allLetters = wordWheel.toLowerCase().replace(" ", "");
String middleLetter = allLetters.substring(4, 5);
Predicate<String> firstFilter = word -> word.contains(middleLetter) && 2 < word.length() && word.length() < 10;
Predicate<String> secondFilter = word -> word.chars().allMatch( ch -> allLetters.indexOf(ch) >= 0 );
Predicate<String> correctWords = firstFilter.and(secondFilter);
words.stream().filter(correctWords).forEach(System.out::println);
int maxWordsFound = 0;
List<String> bestWords9 = new ArrayList<String>();
List<Character> bestCentralLetters = new ArrayList<Character>();
List<String> words9 = words.stream().filter( word -> word.length() == 9 ).toList();
 
for ( String word9 : words9 ) {
List<Character> distinctLetters = word9.chars().mapToObj( i -> (char) i ).distinct().toList();
for ( char letter : distinctLetters ) {
int wordsFound = 0;
for ( String word : words ) {
if ( word.length() >= 3 && word.indexOf(letter) >= 0 ) {
List<Character> letters = new ArrayList<Character>(distinctLetters);
boolean validWord = true;
for ( char ch : word.toCharArray() ) {
final int index = letters.indexOf(ch);
if ( index == -1 ) {
validWord = false;
break;
}
letters.remove(index);
}
if ( validWord ) {
wordsFound += 1;
}
}
}
if ( wordsFound > maxWordsFound ) {
maxWordsFound = wordsFound;
bestWords9.clear();
bestWords9.add(word9);
bestCentralLetters.clear();
bestCentralLetters.add(letter);
} else if ( wordsFound == maxWordsFound ) {
bestWords9.add(word9);
bestCentralLetters.add(letter);
}
}
}
System.out.println(System.lineSeparator() + "Most words found = " + maxWordsFound);
System.out.println("The nine letter words producing this total are:");
for ( int i = 0; i < bestWords9.size(); i++ ) {
System.out.println(bestWords9.get(i) + " with central letter '" + bestCentralLetters.get(i) + "'");
}
}
 
}
</syntaxhighlight>
<pre>
eke
elk
keel
keen
keg
kellogg
ken
kennel
keno
knee
kneel
knell
knew
knoll
know
knowledge
known
kong
kowloon
leek
look
nook
onlook
week
weekend
wok
woke
 
Most words found = 215
The nine letter words producing this total are:
claremont with central letter 'a'
spearmint with central letter 'a'
</pre>
 
=={{header|JavaScript}}==
A version using local access to the dictionary, through the macOS JavaScript for Automation API.
{{Works with|JXA}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'"use strict'";
 
// ------------------- WORD WHEEL --------------------
// main :: IO ()
const main = () =>
console.log(unlines(
gridWords(['NDE', 'OKG', 'ELW'])(
lines(readFile('unixdict.txt'))
)
));
 
// gridWords :: [String] -> [String] -> [String]
Line 962 ⟶ 2,007:
lexemes => {
const
wheel = sort(toLower(concat(grid.join(""))),
wSet = new Set(wheel),
mid = wheel[4];
 
return lexemes.filter(w => {
const cs = chars([...w)];
 
return 2 < cs.length && cs.every(
c => wSet.has(c)
) && elemcs.some(x => mid)(cs === x) && (
wheelFit(wheel, cs)
);
});
};
 
 
// wheelFit :: [Char] -> [Char] -> Bool
Line 985 ⟶ 2,033:
go(ws.slice(1), cs.slice(1))
) : go(ws.slice(1), cs);
 
return go(wheel, sort(word));
};
 
// ----------------- GENERIC FUNCTIONS -----------------
 
// ---------------------- TEST -----------------------
// chars :: String -> [Char]
const// charsmain =:: sIO =>()
const main = s.split(''); =>
gridWords(["NDE", "OKG", "ELW"])(
lines(readFile("unixdict.txt"))
)
.join("\n");
 
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs => (
ys => 0 < ys.length ? (
ys.every(Array.isArray) ? (
[]
) : ''
).concat(...ys) : ys
)(list(xs));
 
// ---------------- GENERIC FUNCTIONS ----------------
// elem :: Eq a => a -> [a] -> Bool
const elem = x =>
// True if xs contains an instance of x.
xs => xs.some(y => x === y);
 
// lines :: String -> [String]
const lines = s =>
// A list of strings derived from a single string
// newline-which is delimited stringby \n or by \r\n or \r.
0 < Boolean(s.length) ? (
s.split(/[\r\n]|\n|\r/u)
) : [];
 
// list :: StringOrArrayLike b => b -> [a]
const list = xs =>
// xs itself, if it is an Array,
// or an Array derived from xs.
Array.isArray(xs) ? (
xs
) : Array.from(xs || []);
 
// readFile :: FilePath -> IO String
const readFile = fp => {
// The contents of a text file at the
// pathgiven file fppath.
const
e = $(),
Line 1,037 ⟶ 2,070:
e
);
 
return ObjC.unwrap(
ns.isNil() ? (
Line 1,043 ⟶ 2,077:
);
};
 
 
// sort :: Ord a => [a] -> [a]
const sort = xs => list(xs).slice()
Array.sortfrom((a, bxs) => a < b ? -1 : .sort(a > b ? 1 : 0));
 
 
// toLower :: String -> String
Line 1,053 ⟶ 2,089:
s.toLocaleLowerCase();
 
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
 
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>eke
Line 1,080 ⟶ 2,111:
wok
woke</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq, and with fq''' provided `keys_unsorted` is replaced `by keys`
<syntaxhighlight lang=jq>
# remove words with fewer than 3 or more than 9 letters
def words: inputs | select(length | . > 2 and . < 10);
 
# The central letter in `puzzle` should be the central letter of the word wheel
def solve(puzzle):
def chars: explode[] | [.] | implode;
def profile(s): reduce s as $c (null; .[$c] += 1);
profile(puzzle[]) as $profile
| def ok($prof): all($prof|keys_unsorted[]; . as $k | $prof[$k] <= $profile[$k]);
(puzzle | .[ (length - 1) / 2]) as $central
| words
| select(index($central) and ok( profile(chars) )) ;
 
"The solutions to the puzzle are as follows:",
solve( ["d", "e", "e", "g", "k", "l", "n", "o", "w"] )
</syntaxhighlight>
'''Invocation''': < unixdict.txt jq -Rnr -f word-wheel.jq
{{output}}
<pre>
The solutions to the puzzle are as follows:
eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Combinatorics
 
const tfile = download("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
Line 1,103 ⟶ 2,177:
 
println(wordwheel("ndeokgelw", "k"))
</langsyntaxhighlight>{{out}}
<pre>
["ken", "keg", "eke", "elk", "wok", "keno", "knee", "keen", "knew", "kong", "know", "woke", "keel", "leek", "week", "kneel", "knowledge"]
</pre>
===Faster but less general version===
<langsyntaxhighlight lang="julia">const tfile = download("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
const wordarraylist = [[string(c) for c in w] for w in split(read(tfile, String), r"\s+")]
 
Line 1,119 ⟶ 2,193:
 
println(wordwheel2("ndeokgelw", "k"))
</langsyntaxhighlight>{{out}}
<pre>
["eke", "elk", "keel", "keen", "keg", "ken", "keno", "knee", "kneel", "knew", "know", "knowledge", "kong", "leek", "week", "wok", "woke"]
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">LetterCounter = {
new = function(self, word)
local t = { word=word, letters={} }
for ch in word:gmatch(".") do t.letters[ch] = (t.letters[ch] or 0) + 1 end
return setmetatable(t, self)
end,
contains = function(self, other)
for k,v in pairs(other.letters) do
if (self.letters[k] or 0) < v then return false end
end
return true
end
}
LetterCounter.__index = LetterCounter
 
grid = "ndeokgelw"
midl = grid:sub(5,5)
ltrs = LetterCounter:new(grid)
file = io.open("unixdict.txt", "r")
for word in file:lines() do
if #word >= 3 and word:find(midl) and ltrs:contains(LetterCounter:new(word)) then
print(word)
end
end</syntaxhighlight>
{{out}}
<pre>eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke</pre>
 
===No metatables, simple===
<syntaxhighlight lang="lua">-- Algorithm is from Ruby implementation.
local wheel = arg[1] or 'ndeoKgelw' -- wheel is 1st argument
wheel = wheel:lower()
local middle = wheel:sub(5, 5)
assert(#middle == 1)
for line in io.lines() do -- get dictionary from standard input
local word = line:lower()
if word:find(middle) and #word >= 3 then
for wheel_char in wheel:gmatch('.') do
word = word:gsub(wheel_char, '', 1)
end -- for
if #word == 0 then io.write(line:lower() .. ' ') end
end -- if
end -- for
print ''
</syntaxhighlight>
 
Shell command
 
<pre>$ < unixdict.txt lua ./word-wheel.lua</pre>
{{out}}
<pre>
eke elk keel keen keg ken keno knee kneel knew know knowledge kong leek week wok woke
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[possible]
possible[letters_List][word_String] := Module[{c1, c2, m},
c1 = Counts[Characters@word];
c2 = Counts[letters];
m = Merge[{c1, c2}, Identity];
Length[Select[Select[m, Length /* GreaterThan[1]], Apply[Greater]]] == 0
]
chars = Characters@"ndeokgelw";
words = Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "String"];
words = StringSplit[ToLowerCase[words], "\n"];
words //= Select[StringLength /* GreaterEqualThan[3]];
words //= Select[StringContainsQ["k"]];
words //= Select[StringMatchQ[Repeated[Alternatives @@ chars]]];
words //= Select[possible[chars]];
words</syntaxhighlight>
{{out}}
<pre>{eke,elk,keel,keen,keg,ken,keno,knee,kneel,knew,know,knowledge,kong,leek,week,wok,woke}</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import strutils, sugar, tables
 
const Grid = """N D E
O K G
E L W"""
 
let letters = Grid.toLowerAscii.splitWhitespace.join()
 
let words = collect(newSeq):
for word in "unixdict.txt".lines:
if word.len in 3..9:
word
 
let midLetter = letters[4]
 
let gridCount = letters.toCountTable
for word in words:
block checkWord:
if midLetter in word:
for ch, count in word.toCountTable.pairs:
if count > gridCount[ch]:
break checkWord
echo word</syntaxhighlight>
 
{{out}}
<pre>eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke</pre>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
<syntaxhighlight lang="pascal">
program WordWheel;
 
{$mode objfpc}{$H+}
 
uses
SysUtils;
 
const
WheelSize = 9;
MinLength = 3;
WordListFN = 'unixdict.txt';
 
procedure search(Wheel : string);
var
Allowed, Required, Available, w : string;
Len, i, p : integer;
WordFile : TextFile;
Match : boolean;
begin
AssignFile(WordFile, WordListFN);
try
Reset(WordFile);
except
writeln('Could not open dictionary file: ' + WordListFN);
exit;
end;
Allowed := LowerCase(Wheel);
Required := copy(Allowed, 5, 1); { central letter is required }
while not eof(WordFile) do
begin
readln(WordFile, w);
Len := length(w);
if (Len < MinLength) or (Len > WheelSize) then continue;
if pos(Required, w) = 0 then continue;
Available := Allowed;
Match := True;
for i := 1 to Len do
begin
p := pos(w[i], Available);
if p > 0 then
{ prevent re-use of letter }
delete(Available, p, 1)
else
begin
Match := False;
break;
end;
end;
if Match then
writeln(w);
end;
CloseFile(WordFile);
end;
 
{ exercise the procedure }
begin
search('NDE' + 'OKG' + 'ELW');
end.
</syntaxhighlight>
{{out}}
<pre>
eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
</pre>
 
Line 1,127 ⟶ 2,417:
UPDATED: this version builds a single regex that will select all valid words
straight from the file string.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Word_wheel
Line 1,147 ⟶ 2,437:
my @words = $file =~ /$valid/g;
 
print @words . " words for\n$_\n@words\n" =~ s/.{60}\K /\n/gr;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,160 ⟶ 2,450:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>requires("0.8.2") -- (fixed some glitches in join_by())
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
constant wheel = "ndeokgelw",
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.1"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (fixed another glitch in unique())</span>
musthave = wheel[5]
<span style="color: #008080;">constant</span> <span style="color: #000000;">wheel</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"ndeokgelw"</span><span style="color: #0000FF;">,</span>
sequence words = {},
<span style="color: #000000;">musthave</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">wheel</span><span style="color: #0000FF;">[</span><span style="color: #000000;">5</span><span style="color: #0000FF;">]</span>
word9 = {} -- (for the optional extra part)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">unix_dict</span><span style="color: #0000FF;">(),</span>
integer fn = open(join_path({"demo","unixdict.txt"}),"r")
<span style="color: #000000;">word9</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> <span style="color: #000080;font-style:italic;">-- (for the optional extra part)</span>
if fn=-1 then crash("unixdict.txt not found") end if
<span style="color: #004080;">integer</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
while 1 do
<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>
object word = lower(trim(gets(fn)))
<span style="color: #004080;">string</span> <span style="color: #000000;">word</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">lower</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>
if atom(word) then exit end if -- eof
<span style="color: #004080;">integer</span> <span style="color: #000000;">lw</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>
integer lw = length(word)
<span style="color: #008080;">if</span> <span style="color: #000000;">lw</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">3</span> <span style="color: #008080;">then</span>
if lw>=3 then
<span style="color: #008080;">if</span> <span style="color: #000000;">lw</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">9</span> <span style="color: #008080;">then</span>
if lw<=9 then
<span style="color: #000000;">word9</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span>
word9 = append(word9,word)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">musthave</span><span style="color: #0000FF;">,</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
if find(musthave,word) then
<span style="color: #004080;">string</span> <span style="color: #000000;">remaining</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">wheel</span>
string remaining = wheel
<span style="color: #008080;">while</span> <span style="color: #000000;">lw</span> <span style="color: #008080;">do</span>
while lw do
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">[</span><span style="color: #000000;">lw</span><span style="color: #0000FF;">],</span><span style="color: #000000;">remaining</span><span style="color: #0000FF;">)</span>
integer k = find(word[lw],remaining)
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if k=0 then exit end if
<span style="color: #000000;">remaining</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'\0'</span> <span style="color: #000080;font-style:italic;">-- (prevent re-use)</span>
remaining[k] = '\0' -- (prevent re-use)
<span style="color: #000000;">lw</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
lw -= 1
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">lw</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
if lw=0 then words = append(words,word) end if
<span style="color: #000000;">found</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end if
<span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">found</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">word</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
close(fn)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
string jbw = join_by(words,1,9," ","\n ")
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1, "The following %d words were found:\n %s\n",{length(words),jbw})
<span style="color: #004080;">string</span> <span style="color: #000000;">jbw</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">found</span><span style="color: #0000FF;">],</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n "</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 following %d words were found:\n %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">found</span><span style="color: #0000FF;">,</span><span style="color: #000000;">jbw</span><span style="color: #0000FF;">})</span>
-- optional extra
integer mostFound = 0
<span style="color: #000080;font-style:italic;">-- optional extra</span>
sequence mostWheels = {},
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (works but no progress/blank screen for 2min 20s)
mustHaves = {}
-- (the "working" won't show, even w/o the JS check)</span>
for i=1 to length(word9) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">mostFound</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
string try_wheel = word9[i]
<span style="color: #004080;">sequence</span> <span style="color: #000000;">mostWheels</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span>
if length(try_wheel)=9 then
<span style="color: #000000;">mustHaves</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
string musthaves = unique(try_wheel)
<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;">word9</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
for j=1 to length(musthaves) do
<span style="color: #004080;">string</span> <span style="color: #000000;">try_wheel</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">word9</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
integer found = 0
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">try_wheel</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">9</span> <span style="color: #008080;">then</span>
for k=1 to length(word9) do
<span style="color: #004080;">string</span> <span style="color: #000000;">musthaves</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">unique</span><span style="color: #0000FF;">(</span><span style="color: #000000;">try_wheel</span><span style="color: #0000FF;">)</span>
string word = word9[k]
<span style="color: #008080;">for</span> <span style="color: #000000;">j</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;">musthaves</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if find(musthaves[j],word) then
<span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
string rest = try_wheel
<span style="color: #008080;">for</span> <span style="color: #000000;">k</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;">word9</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
bool ok = true
<span style="color: #004080;">string</span> <span style="color: #000000;">word</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">word9</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span>
for c=1 to length(word) do
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">musthaves</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
integer ix = find(word[c],rest)
<span style="color: #004080;">string</span> <span style="color: #000000;">rest</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">try_wheel</span>
if ix=0 then
<span style="color: #004080;">bool</span> <span style="color: #000000;">ok</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
ok = false
<span style="color: #008080;">for</span> <span style="color: #000000;">c</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>
exit
<span style="color: #004080;">integer</span> <span style="color: #000000;">ix</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">],</span><span style="color: #000000;">rest</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">if</span> <span style="color: #000000;">ix</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
rest[ix] = '\0'
<span style="color: #000000;">ok</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
end for
found + <span style="color: ok#008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">rest</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ix</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'\0'</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"working (%s)\r",{try_wheel})
<span style="color: #000000;">found</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">ok</span>
if found>mostFound then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
mostFound = found
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
mostWheels = {try_wheel}
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (wouldn't show up anyway)</span>
mustHaves = {musthaves[j]}
<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;">"working (%s)\r"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">try_wheel</span><span style="color: #0000FF;">})</span>
elsif found==mostFound then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
mostWheels = append(mostWheels,try_wheel)
<span style="color: #008080;">if</span> <span style="color: #000000;">found</span><span style="color: #0000FF;">></span><span style="color: #000000;">mostFound</span> <span style="color: #008080;">then</span>
mustHaves = append(mustHaves,musthaves[j])
<span style="color: #000000;">mostFound</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">found</span>
end if
<span style="color: #000000;">mostWheels</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">try_wheel</span><span style="color: #0000FF;">}</span>
end for
<span style="color: #000000;">mustHaves</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">musthaves</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]}</span>
end if
<span style="color: #008080;">elsif</span> <span style="color: #000000;">found</span><span style="color: #0000FF;">==</span><span style="color: #000000;">mostFound</span> <span style="color: #008080;">then</span>
end for
<span style="color: #000000;">mostWheels</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mostWheels</span><span style="color: #0000FF;">,</span><span style="color: #000000;">try_wheel</span><span style="color: #0000FF;">)</span>
printf(1,"Most words found = %d\n",mostFound)
<span style="color: #000000;">mustHaves</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mustHaves</span><span style="color: #0000FF;">,</span><span style="color: #000000;">musthaves</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])</span>
printf(1,"Nine letter words producing this total:\n")
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
for i=1 to length(mostWheels) do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"%s with central letter '%c'\n",{mostWheels[i],mustHaves[i]})
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for</lang>
<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;">"Most words found = %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mostFound</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;">"Nine letter words producing this total:\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;">mostWheels</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 with central letter '%c'\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">mostWheels</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">mustHaves</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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
{{out}}
<small>(Only the first three lines are shown under pwa/p2js)</small>
<pre>
The following 17 words were found:
Line 1,244 ⟶ 2,543:
claremont with central letter 'a'
spearmint with central letter 'a'
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
MinLen = 3,
MaxLen = 9,
Chars = "ndeokgelw",
MustContain = 'k',
 
WordList = "unixdict.txt",
Words = read_file_lines(WordList),
Res = word_wheel(Chars,Words,MustContain,MinLen, MaxLen),
println(Res),
println(len=Res.len),
nl.
 
word_wheel(Chars,Words,MustContain,MinLen,MaxLen) = Res.reverse =>
Chars := to_lowercase(Chars),
D = make_hash(Chars),
Res = [],
foreach(W in Words, W.len >= MinLen, W.len <= MaxLen, membchk(MustContain,W))
WD = make_hash(W),
Check = true,
foreach(C in keys(WD), break(Check == false))
if not D.has_key(C) ; WD.get(C,0) > D.get(C,0) then
Check := false
end
end,
if Check == true then
Res := [W|Res]
end
end.
 
% Returns a map of the elements and their occurrences
% in the list L.
make_hash(L) = D =>
D = new_map(),
foreach(E in L)
D.put(E,D.get(E,0)+1)
end.</syntaxhighlight>
 
{{out}}
<pre>[eke,elk,keel,keen,keg,ken,keno,knee,kneel,knew,know,knowledge,kong,leek,week,wok,woke]
len = 17</pre>
 
'''Optimal word(s)''':
<syntaxhighlight lang="picat">main =>
WordList = "unixdict.txt",
MinLen = 3,
MaxLen = 9,
Words = [Word : Word in read_file_lines(WordList), Word.len >= MinLen, Word.len <= MaxLen],
TargetWords = [Word : Word in Words, Word.len == MaxLen],
MaxResWord = [],
MaxResLen = 0,
foreach(Word in TargetWords)
foreach(MustContain in Word.remove_dups)
Res = word_wheel(Word,Words,MustContain,MinLen, MaxLen),
Len = Res.len,
if Len >= MaxResLen then
if Len == MaxResLen then
MaxResWord := MaxResWord ++ [[word=Word,char=MustContain]]
else
MaxResWord := [[word=Word,char=MustContain]],
MaxResLen := Len
end
end
end
end,
println(maxLResen=MaxResLen),
println(maxWord=MaxResWord).</syntaxhighlight>
 
{{out}}
<pre>
maxReLen = 215
maxWord = [[word = claremont,char = a],[word = spearmint,char = a]]
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">Procedure.b check_word(word$)
Shared letters$
If Len(word$)<3 Or FindString(word$,"k")<1
ProcedureReturn #False
EndIf
For i=1 To Len(word$)
If CountString(letters$,Mid(word$,i,1))<CountString(word$,Mid(word$,i,1))
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
 
If ReadFile(0,"./Data/unixdict.txt")
txt$=LCase(ReadString(0,#PB_Ascii|#PB_File_IgnoreEOL))
CloseFile(0)
EndIf
 
If OpenConsole()
letters$="ndeokgelw"
wordcount=1
Repeat
buf$=StringField(txt$,wordcount,~"\n")
wordcount+1
If check_word(buf$)=#False
Continue
EndIf
PrintN(buf$) : r+1
Until buf$=""
PrintN("- Finished: "+Str(r)+" words found -")
Input()
EndIf
End</syntaxhighlight>
{{out}}
<pre>eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
- Finished: 17 words found -
</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import urllib.request
from collections import Counter
 
Line 1,273 ⟶ 2,702:
chars = ''.join(GRID.strip().lower().split())
found = solve(chars, dictionary=getwords())
print('\n'.join(found))</langsyntaxhighlight>
 
{{out}}
Line 1,296 ⟶ 2,725:
 
Or, using a local copy of the dictionary, and a recursive test of wheel fit:
<langsyntaxhighlight lang="python">'''Word wheel'''
 
from os.path import expanduser
Line 1,365 ⟶ 2,794:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>eke
Line 1,384 ⟶ 2,813:
wok
woke</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ over find swap found ] is has ( $ c --> b )
 
[ over find
split 1 split
swap drop join ] is remove ( $ c --> $ )
 
$ "rosetta/unixdict.txt" sharefile
drop nest$
[] swap
witheach
[ dup size 3 < iff drop done
dup size 9 > iff drop done
dup char k has not iff drop done
dup $ "ndeokgelw"
witheach remove
$ "" != iff drop done
nested join ]
30 wrap$</syntaxhighlight>
 
{{out}}
 
<pre>eke elk keel keen keg ken keno knee
kneel knew know knowledge kong leek week
wok woke
</pre>
 
=={{header|q}}==
<syntaxhighlight lang="q">ce:count each
lc:ce group@ / letter count
dict:"\n"vs .Q.hg "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
// dictionary of 3-9 letter words
d39:{x where(ce x)within 3 9}{x where all each x in .Q.a}dict
 
solve:{[grid;dict]
i:where(grid 4)in'dict;
dict i where all each 0<=(lc grid)-/:lc each dict i }[;d39]</syntaxhighlight>
<syntaxhighlight lang="q">q)`$solve "ndeokglew"
`eke`elk`keel`keen`keg`ken`keno`knee`kneel`knew`know`knowledge`kong`leek`week`wok`woke</syntaxhighlight>
A naive solution to the second question is simple
<syntaxhighlight lang="q">bust:{[dict]
grids:distinct raze(til 9)rotate\:/:dict where(ce dict)=9;
wc:(count solve@)each grids;
grids where wc=max wc }</syntaxhighlight>
but inefficient. Better:
<syntaxhighlight lang="q">best:{[dict]
dlc:lc each dict; / letter counts of dictionary words
ig:where(ce dict)=9; / find grids (9-letter words)
igw:where each(all'')0<=(dlc ig)-/:\:dlc; / find words composable from each grid (length ig)
grids:raze(til 9)rotate\:/:dict ig; / 9 permutations of each grid
iaz:(.Q.a)!where each .Q.a in'\:dict; / find words containing a, b, c etc
ml:4 rotate'dict ig; / mid letters for each grid
wc:ce raze igw inter/:'iaz ml; / word counts for grids
distinct grids where wc=max wc } / grids with most words</syntaxhighlight>
<syntaxhighlight lang="q">q)show w:best d39
"ntclaremo"
"tspearmin"
 
q)ce solve each w
215 215</syntaxhighlight>
Full discussion at [https://code.kx.com/q/learn/pb/word-wheel/ code.kx.com]
 
=={{header|Raku}}==
Line 1,393 ⟶ 2,885:
Using [https://modules.raku.org/search/?q=Terminal%3A%3ABoxer Terminal::Boxer] from the Raku ecosystem.
 
<syntaxhighlight lang="raku" perl6line>use Terminal::Boxer;
 
my %*SUB-MAIN-OPTS = :named-anywhere;
Line 1,415 ⟶ 2,907:
say "{sum %words.values».elems} words found";
 
printf "%d letters: %s\n", .key, .value.sort.join(', ') for %words.sort;</langsyntaxhighlight>
 
{{out}}
;Using defaults
 
<syntaxhighlight lang="text">raku word-wheel.raku</langsyntaxhighlight>
<pre>Using ./unixdict.txt, minimum 3 letters.
╭───┬───┬───╮
Line 1,438 ⟶ 2,930:
Using the much larger dictionary '''words.txt''' file from '''https://github.com/dwyl/english-words'''
 
<syntaxhighlight lang="text">raku word-wheel.raku --dict=./words.txt</langsyntaxhighlight>
 
<pre>Using ./words.txt, minimum 3 letters.
Line 1,488 ⟶ 2,980:
Additional information is also provided concerning how many words have been skipped due to
the various filters.
<langsyntaxhighlight lang="rexx">/*REXX pgm finds (dictionary) words which can be found in a specified word wheel (grid).*/
parse arg grid minL iFID . /*obtain optional arguments from the CL*/
if grid==''|grid=="," then grid= 'ndeokgelw' /*Not specified? Then use the default.*/
Line 1,548 ⟶ 3,040:
do n=1 for length(aa); p= pos( substr(aa,n,1), gg); if p==0 then return 1
gg= overlay(., gg, p) /*"rub out" the found character in grid*/
end /*n*/; return 0 /*signify that the AA passed the test*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,617 ⟶ 3,109:
number of nine-letter wheel words found: 0
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">wheel = "ndeokgelw"
middle, wheel_size = wheel[4], wheel.size
 
res = File.open("unixdict.txt").each_line.select do |word|
w = word.chomp
next unless w.size.between?(3, wheel_size)
next unless w.match?(middle)
wheel.each_char{|c| w.sub!(c, "") } #sub! substitutes only the first occurrence (gsub would substitute all)
w.empty?
end
 
puts res
</syntaxhighlight>
{{out}}
<pre>eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
</pre>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
MainModule: {
maxwLen: 9,
minwLen: 3,
dict: Vector<String>(),
subWords: Vector<String>(),
 
procGrid: (λ grid String() cent String() subs Bool()
(with cnt 0 (sort grid)
(for w in dict where (and (neq (index-of w cent) -1)
(match w "^[[:alpha:]]+$")) do
(if (is-subset grid (sort (cp w))) (+= cnt 1)
(if subs (append subWords w))
)
)
(ret cnt)
)),
 
_start: (λ locals: res 0 maxRes 0
(with fs FileStream()
(open-r fs "/mnt/proj/res/unixdict.txt")
(for w in (read-lines fs)
where (within (size w) minwLen maxwLen) do
(append dict w))
)
 
(lout "Main part of task:\n")
(procGrid "ndeokgelw" "k" true)
(lout "Number of words: " (size subWords) ";\nword list: " subWords)
 
(lout "\n\nOptional part of task:\n")
(for w in dict where (eq (size w) maxwLen) do
(for centl in (split (unique (sort (cp w))) "") do
(if (>= (= res (procGrid (cp w) centl false)) maxRes) (= maxRes res)
(lout "New max. number: " maxRes ", word: " w ", central letter: " centl)
) ) ) )
}</syntaxhighlight>
{{out}}
<pre>
Main part of task:
 
Number of words: 17;
word list: ["eke", "elk", "keel", "keen", "keg", "ken", "keno", "knee", "kneel", "knew", "know", "knowledge", "kong", "leek", "week", "wok", "woke"]
 
 
Optional part of task:
 
New max. number: 100, word: abdominal, central letter: a
New max. number: 117, word: abernathy, central letter: a
New max. number: 119, word: abhorrent, central letter: r
New max. number: 121, word: absorbent, central letter: e
New max. number: 123, word: adsorbate, central letter: a
New max. number: 125, word: adventure, central letter: e
New max. number: 155, word: advertise, central letter: e
New max. number: 161, word: alongside, central letter: a
New max. number: 170, word: alongside, central letter: l
New max. number: 182, word: ancestral, central letter: a
New max. number: 182, word: arclength, central letter: a
New max. number: 185, word: beplaster, central letter: e
New max. number: 215, word: claremont, central letter: a
New max. number: 215, word: spearmint, central letter: a
</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Const wheel="ndeokgelw"
 
Sub print(s):
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
 
Dim oDic
Set oDic = WScript.CreateObject("scripting.dictionary")
Dim cnt(127)
Dim fso
Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set ff=fso.OpenTextFile("unixdict.txt")
i=0
print "reading words of 3 or more letters"
While Not ff.AtEndOfStream
x=LCase(ff.ReadLine)
If Len(x)>=3 Then
If Not odic.exists(x) Then oDic.Add x,0
End If
Wend
print "remaining words: "& oDic.Count & vbcrlf
ff.Close
Set ff=Nothing
Set fso=Nothing
 
Set re=New RegExp
print "removing words with chars not in the wheel"
re.pattern="[^"& wheel &"]"
For Each w In oDic.Keys
If re.test(w) Then oDic.remove(w)
Next
print "remaining words: "& oDic.Count & vbcrlf
 
print "ensuring the mandatory letter "& Mid(wheel,5,1) & " is present"
re.Pattern=Mid(wheel,5,1)
For Each w In oDic.Keys
If Not re.test(w) Then oDic.remove(w)
Next
print "remaining words: "& oDic.Count & vbcrlf
 
print "checking number of chars"
 
Dim nDic
Set nDic = WScript.CreateObject("scripting.dictionary")
For i=1 To Len(wheel)
x=Mid(wheel,i,1)
If nDic.Exists(x) Then
a=nDic(x)
nDic(x)=Array(a(0)+1,0)
Else
nDic.add x,Array(1,0)
End If
Next
 
For Each w In oDic.Keys
For Each c In nDic.Keys
ndic(c)=Array(nDic(c)(0),0)
Next
For ii = 1 To len(w)
c=Mid(w,ii,1)
a=nDic(c)
If (a(0)=a(1)) Then
oDic.Remove(w):Exit For
End If
nDic(c)=Array(a(0),a(1)+1)
Next
Next
 
print "Remaining words "& oDic.count
For Each w In oDic.Keys
print w
Next
</syntaxhighlight>
{{out}}
<small>
<pre>
reading words of 3 or more letters
remaining words: 24945
 
removing words with chars not in the wheel
remaining words: 163
 
ensuring the mandatory letter k is present
remaining words: 27
 
checking number of chars
Remaining words 17
eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
</pre>
</small>
 
=={{header|Wren}}==
{{libheader|Wren-sort}}
{{libheader|Wren-seq}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
import "./sort" for Sort, Find
import "./seq" for Lst
 
var letters = ["d", "e", "e", "g", "k", "l", "n", "o","w"]
Line 1,692 ⟶ 3,394:
for (i in 0...mostWords9.count) {
System.print("%(mostWords9[i]) with central letter '%(mostLetters[i])'")
}</langsyntaxhighlight>
 
{{out}}
Line 1,719 ⟶ 3,421:
claremont with central letter 'a'
spearmint with central letter 'a'
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">string 0; \use zero-terminated strings
int I, Set, HasK, HasOther, HasDup, ECnt, Ch;
char Word(25);
def LF=$0A, CR=$0D, EOF=$1A;
[FSet(FOpen("unixdict.txt", 0), ^I);
OpenI(3);
repeat I:= 0; HasK:= false; HasOther:= false;
ECnt:= 0; Set:= 0; HasDup:= false;
loop [repeat Ch:= ChIn(3) until Ch # CR; \remove possible CR
if Ch=LF or Ch=EOF then quit;
Word(I):= Ch;
I:= I+1;
if Ch = ^k then HasK:= true;
case Ch of ^k,^n,^d,^e,^o,^g,^l,^w: [] \assume all lowercase
other HasOther:= true;
if Ch = ^e then ECnt:= ECnt+1
else [if Set & 1<<(Ch-^a) then HasDup:= true;
Set:= Set ! 1<<(Ch-^a);
];
];
Word(I):= 0; \terminate string
if I>=3 & HasK & ~HasOther & ~HasDup & ECnt<=2 then
[Text(0, Word); CrLf(0);
];
until Ch = EOF;
]</syntaxhighlight>
 
{{out}}
<pre>
eke
elk
keel
keen
keg
ken
keno
knee
kneel
knew
know
knowledge
kong
leek
week
wok
woke
</pre>
31

edits