Find words which contain the most consonants: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Python}}: Restored variant showing results for two of the possible interpretations of an ambiguous task description)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(19 intermediate revisions by 13 users not shown)
Line 11:
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">
V lines = File(‘unixdict.txt’).read().split("\n")
 
V words = lines.filter(w -> w.len > 10 & !re:‘[^a-z]’.search(w))
 
DefaultDict[Int, [String]] good
L(word) words
V c = word.replace(re:‘[aeiou]’, ‘’)
I sorted(Array(c)) == sorted(Array(Set(Array(c))))
good[c.len].append(word)
 
L(k, v) sorted(good.items(), reverse' 1B)
I v.len > 30
print(k‘: ’v.len‘ words’)
E
print(k‘: ’sorted(v).join(‘ ’))
</syntaxhighlight>
 
{{out}}
<pre>
9: comprehensible
8: 39 words
7: 130 words
6: 152 words
5: acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition
4: audiovisual bourgeoisie onomatopoeia
</pre>
 
=={{header|Action!}}==
In the following solution the input file [https://gitlab.com/amarok8bit/action-rosetta-code/-/blob/master/source/unixdict.txt unixdict.txt] is loaded from H6 drive. Altirra emulator automatically converts CR/LF character from ASCII into 155 character in ATASCII charset used by Atari 8-bit computer when one from H6-H10 hard drive under DOS 2.5 is used.
<langsyntaxhighlight Actionlang="action!">CHAR ARRAY line(256)
 
BYTE FUNC ConsonantsCount(CHAR ARRAY word)
Line 85 ⟶ 116:
i==-1
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Find_words_which_contain_the_most_consonants.png Screenshot from Atari 8-bit computer]
Line 103 ⟶ 134:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_Io;
with Ada.Strings.Fixed;
with Ada.Containers.Indefinite_Vectors;
Line 172 ⟶ 203:
end loop;
 
end Most_Consonants;</langsyntaxhighlight>
{{out}}
<pre> 4 consonants: 3 words
Line 226 ⟶ 257:
9 consonants: 1 words
comprehensible</pre>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68"># find words longer than 10 characters and sort by the number of consonants #
# they contain #
IF FILE input file;
STRING file name = "unixdict.txt";
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
print( ( "Unable to open """ + file name + """", newline ) )
ELSE
# file opened OK #
BOOL at eof := FALSE;
# set the EOF handler for the file #
on logical file end( input file
, ( REF FILE f )BOOL:
BEGIN # note that we reached EOF on the latest read #
# and return TRUE so processing can continue #
at eof := TRUE
END
);
 
# in-place quick sort an array of strings #
PROC s quicksort = ( REF[]STRING a, INT lb, ub )VOID:
IF ub > lb
THEN
# more than one element, so must sort #
INT left := lb;
INT right := ub;
# choosing the middle element of the array as the pivot #
STRING pivot := a[ left + ( ( right + 1 ) - left ) OVER 2 ];
WHILE
WHILE IF left <= ub THEN a[ left ] < pivot ELSE FALSE FI
DO
left +:= 1
OD;
WHILE IF right >= lb THEN a[ right ] > pivot ELSE FALSE FI
DO
right -:= 1
OD;
left <= right
DO
STRING t := a[ left ];
a[ left ] := a[ right ];
a[ right ] := t;
left +:= 1;
right -:= 1
OD;
s quicksort( a, lb, right );
s quicksort( a, left, ub )
FI # s quicksort # ;
 
# returns the length of s #
OP LENGTH = ( STRING s )INT: 1 + ( UPB s - LWB s );
# returns the consonant count of s or 0 if the consonants are not unique #
OP UNIQUECONSONANTS = ( STRING s )INT:
BEGIN
[ 0 : 26 ]INT count;
FOR c FROM LWB count TO UPB count DO count[ c ] := 0 OD;
FOR i FROM LWB s TO UPB s DO
CHAR c := s[ i ];
IF c >= "A" AND c <= "Z" THEN
c := REPR ( ABS c + ( ABS "a" - ABS "A" ) )
FI;
IF c >= "b" AND c <= "z" THEN
IF c /= "e" AND c /= "i" AND c /= "o" AND c /= "u" THEN
count[ ABS c - ABS "a" ] +:= 1
FI
FI
OD;
BOOL all unique := TRUE;
INT consonants := 0;
FOR c FROM LWB count TO UPB count WHILE all unique := count[ c ] < 2 DO
consonants +:= count[ c ]
OD;
IF all unique THEN consonants ELSE 0 FI
END # UNIQUECONSONANTS # ;
[ 1 : 2 000 ]STRING words;
INT w count := 0;
INT max length := 0;
WHILE NOT at eof
DO
STRING word;
get( input file, ( word, newline ) );
IF NOT at eof THEN
# have another word #
IF INT w length = LENGTH word;
w length > 10
THEN
IF INT consonants = UNIQUECONSONANTS word;
consonants > 0
THEN
# word is long enough to include and contains only uniue #
# consonants, store it prefixed by the max abs char #
# complement of the number of consonants in it, so we #
# can sort the words into reverse consonant count order #
words[ w count +:= 1 ] := REPR ( max abs char - consonants ) + word;
IF w length > max length THEN max length := w length FI
FI
FI
FI
OD;
close( input file );
# sort the words #
s quicksort( words, 1, w count );
# display the words #
INT prev count := 0;
INT p count := 0;
BOOL need nl := FALSE;
FOR w TO w count DO
STRING s word = words[ w ];
INT count = max abs char - ABS s word[ 1 ];
STRING word = s word[ 2 : ];
INT w length = LENGTH word;
IF count /= prev count THEN
IF need nl THEN print( ( newline ) ) FI;
print( ( newline, whole( count, 0 ), " consonants:", newline ) );
prev count := count;
p count := 0;
need nl := FALSE
FI;
print( ( " ", " " * ( max length - w length ), word ) );
IF NOT ( need nl := ( p count +:= 1 ) MOD 5 /= 0 ) THEN
print( ( newline ) )
FI
OD
FI</syntaxhighlight>
{{out}}
<pre>
 
9 consonants:
comprehensible
 
8 consonants:
administrable anthropology blameworthy bluestocking boustrophedon
bricklaying chemisorption christendom claustrophobia compensatory
comprehensive counterexample demonstrable disciplinary discriminable
geochemistry hypertensive indecipherable indecomposable indiscoverable
lexicography manslaughter misanthropic mockingbird monkeyflower
neuropathology paralinguistic pharmacology pitchblende playwriting
shipbuilding shortcoming springfield stenography stockholder
switchblade switchboard switzerland thunderclap
 
7 consonants:
acknowledge algorithmic alphanumeric ambidextrous amphibology
anchoritism atmospheric autobiography bakersfield bartholomew
bidirectional bloodstream boardinghouse cartilaginous centrifugal
chamberlain charlemagne clairvoyant combinatorial compensable
complaisant conflagrate conglomerate conquistador consumptive
convertible cosmopolitan counterflow countryside countrywide
declamatory decomposable decomposition deliquescent description
descriptive dilogarithm discernible discriminate disturbance
documentary earthmoving encephalitis endothermic epistemology
everlasting exchangeable exclamatory exclusionary exculpatory
explanatory extemporaneous extravaganza filamentary fluorescent
galvanometer geophysical glycerinate groundskeep herpetology
heterozygous homebuilding honeysuckle hydrogenate hyperboloid
impenetrable imperceivable imperishable imponderable impregnable
improvident improvisation incomparable incompatible incomputable
incredulity indefatigable indigestible indisputable inexhaustible
inextricable inhospitable inscrutable jurisdiction lawbreaking
leatherback leatherneck leavenworth logarithmic loudspeaking
maidservant malnourished marketplace merchandise methodology
misanthrope mitochondria molybdenite nearsighted obfuscatory
oceanography palindromic paradigmatic paramagnetic perfectible
phraseology politicking predicament presidential problematic
proclamation promiscuity providential purchasable pythagorean
quasiparticle quicksilver radiotelephone sedimentary selfadjoint
serendipity sovereignty subjunctive superfluity terminology
valedictorian valedictory verisimilitude vigilantism voluntarism
 
6 consonants:
aboveground advantageous adventurous aerodynamic anglophobia
anisotropic archipelago automorphic baltimorean beneficiary
borosilicate cabinetmake californium codetermine coextensive
comparative compilation composition confabulate confederate
considerate consolidate counterpoise countervail decisionmake
declamation declaration declarative deemphasize deformation
deliverance demountable denumerable deoxyribose depreciable
deprivation destabilize diagnosable diamagnetic dichotomize
dichotomous disambiguate eigenvector elizabethan encapsulate
enforceable ephemerides epidemiology evolutionary exceptional
exclamation exercisable exhaustible exoskeleton expenditure
experiential exploration fluorescein geometrician hemosiderin
hereinbelow hermeneutic heterogamous heterogeneous heterosexual
hexadecimal hexafluoride homebuilder homogeneity housebroken
icosahedral icosahedron impersonate imprecision improvisate
inadvisable increasable incredulous indivisible indomitable
ineradicable inescapable inestimable inexcusable infelicitous
informatica informative inseparable insuperable ionospheric
justiciable kaleidescope kaleidoscope legerdemain liquefaction
loudspeaker machinelike magisterial maladaptive mantlepiece
manufacture masterpiece meetinghouse meteorology minesweeper
ministerial multifarious musculature observation patrimonial
peasanthood pediatrician persecution pertinacious picturesque
planetarium pleistocene pomegranate predominate prejudicial
prohibition prohibitive prolegomena prosecution provisional
provocation publication quasiperiodic reclamation religiosity
renegotiable residential rooseveltian safekeeping saloonkeeper
serviceable speedometer subrogation sulfonamide superficial
superlative teaspoonful trapezoidal tridiagonal troublesome
vainglorious valediction venturesome vermiculite vocabularian
warehouseman wisenheimer
 
5 consonants:
acquisition acquisitive acrimonious ceremonious deleterious
diatomaceous egalitarian equilibrate equilibrium equinoctial
expeditious hereinabove homogeneous inequitable injudicious
inoperative inquisitive interviewee leeuwenhoek onomatopoeic
radioactive requisition
 
4 consonants:
audiovisual bourgeoisie onomatopoeia
</pre>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight algolwlang="pascal">begin % find the words longer than 10 characters that contain most consonants %
% an element of a WordList %
record WordListElement ( string(32) w; reference(WordListElement) next );
Line 311 ⟶ 556:
end if_words_wPos_ne_null
end for_wPos
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 393 ⟶ 638:
audiovisual bourgeoisie onomatopoeia
</pre>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">words: read.lines relative "unixdict.txt"
vowels: ["a" "e" "i" "o" "u"]
 
Line 423 ⟶ 669:
print ""
]
]</langsyntaxhighlight>
 
{{out}}
Line 799 ⟶ 1,045:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">FileRead, db, % A_Desktop "\unixdict.txt"
vowels := ["a", "e", "i", "o", "u"]
oRes := []
Line 820 ⟶ 1,066:
result .= "`n`n"
}
MsgBox, 262144, , % result</langsyntaxhighlight>
{{out}}
<pre>9 Unique consonants, word count: 1
Line 877 ⟶ 1,123:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f FIND_WORDS_WHICH_CONTAINS_MOST_CONSONANTS.AWK unixdict.txt
#
Line 921 ⟶ 1,167:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 934 ⟶ 1,180:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <bitset>
#include <cctype>
#include <cstdlib>
Line 1,002 ⟶ 1,248:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 1,110 ⟶ 1,356:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% If a word has no repeated consonants, return the amount
% of consonants. If it does have repeated consonants, return
% -1.
Line 1,169 ⟶ 1,415:
stream$putl(po, "")
end
end start_up</langsyntaxhighlight>
{{out}}
<pre style='height:100ex;'>4 consonants - 3 words:
Line 1,271 ⟶ 1,517:
9 consonants - 1 words:
comprehensible</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
This program makes extensive use of the standard Delphi TStringList component. It holds the dictionary, which is preloaded. It sorts a list of words by the number of consonants. It keeps track of the number of unique consonates in a word. The power the component is tha ability to sort and search the list at high speed. The program runs in 28 ms, including the time display the result. Note: The dictionary must of changed since the problem was first proposed because this program finds 10 words with 9 consonants, whereas other programs only find one.
 
<syntaxhighlight lang="Delphi">
var Dict: TStringList; {List holds dictionary}
 
 
function CountConsonants(S: string): integer;
{Count the number of unique consonants in a word}
{Uses TStringList capabilities to do this}
var I: integer;
var SL: TStringList;
begin
SL:=TStringList.Create;
try
{Keep sorted for speed}
SL.Sorted:=True;
{insure that no duplicates are added}
SL.Duplicates:=dupIgnore;
for I:=1 to Length(S) do
if not (S[I] in ['a','e','i','o','u']) then SL.Add(S[I]);
Result:=SL.Count;
finally SL.Free; end;
end;
 
 
function SortCompare(List: TStringList; Index1, Index2: Integer): Integer;
{Function used to sort words by consonant count}
begin
{Consonant count stored in the object parts of the string list}
Result:=Integer(List.Objects[Index2])-Integer(List.Objects[Index1]);
end;
 
{Item used to keep track of the range of }
{ word that have the same consonant count}
 
type TRangeInfo = record
Count: integer;
Start,Stop: integer;
end;
 
type TRangeArray = array of TRangeInfo;
 
 
procedure FindMostConsonants(Memo: TMemo);
{Find words with the most consonants}
var I,J,Cnt,CCnt: integer;
var SL: TStringList;
var S: string;
var RA: TRangeArray;
begin
SL:=TStringList.Create;
try
{Choose dictionary words > 10 in length}
for I:=0 to Dict.Count-1 do
if Length(Dict[I])>10 then
begin
{Get the number of consonants}
Cnt:=CountConsonants(Dict[I]);
{Store the word with the count casts as an object}
SL.AddObject(Dict[I],TObject(Cnt));
end;
{Sort the list by consonant count}
SL.CustomSort(SortCompare);
 
Cnt:=0;
SetLength(RA,0);
{Get the start and stop of words /c same # of consonants}
for I:=0 to SL.Count-1 do
begin
{If the count has changed, add new range variable}
if Integer(SL.Objects[I])<>Cnt then
begin
Cnt:=Integer(SL.Objects[I]);
if Length(RA)>0 then RA[High(RA)].Stop:=I-1;
SetLength(RA,Length(RA)+1);
RA[High(RA)].Count:=Cnt;
RA[High(RA)].Start:=I;
end;
end;
RA[High(RA)].Stop:=SL.Count-1;
{Display consonant information}
Memo.Lines.BeginUpdate;
try
for I:=0 to High(RA) do
begin
Cnt:=RA[I].Stop-RA[I].Start;
Memo.Lines.Add(IntToStr(Cnt)+' words with '+IntToStr(RA[I].Count)+' Consonants');
S:=''; Cnt:=0;
for J:=RA[I].Start to RA[I].Stop do
begin
Inc(Cnt);
S:=S+Format('%-23s',[SL[J]]);
if (Cnt mod 4)=0 then S:=S+#$0D#$0A
end;
Memo.Lines.Add(S);
end;
finally Memo.Lines.EndUpdate; end;
finally SL.Free; end;
end;
 
 
 
initialization
{Create/load dictionary}
Dict:=TStringList.Create;
Dict.LoadFromFile('unixdict.txt');
Dict.Sorted:=True;
finalization
Dict.Free;
end.
 
</syntaxhighlight>
{{out}}
<pre>
10 words with 9 Consonants
handicraftsmen bremsstrahlung crystallographer comprehensible
knightsbridge electroencephalogram handicraftsman crystallography
immunoelectrophoresis electroencephalography incomprehensible
91 words with 8 Consonants
indecomposable indecipherable switchboard switzerland
streptomycin switchblade supplementary indestructible
indiscoverable blameworthy contradistinguish polysaccharide
bluestocking playwriting cryptanalyst cryptanalyze
thyroglobulin cryptanalysis hollingsworth transmogrify
metallography incompressible thunderflower teleprocessing
counterclockwise manslaughter pitchblende astrophysical
thunderclap counterexample pharmacology complimentary
geochemistry complementarity complementary comprehensive
shortcoming psychometry chemisorption shipbuilding
claustrophobia fredericksburg clytemnestra claustrophobic
radiochemistry compensatory christendom chrysanthemum
chromatography indistinguishable brinkmanship laughingstock
stenography bricklaying straightforward boustrophedon
lexicography stockholder inextinguishable psychoanalyst
psychobiology psychoanalytic featherbedding spectrography
springfield jurisprudential extralinguistic disciplinary
paralinguistic mockingbird anthropology parasympathetic
parapsychology acknowledgeable discriminatory hydrochemistry
electrocardiograph misanthropic electroencephalograph discriminable
demonstrable hypertensive northumberland neuropathology
neuropsychiatric neurophysiology diethylstilbestrol triphenylphosphine
deoxyribonucleic administrable monkeyflower weatherstripping
 
409 words with 7 Consonants
jurisdiction psychiatric extravaganza condemnatory
dilogarithm jurisprudent draftsperson psychoanalysis
jacksonville psychiatrist providential monocotyledon
johannesburg nevertheless protoplasmic confirmatory
proclamation problematic diffeomorphism conquistador
knowledgeable productivity extemporaneous conservatism
presidential leavenworth leatherneck diffeomorphic
lawbreaking leatherback propagandist promiscuity
conglomerate prophylactic confiscatory conflagrate
conflagration congresswomen differentiable prognosticate
congresswoman nightmarish nitroglycerine congratulatory
commensurable flabbergast radiotelephone fluorescent
rapprochement commendatory radiotelegraph investigatory
radioastronomy quicksilver radiophysics fitzpatrick
mulligatawny documentary multiplicand nearsighted
clothesbrush fredrickson disturbance insupportable
insurmountable formaldehyde combinatorial resplendent
fragmentary reprehensible filamentary componentry
psychotherapy comprehension discriminant pterodactyl
discretionary disciplinarian discernible psychosomatic
psychophysiology compressible psychotherapist psychotherapeutic
quasiparticle netherworld ferromagnetism netherlands
commonwealth fiddlestick pythagorean purchasable
discriminate complaisant pyrotechnic ferromagnetic
compensable otherworldly counterflow petrochemical
philanthropic phenomenology electrocardiogram counterproductive
countrywide craftspeople craftsperson counterproposal
merchandise countryside physiochemical correspondent
phycomycetes phytoplankton marketplace physiognomy
phraseology phosphorescent philharmonic philanthropy
cosmopolitan micrography phosphorylate crestfallen
encephalitis perfectible declamatory cytochemistry
parliamentary czechoslovakia methacrylate decompression
electrophorus decontrolling methodology decomposable
decomposition deliquescent paradigmatic cryptanalytic
palindromic endothermic endomorphism cryptographer
electrophoresis perfunctory cybernetics cryptography
crystalline paramagnetic loudspeaking exculpatory
consumptive logarithmic predicament constructible
praiseworthy eavesdropping mitochondria contemporary
exclusionary exclamatory contemporaneous earthmoving
earthshaking explanatory nondescript conservatory
earsplitting notwithstanding lithospheric molybdenite
obfuscatory presbyterian conspiratorial lithography
contemptible misanthrope organometallic middleweight
maldistribute efflorescent ophthalmology contretemps
controvertible epistemology convertible malnourished
controversial controversy maidservant oceanography
polytechnic mispronunciation postdoctoral exchangeable
polymorphic everlasting ethnography description
politicking ombudsperson descriptive terpsichorean
heterozygous terminology incontrovertible thistledown
astrophysics thanksgiving atmospheric tablespoonful
incorruptible synergistic axisymmetric autobiography
inconvertible telephotography teletypesetting histochemistry
historiography incomputable transcendental archetypical
homebuilding transferable incomprehension hieroglyphic
thunderbolt astrophysicist thousandfold trafficking
inconsiderable thundershower thunderstorm bloodstream
indiscernible subjunctive boardinghouse indeterminable
superfluity indigestible indeterminacy straightway
bootstrapping straightaway brainchildren indiscriminate
subjectivity hardscrabble hardworking bartholomew
herpetology basidiomycetes sympathetic bakersfield
synchrotron synchronism incredulity hendrickson
indefatigable indescribable bidirectional battleground
sycophantic bibliography bespectacled incompatible
hypochlorous valedictorian upperclassmen hypochlorite
verisimilitude improvident valedictory hypocritical
hygroscopic hyperboloid hydrothermal hydroxylate
hyperboloidal upperclassman underclassman underclassmen
imponderable williamsburg acknowledge idiosyncratic
imperceivable impenetrable imperishable imperceptible
administratrix voluntarism vigilantism hypothalamic
hysterectomy impracticable hypothalamus impregnable
transshipping anthropomorphism transposable transshipped
huckleberry transylvania anthropomorphic anthropogenic
transmissible transmittable transfusable incomparable
transpacific incombustible honeysuckle incommensurable
improvisation hydrophobic hydrophilic amphibology
alphanumeric algorithmic hydrostatic ambidextrous
hydrocarbon anchoritism inapproachable hummingbird
hydrofluoric hydrogenate hydrodynamic hydroelectric
schoolmaster schroedinger grandmother grandnephew
schlesinger somebody'll grandiloquent centrifugal
chronography scrupulosity sledgehammer grandfather
skullduggery spatterdock sovereignty cartilaginous
spectrogram groundskeep circumscription schenectady
circumferential schizophrenic cartography schizomycetes
schizophrenia inexhaustible seismography selfadjoint
chemotherapy checksumming christoffel geophysical
geochronology inflammatory serendipity cholinesterase
servomechanism chloroplast chloroplatinate chromatograph
silversmith chamberlain searchlight grandchildren
inexpressible glycerinate shuffleboard sedimentary
galvanometer inextricable charlemagne charlottesville
inhospitable clairvoyant springboard staphylococcus
industrialism sportswriting gyrocompass saskatchewan
spermatophyte calligraphy indisputable salmonberry
stoichiometry clockwatcher handkerchief stereography
stenographer breathtaking classificatory candlestick
candlelight spectrophotometer carbohydrate inscrutable
spectrograph circumstantial
739 words with 6 Consonants
irredentism inadmissible introductory inadvisable
monochromatic intractable interruptible minesweeper
impermissible impersonate inscription insubordinate
insufferable multiplexor irreproducible irreproachable
multiplication multifarious multiplicative inappreciable
irrelevancy inflationary intramolecular monochromator
informative imprecision involuntary improvisate
impractical informatica infrastructure intemperance
inhomogeneity miscegenation intermediary insuppressible
impressible imperturbable implementer implementor
minicomputer morphophonemic monstrosity insuperable
insignificant inseparable ministerial interpolatory
ionospheric incredulous malfunction mantlepiece
malpractice inescapable maladaptive indefensible
malformation koenigsberg inestimable juxtaposition
increasable marshmallow incorrigible marlborough
manufacture kindergarten kaleidescope kaleidoscope
latitudinary indispensable longstanding legerdemain
loudspeaker liechtenstein lithosphere liquefaction
liverpudlian lighthearted luminescent magisterial
indomitable ineradicable magnificent machinelike
individualism indiscretion leatherwork indivisible
metamorphic metallurgist metamorphose metamorphism
infantryman metallurgic incondensable incompletion
irrespective metamorphosis michaelangelo metropolitan
infinitesimal michelangelo infelicitous infantrymen
meteorology incommensurate incommutable incongruity
meetinghouse incontrollable meistersinger incontestable
justiciable incorporable masterpiece matriarchal
inexcusable melodramatic inexplicable mercilessly
inconsequential metalliferous irresponsible mephistopheles
mendelssohn inconsiderate jitterbugging stereoscopy
stickleback steeplechase steprelation stimulatory
stratospheric strawflower stockbroker strangulate
spectrometer spectroscopy southwestern spectacular
speedometer statesmanlike steeplebush squashberry
stagestruck stroboscopic surveillant susceptible
superlunary supranational syllogistic systemization
teaspoonful symptomatic synchronous subservient
substitutionary stupefaction subrogation sulfanilamide
superintendent superlative sulfonamide superficial
southernmost scarborough scatterbrain sarcophagus
satisfactory schoolgirlish scrumptious seismograph
schoolteacher screwdriver responsible revolutionary
representative residential rhombohedral safekeeping
saloonkeeper rooseveltian rudimentary septuagenarian
simpleminded simultaneity sidestepping significant
singlehanded smokescreen southampton slaughterhouse
smithereens serviceberry severalfold serendipitous
serviceable shakespearean shortsighted shuttlecock
shakespearian shatterproof teleconference unidirectional
vacationland unbeknownst unchristian vainglorious
vermiculite vladivostok valediction venturesome
troublesome trustworthy tropospheric troubleshoot
tuberculosis typographer tyrannicide typesetting
typewritten vocabularian wiretapping wisenheimer
whistleable wholehearted workmanlike yellowknife
yellowstone workstation worthington weatherbeaten
weatherproof warehouseman warmhearted weatherstrip
westinghouse westminster westchester westernmost
trisyllable transceiver transcendent transalpine
transatlantic transconductance transduction transference
transcontinental transcription terpsichore testamentary
teletypewrite tenterhooks tetrachloride thunderbird
tranquillity thenceforth thoroughbred transferral
traversable trencherman transversal trapezoidal
trenchermen tridiagonal trigonometry trichinella
trichloroethane transformation translucent transferred
transferring transmittal transmitting transplantation
transmittance transmitted renegotiable performance
periphrastic perceptible perchlorate permissible
persecutory perseverance perpendicular persecution
pathogenesis patriarchal parenthetic parliamentarian
patrimonial pennsylvania pentecostal peasanthood
pediatrician perseverant piezoelectric pigeonberry
physiotherapy picturesque placeholder planoconvex
platitudinous planetarium planetesimal pertinacious
petrifaction perspective perspicuity pharmaceutic
photography physiotherapist philanthrope philodendron
parenthesis nomenclature northampton newspaperman
newspapermen northernmost novosibirsk nymphomaniac
northwestern nostradamus musculature muskellunge
multiplicity multitudinous mycobacteria neurasthenic
neuromuscular neanderthal neoconservative objectivity
orthorhombic oscillatory orthography orthonormal
pacesetting paramilitary parentheses painstaking
paperweight obsolescent oceanographer observation
observatory officeholder orthodontic orthodontist
omnipresent optoelectronic pleistocene provisional
provocation proteolytic prothonotary psychoacoustic
puddingstone pumpkinseed psychopathic publication
prolegomena pronounceable prohibitive prohibitory
proscription protagonist proteolysis prosecution
protactinium pyroelectric recombinant recriminatory
rattlesnake reclamation rectangular religiosity
reminiscent reflectance registrable quarterback
quasiperiodic pyrophosphate quadrangular quasistationary
radiography radiotherapy rachmaninoff radiochemical
prohibition precambrian precautionary practicable
praseodymium precipitable predominate prefabricate
predisposition predominant poliomyelitis pomegranate
plenipotentiary polarography ponchartrain postgraduate
postmultiply pornography postcondition preferential
primitivism prizewinning presumption presumptive
probabilist professional programmable procrastinate
procrustean preliminary premonitory prehistoric
prejudicial prescription preservation prestidigitate
prescriptive presentational countersink counterpoise
counterbalance countersunk cruickshank cromwellian
countervail counterargument convalescent controlling
controllable conversation corruptible corrigendum
copperfield deforestation deerstalker deemphasize
deformation demonstrate deliverance delicatessen
deconvolution declamation decisionmake crystallite
declaration decontrolled declaratory declarative
contributory congressmen congressman congressional
conjectural conservation consequential conscription
congratulate confidential conferrable confederate
configuration conformation confiscable confirmation
contraceptive contemptuous contemplate contradictory
contrariwise contradistinction contradistinct consumption
considerate conservator conservative consolidate
consultative constantinople conspirator demountable
epistolatory epigrammatic epidemiology evolutionary
exercisable exclamation exceptional ephemerides
encapsulate emphysematous ellipsometer enchantress
entranceway enforceable encyclopedic extraordinary
extraditable expressible extravagant featherweight
featherbrain extroversion exploratory expectorant
exoskeleton exhaustible expenditure exploration
experimentation experiential elizabethan diagnosable
destabilize deregulatory diagnostician diamagnetism
diamagnetic diagrammatic deprivation denumerable
densitometer demultiplex deoxyribose depressible
depreciable deprecatory distributive distribution
distinguish diversionary electrolysis eigenvector
dreadnought dispersible dicotyledon dichotomous
dichotomize differential dispensable disambiguate
diffractometer confederacy blasphemous bladderwort
birefringent bloomington bookshelves bodybuilding
bodhisattva bilharziasis barycentric baltimorean
backscatter battlefront bestselling beneficiary
belligerent cacophonist cabinetmake butterfield
californium carborundum cantabrigian calisthenic
burglarproof brahmaputra borosilicate bootstrapped
breakthrough bronchiolar bridgewater breastplate
babysitting aforementioned afghanistan aerodynamic
amethystine anastigmatic anachronistic anachronism
adventurous absentminded abovementioned aboveground
accompanist advantageous administrate addressograph
argumentative archipelago approximant asynchronous
autotransformer automorphism automorphic approximable
animadversion anglophobia anglicanism anisotropic
apprehensive anticipatory anthracnose cardiovascular
combinatoric coextensive codetermine combustible
companionway commonality commensurate cobblestone
clandestine circumvention circumstance classification
clothesline clotheshorse climatology concertmaster
comptroller compressive conciliatory confectionery
confabulate condensible compression compassionate
compartment comparative compilation composition
complementation complainant circumsphere charismatic
chambermaid chairperson checkerberry chippendale
checksummed checkerboard centrifugate cartographic
cartographer carthaginian cataclysmic catholicism
catastrophic catastrophe chronograph chromosphere
chromatogram churchwoman circumspect circumlocution
churchwomen christopher cholesterol choirmaster
chlorophyll choreography christianson christenson
christensen hemispheric fingerprint fragmentation
housebroken hypothyroid hellgrammite heliocentric
fredericton handicapper handicapping halfhearted
homogeneity gaithersburg illegitimacy hereinbelow
ferromagnet furthermost icosahedral icosahedron
idiosyncrasy hemosiderin frostbitten fundamental
frontiersmen hundredfold hydrochloride hattiesburg
fluorocarbon fluorescein hydrochloric functionary
harpsichord handwritten hypocycloid frontiersman
hebephrenic furtherance headquarters happenstance
hydrophobia hydrosphere heavyweight heterocyclic
homebuilder forgettable geometrician gerontology
heterogeneous heterogamous gastrointestinal hippocrates
hexadecimal heterogeneity hexachloride granddaughter
grandparent heterosexual gubernatorial gobbledygook
haberdashery hermeneutic highfalutin hexafluoride
 
669 words with 5 Consonants
sightseeing retrovision characteristic retrogressive
revisionary ribonucleic rockefeller indigestion
rhetorician sacrilegious sacrificial retrogression
requisition centerpiece reservation simultaneous
replaceable coincidental cauliflower inconsolable
cockleshell headquarter ceremonious retrofitting
resourceful resignation respiratory respiration
salesperson churchgoing churchillian indefinable
choreograph scintillate circumcision circumference
circulatory seventeenth hereinafter segmentation
incriminate sensorimotor sedimentation sequestration
herringbone hereinabove secretarial indianapolis
sanctimonious satisfaction indeterminate salvageable
clearheaded heterostructure indifferent chattanooga
circumscribe shakespeare chiropractor circumpolar
incorporate scandinavia cheerleader cheesecloth
shareholder prostitution proprioceptive proprioception
inequitable protestation inequivalent pronunciation
confrontation promptitude proposition conformance
inexpedient psychophysic computation industrious
hallucinate indubitable compunction provocateur
protuberant ineluctable ineffective ineffectual
provocative consecutive gesticulate prestigious
pretentious presupposition presumptuous consolation
consonantal prerogative geochemical inferential
presentation inexpensive inexperience inexplainable
promiscuous confucianism proliferate conjuncture
professorial conscionable progressive progression
programming recriminate reciprocity recalcitrant
rectilinear colorimeter combination commentator
commiserate commissariat reactionary commendation
indisposition collapsible reimbursable rehabilitate
remonstrate collaborate remembrance refractometer
reformatory referential regrettable registration
regimentation quadrilateral quadrennial indissoluble
quarrelsome quadripartite quadrillion handicapped
indochinese indoctrinate compellable competition
competitive radioactive committeewomen quintessential
committable radiocarbon committeewoman communicable
quasicontinuous quartermaster quintessence questionnaire
commonplace transmutation apocalyptic apperception
transpiration transparent transoceanic apprehension
impropriety transmission transmitter application
appreciable antisemitic treacherous anniversary
anorthosite triceratops triangulate trepidation
antiperspirant transposition transportation antagonistic
transvestite hypophyseal arrangeable arteriolosclerosis
tortoiseshell aristocracy aristotelean aristotelian
ascomycetes assyriology thoroughgoing topocentric
arteriosclerosis articulatory inaccessible transgression
transfusion transfinite approbation transliterate
transgressor architectural argillaceous argumentation
approximate archdiocese architectonic trichloroacetic
acrimonious watercourse wastebasket acquiescent
acquisition acquisitive adventitious viscoelastic
vicissitude actinometer illusionary impertinent
accreditation immeasurable accelerometer acclamation
zoroastrian impartation absenteeism wherewithal
wheresoever weyerhauser winnipesaukee accompaniment
impermeable aminobenzoic amphetamine anaplasmosis
tyrannosaurus agriculture americanism trifluouride
trifluoride importunate troposphere importation
anastomotic agricultural afforestation implausible
implementation implantation affirmation affirmative
unidimensional agglomerate agribusiness aforethought
uniprocessor afterthought incommunicable homomorphic
homogeneous storyteller brazzaville breadwinner
stephanotis brucellosis incompetent stethoscope
brontosaurus brotherhood brandenburg submersible
bodybuilder bonaventure substantive substantial
incandescent stratosphere horticulture homomorphism
strikebreak streptococcus bootlegging hippopotamus
carolingian hippocratic inconceivable carbonaceous
inconclusive solicitation smithsonian caterpillar
incongruous southeastern sophisticate spectroscope
calendrical hollandaise sportswriter stationmaster
stationarity homeomorphic histochemic calorimeter
spectroscopic sportswrite spontaneity spokesperson
subterranean inadvertent telekinesis telecommunicate
teratogenic teleprompter teleprinter tachistoscope
inalterable baccalaureate tegucigalpa technocratic
autosuggestible testimonial thereabouts therapeutic
theoretician thoroughfare astronautic thiocyanate
tetrahedral tetrafluouride tetrafluoride thallophyte
tetravalent tetrahedron biconnected superfluous
bimetallism superposable supernatant bicentennial
bittersweet suggestible suffragette bimolecular
supercilious superannuate superstition battlefield
humanitarian benedictine inappeasable balletomane
inapplicable suppressible bicarbonate supervisory
benediction inarticulate susceptance interrogatory
divestiture doctrinaire interpretive interregnum
distributor dodecahedron mountainside domesticate
documentation multipliable dodecahedral narragansett
neuroanotomy neuroanatomy neuroanatomic disaccharide
interpolate forbearance necromantic dissertation
dissociable disquisition disseminate needlepoint
montenegrin electrician intersperse electrolyte
egalitarian minneapolis eigenfunction embarcadero
embraceable interviewee electrolytic elephantine
interstitial econometrica fontainebleau earthenware
easternmost doubleheader monongahela downtrodden
econometric mischievous miscellaneous eavesdropped
mollycoddle eavesdropper directrices optometrist
intelligible oppenheimer deportation intelligentsia
orchestrate desegregate oleomargarine officialdom
dereference onomatopoeic oneupmanship insurrection
paraboloidal insufficient palestinian parallelogram
delimitation delineament osteopathic fountainhead
orthophosphate paleolithic frankfurter fractionate
desideratum internescine differentiate nitrogenous
northeastern nonetheless dictatorial diophantine
newfoundland directorial interpolant nightingale
nicotinamide diatomaceous determinate diacritical
intercalate octogenarian intemperate determinant
interceptor interference interferometer interception
nymphomania nullstellensatz lackadaisic labradorite
kwashiorkor exponential exportation irredentist
knickerbocker kitchenette kirkpatrick knuckleball
exterminate extracellular irredeemable lightweight
irreclaimable irreconcilable expectorate expeditious
lineprinter explanation leeuwenhoek exploitation
libertarian irrecoverable legislature kinesthesis
irretrievable fayetteville irremovable isochronous
irrevocable irreversible fermentation irrepressible
irreplaceable irresolvable irresolution irresistible
fasciculate extramarital irrefutable extrapolate
extracurricular irreducible extradition facultative
jitterbugger jeffersonian extraterrestrial ferroelectric
irremediable ipsilateral introduction mathematician
flirtatious meadowsweet matrimonial matriculate
epimorphism episcopalian invertebrate massachusetts
introversion marriageable mediterranean endothelial
intransigent enlargeable intolerable encumbrance
meretricious intransitive megalomaniac entrepreneurial
mensuration enthusiastic mendelevium equidistant
excommunicate involutorial invulnerable macroprocessor
machination machiavelli existential ferruginous
expectation loosestrife exhortation longitudinal
macroscopic malocclusion malnutrition equilibrium
manipulable manifestation equilibrate exasperater
magnanimity macrostructure equinoctial eratosthenes
investigate injudicious innumerable corpuscular
convolution cornerstone philosophic philosopher
phosphoresce cotoneaster cottonmouth plagioclase
contrivance contributor contribution planoconcave
furthermore inhomogeneous inheritance inharmonious
pigmentation councilwoman crocodilian crucifixion
inquisitive perturbation perspiration customhouse
decaffeinate curvilinear insecticide permutation
inoperative pharmacopoeia phenylalanine councilwomen
counterattack counterpoint pestilential counterpart
counterfeit counterintuitive contravention precipitous
constructor predecessor constitutive constrictor
poughkeepsie potentiometer practitioner consultation
inflammation preponderant premonition preponderate
prerequisite preposition constellate consternate
inflammable premeditate gegenschein postprocessor
polarograph polariscope contraption gainesville
contralateral ingratitude contravariant contrariety
polarimeter pneumococcus porterhouse pornographer
portmanteau postprocess postoperative information
polypropylene contractual pontificate contraception
inspiration instrumentation particulate deleterious
penitentiary parsimonious decommission instinctual
paternoster degradation penultimate paraphernalia
decollimate parishioner insubstantial decolletage
participant declination
226 words with 4 Consonants
appropriable escherichia rotogravure maintenance
ornamentation examination concomitant magnanimous
firecracker condescension decorticate instillation
intellectual protectorate contentious guaranteeing
continental antiquarian antisemitism intelligent
condominium macromolecule inefficient conductance
macromolecular inhabitation inconvenient retrorocket
toastmaster totalitarian individuate tonsillitis
entrepreneur memorabilia occultation astigmatism
assignation assimilable megalomania optoacoustic
equilateral participate optoisolate concessionaire
indignation concentrate aristocratic fossiliferous
reverberate onomatopoeia architecture rhododendron
indoeuropean consanguineous illustrious consanguine
conscientious acquaintance weierstrass constantine
connotative affectionate constituent constitution
affectation connoisseur illimitable veterinarian
acculturate academician parallelepiped sarsparilla
irreparable preposterous immunization infestation
sarsaparilla conspicuous accreditate pandemonium
preparation accommodate preparatory preparative
anastomosis secretariat proportionate sagittarius
contaminate ignominious oscilloscope postposition
influential greengrocer aniseikonic lilliputian
proprietary denunciation garrisonian exponentiate
aftereffect precipitate expropriate independent
circumcircle schoolhouse utilitarian agglutinate
albuquerque contaminant illegitimate osteoporosis
proletariat lamentation latitudinal internecine
substantiate nonsensical substituent mountainous
incalculable substitution multinomial carcinogenic
inclination collocation penitential incapacitate
dodecahedra incarcerate mountaineer inoffensive
restorative ratiocinate ecclesiastic supposition
mississippian superstitious commemorate intermittent
inauspicious reconnaissance restitution philadelphia
restoration reciprocate inopportune businessman
businessmen homeostasis camaraderie insensitive
statistician renaissance repetitious directorate
spontaneous coeducation coefficient peripatetic
reportorial peppergrass bureaucratic collectible
inquisition perspicacious perspicuous refrigerate
interrogate bourgeoisie necessitate interpretation
bureaucracy stegosaurus disquietude necromancer
capacitance installation suppression authoritative
autocollimate retrofitted temperature detestation
authoritarian tempestuous autocorrelate retroactive
quintillion retribution corroborate inconspicuous
intervention ellipsoidal authenticate communicate
convocation meritorious attitudinal theretofore
qualitative quantitative mesopotamia terrestrial
audiovisual augmentation attributive communicant
attribution certificate millionaire interruption
millenarian surreptitious einsteinium swallowtail
inconsistent socioeconomic retaliatory resuscitate
retardation tallahassee committeeman bibliophile
inappropriate committeemen numismatist
32 words with 3 Consonants
sanguineous instantiate inattentive efficacious
territorial deteriorate attestation portraiture
countenance prosopopoeia assassinate mississippi
continuation coccidiosis einsteinian inalienable
nonogenarian manumission incantation indentation
institution concatenate appropriate restaurateur
nonagenarian trinitarian instantaneous glossolalia
regurgitate ostentatious connecticut connotation
barbiturate
1 words with 2 Consonants
inattention ouagadougou
 
</pre>
 
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Word(s) containing most consonants. Nigel Galloway: February 18th., 2021
let vowels=set['a';'e';'i';'o';'u']
let fN g=let g=g|>Seq.filter(vowels.Contains>>not)|>Array.ofSeq in if g=(g|>Array.distinct) then g.Length else 0
printfn "%A" (seq{use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(fun n->n.Length>10)|>Seq.groupBy fN|>Seq.sortBy fst|>Seq.last)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,285 ⟶ 2,211:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs formatting io.encodings.ascii io.files kernel math
prettyprint prettyprint.config sequences sets sets.extras ;
FROM: namespaces => set ;
Line 1,295 ⟶ 2,221:
[ [ "aeiou" member? not ] count ] collect-by >alist reverse
 
6 length-limit set 100 margin set .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,310 ⟶ 2,236:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
function uniq_cons( s as string ) as integer
dim letter( 1 to 26 ) as boolean
Line 1,336 ⟶ 2,262:
wend
 
close #1</langsyntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
#build WarnOfScopedVars NO
 
#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
 
local fn Words as CFArrayRef
CFURLRef url = fn URLWithString( @"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" )
CFStringRef string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
CFArrayRef array = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet )
end fn = fn ArrayFilteredArrayUsingPredicate( array, fn PredicateWithFormat( @"self.length > %d", 10 ) )
 
 
local fn StringByDeletingCharactersInSet( inString as CFStringRef, set as CFCharacterSetRef ) as CFStringRef
CFMutableStringRef outString = fn MutableStringWithCapacity(0)
long i, length = len(inString)
for i = 0 to length - 1
unichar c = fn StringCharacterAtIndex( inString, i )
if ( fn CharacterSetCharacterIsMember( set, c ) == NO )
MutableStringAppendFormat( outString, @"%C", c )
end if
next
end fn = outString
 
 
void local fn DoIt
CFArrayRef words = fn Words
CFCharacterSetRef vowelSet = fn CharacterSetWithCharactersInString( @"aeiou" )
CFMutableArrayRef array = fn MutableArrayWithCapacity(0)
long maxCons = 0
CFStringRef wd
for wd in words
CFStringRef wd2 = fn StringByDeletingCharactersInSet( wd, vowelSet )// remove vowels
CFMutableSetRef mutSet = fn MutableSetWithCapacity(0)
long i, length = len(wd2)
for i = 0 to length - 1
MutableSetAddObject( mutSet, mid(wd2,i,1) )
next
if ( length == len(mutSet) ) // if equal lengths, there are no duplicate consonants
if ( length >= maxCons )
if ( length > maxCons ) // more consonants in current word so clear array
MutableArrayRemoveAllObjects( array )
maxCons = length
end if
MutableArrayAddObject( array, wd )
end if
end if
next
print fn ArrayComponentsJoinedByString( array, @"\n" )
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
comprehensible
</pre>
 
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,420 ⟶ 2,412:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,428 ⟶ 2,420:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">{-# LANGUAGE LambdaCase #-}
 
-- Given a list of words on stdin, write to stdout the set of words having the
Line 1,463 ⟶ 2,455:
main :: IO ()
main = interact (unlines . mostDistinctConsonants . filter longEnough . words)
where longEnough xs = length xs > 10</langsyntaxhighlight>
 
{{out}}
Line 1,471 ⟶ 2,463:
Or, in terms of Data.Set, choosing just one of various possible interpretations of an ambiguous task description.
 
<langsyntaxhighlight lang="haskell">import Data.Char (toLower)
import Data.Function (on)
import Data.List (groupBy, sortOn, (\\))
Line 1,498 ⟶ 2,490:
. take 1
. uniqueGlyphCounts consonants
. lines</langsyntaxhighlight>
{{Out}}
<pre>("bremsstrahlung",9)
Line 1,514 ⟶ 2,506:
or adjusting the test above to return only words which use no consonant twice:
 
<langsyntaxhighlight lang="haskell">main :: IO ()
main =
readFile "unixdict.txt"
Line 1,529 ⟶ 2,521:
. length
. filter (`S.member` consonants)
)</langsyntaxhighlight>
{{Out}}
<pre>("comprehensible",9)</pre>
 
=={{header|J}}==
<langsyntaxhighlight Jlang="j"> >(#~ [: (= >./) #@(~.#~ ~.-:])@-.&'aeiou'@>) cutLF fread'unixdict.txt'
comprehensible</langsyntaxhighlight>
 
=={{header|JavaScript}}==
For file IO, this version relies on the macOS ObjC classes exposed to JavaScript for Automation.
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// ----- WORDS USING LARGEST SETS OF CONSONANTS ------
 
// uniqueGlyphCounts :: Int -> S.Set Char ->
// [String] -> [[(String, Int)]]
const uniqueGlyphCounts = n =>
// Words of length greater than n, tupled with the
// size of their subset of used glyphs, and grouped
// accordingly – sorted by descending set size.
glyphSet => ws => groupBy(
on(a => b => a === b)(snd)
)(
sortBy(
flip(comparing(snd))
)(
ws.flatMap(
w => n < w.length ? [[
w,
intersection(glyphSet)(
new Set([...w])
).size
]] : []
)
)
);
 
 
// noGlyphTwice :: Set Char -> (String, Int) -> Bool
const noGlyphTwice = glyphs =>
// True if the number of characters in the string
// that are included in glyphs matches the
// precalculated size of the set of glyphs used.
sn => sn[1] === [...sn[0]]
.filter(c => glyphs.has(c))
.length;
 
 
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
const
upperCs = (
enumFromToChar("A")("Z")
).filter(c => !"AEIOU".includes(c)),
consonants = new Set(
[...upperCs, ...upperCs.map(toLower)]
),
noRepetition = noGlyphTwice(consonants);
 
return take(1)(
uniqueGlyphCounts(10)(consonants)(
readFile("unixdict.txt").split("\n")
)
)[0].filter(noRepetition);
};
 
 
// --------------------- GENERIC ---------------------
 
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
// A pair of values, possibly of
// different types.
b => ({
type: "Tuple",
"0": a,
"1": b,
length: 2,
*[Symbol.iterator]() {
for (const k in this) {
if (!isNaN(k)) {
yield this[k];
}
}
}
});
 
 
// comparing :: Ord a => (b -> a) -> b -> b -> Ordering
const comparing = f =>
// The ordering of f(x) and f(y) as a value
// drawn from {-1, 0, 1}, representing {LT, EQ, GT}.
x => y => {
const
a = f(x),
b = f(y);
 
return a < b ? -1 : (a > b ? 1 : 0);
};
 
 
// enumFromToChar :: Char -> Char -> [Char]
const enumFromToChar = m =>
n => {
const [intM, intN] = [m, n].map(
x => x.codePointAt(0)
);
 
return Array.from({
length: Math.floor(intN - intM) + 1
}, (_, i) => String.fromCodePoint(intM + i));
};
 
 
// flip :: (a -> b -> c) -> b -> a -> c
const flip = op =>
// The binary function op with
// its arguments reversed.
1 !== op.length ? (
(a, b) => op(b, a)
) : (a => b => op(b)(a));
 
 
// groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
const groupBy = eqOp =>
// A list of lists, each containing only elements
// equal under the given equality operator,
// such that the concatenation of these lists is xs.
xs => Boolean(xs.length) ? (() => {
const [h, ...t] = xs;
const [groups, g] = t.reduce(
([gs, a], x) => eqOp(x)(a[0]) ? (
Tuple(gs)([...a, x])
) : Tuple([...gs, a])([x]),
Tuple([])([h])
);
 
return [...groups, g];
})() : [];
 
 
// intersection :: Set -> Set -> Set
const intersection = a =>
// The intersection of two sets.
b => new Set([...a].filter(i => b.has(i)));
 
 
// on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
const on = f =>
// e.g. groupBy(on(eq)(length))
g => a => b => f(g(a))(g(b));
 
 
// readFile :: FilePath -> IO String
const readFile = fp => {
// The contents of a text file at the
// given file path.
const
e = $(),
ns = $.NSString
.stringWithContentsOfFileEncodingError(
$(fp).stringByStandardizingPath,
$.NSUTF8StringEncoding,
e
);
 
return ObjC.unwrap(
ns.isNil() ? (
e.localizedDescription
) : ns
);
};
 
 
// snd :: (a, b) -> b
const snd = tpl =>
// Second member of a pair.
tpl[1];
 
 
// sortBy :: (a -> a -> Ordering) -> [a] -> [a]
const sortBy = f =>
// A copy of xs sorted by the comparator function f.
xs => xs.slice()
.sort((a, b) => f(a)(b));
 
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : Array.from({
length: n
}, () => {
const x = xs.next();
 
return x.done ? [] : [x.value];
}).flat();
 
 
// toLower :: String -> String
const toLower = s =>
// Lower-case version of string.
s.toLocaleLowerCase();
 
 
// MAIN ---
return JSON.stringify(main());
})();</syntaxhighlight>
{{Out}}
<pre>[["comprehensible",9]]</pre>
 
=={{header|jq}}==
Line 1,548 ⟶ 2,750:
 
'''Preliminaries'''
<langsyntaxhighlight lang="jq"># "bag of words"
def bow(stream):
reduce stream as $word ({}; .[($word|tostring)] += 1);
Line 1,565 ⟶ 2,767:
bow(explode[])
| all(.[]; . == 1);
</syntaxhighlight>
</lang>
'''The Tasks'''
<langsyntaxhighlight lang="jq">def tasks:
 
def taskA:
Line 1,592 ⟶ 2,794:
taskB) ;
 
tasks</langsyntaxhighlight>
{{out}}
Invocation example: jq -nRrM program.jq unixdict.txt
Line 1,608 ⟶ 2,810:
=={{header|Julia}}==
{{trans|Phix}}
<langsyntaxhighlight lang="julia">consonant(ch) = !(ch in ['a', 'e', 'i', 'o', 'u'])
singlec(consonants) = length(unique(consonants)) == length(consonants)
over10sc(word) = length(word) > 10 && singlec(filter(consonant, word))
Line 1,615 ⟶ 2,817:
println(length(res), " words found.\n\nWord Consonants\n----------------------")
foreach(a -> println(rpad(a[2], 16), -a[1]), res)
</langsyntaxhighlight>{{out}}
<pre>
347 words found.
Line 1,643 ⟶ 2,845:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">consonants = DeleteCases[Alphabet[], Alternatives @@ Characters["euioa"]];
dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]];
dict //= StringSplit[#, "\n"] &;
Line 1,649 ⟶ 2,851:
dict = {#, Select[Characters[#], MemberQ[consonants, #] &]} & /@ dict;
dict //= Select[Last /* DuplicateFreeQ];
SortBy[GatherBy[dict, Last /* Length], First /* Last /* Length][[All, All, 1]] // Column</langsyntaxhighlight>
{{out}}
<pre>{audiovisual,bourgeoisie,onomatopoeia}
Line 1,663 ⟶ 2,865:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import strformat, strutils, tables
 
const Vowels = {'a', 'e', 'i', 'o', 'u'}
Line 1,688 ⟶ 2,890:
for i, word in results[n]:
stdout.write word.align(14), if (i + 1) mod 9 == 0: '\n' else: ' '
echo()</langsyntaxhighlight>
 
{{out}}
Line 1,747 ⟶ 2,949:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Find_words_which_contains_most_consonants
Line 1,757 ⟶ 2,959:
$most[$_] and printf "%d Unique consonants, word count: %d\n\n%s\n\n",
$_, $most[ $_ ] =~ tr/\n//, $most[ $_ ] =~ tr/\n/ /r =~ s/.{66}\K /\n/gr
for reverse 0 .. $#most;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,842 ⟶ 3,044:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">consonant</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"aeiou"</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
Line 1,850 ⟶ 3,052:
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sort_columns</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;">over10sc</span><span style="color: #0000FF;">),</span><span style="color: #000000;">mostc</span><span style="color: #0000FF;">),{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</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;">"%d most consonant words: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<!--</langsyntaxhighlight>-->
<small>It does ''not'' escape me that the use of lambda expressions would make this ''slightly'' easier to write but ''much'' harder to comprehend...<br>
Admittedly adding a dozen or so line breaks to the above might (actually) improve matters, but I'm sure you'll cope somehow.</small>
Line 1,860 ⟶ 3,062:
=={{header|Python}}==
"Use Python," they say, "it's comprehensible," they say.
<langsyntaxhighlight lang="python">print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in
(x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)
for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]
if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)</langsyntaxhighlight>
{{out}}
<pre>9: comprehensible
Line 1,874 ⟶ 3,076:
 
The above is roughly equivalent to the following:
<langsyntaxhighlight lang="python">import re
from collections import defaultdict
 
Line 1,896 ⟶ 3,098:
print(f'{k}: {len(v)} words')
else:
print(f'{k}:', ' '.join(sorted(v)))</langsyntaxhighlight>
 
 
Or, aiming for asome littledegree moreof legibility, and showing results for two of the possible interpretations of an ambiguous task description:
<langsyntaxhighlight lang="python">'''Words using largest sets of consonants'''
 
from itertools import groupby
Line 1,993 ⟶ 3,195:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Words using largest sets of unique consonants:
Line 2,010 ⟶ 3,212:
Excluding words which reuse any consonants:
('comprehensible', 9)</pre>
 
===Using generator functions===
<syntaxhighlight lang="python">"""Find words which contain the most consonants. Requires Python >= 3.7."""
import fileinput
import textwrap
 
from itertools import groupby
from operator import itemgetter
 
from typing import Iterable
from typing import List
from typing import Tuple
 
 
VOWELS = frozenset("aeiou")
 
 
def read_words(path: str, encoding="utf-8") -> Iterable[str]:
for line in fileinput.input(path, encoding=encoding):
yield line.strip().lower()
 
 
def filter_words(words: Iterable[str]) -> Iterable[Tuple[str, int]]:
for word in words:
if len(word) <= 10:
continue
 
consonants = [c for c in word if c not in VOWELS]
if len(consonants) != len(set(consonants)):
continue
 
yield word, len(consonants)
 
 
def group_words(words: Iterable[Tuple[str, int]]) -> Iterable[Tuple[int, List[str]]]:
for count, group in groupby(
sorted(words, key=itemgetter(1), reverse=True),
key=itemgetter(1),
):
yield count, [word for word, _ in group]
 
 
def main() -> None:
all_words = read_words("unixdict.txt")
words = filter_words(all_words)
 
for count, word_group in group_words(words):
pretty_words = "\n".join(
textwrap.wrap(" ".join(word_group)),
)
plural = "s" if count > 1 else ""
print(
f"Found {len(word_group)} word{plural} "
f"with {count} unique consonants:\n{pretty_words}\n"
)
 
 
if __name__ == "__main__":
main()
</syntaxhighlight>
 
{{out}}
<pre style="font-size:85%;height:160ex">
Found 1 word with 9 unique consonants:
comprehensible
 
Found 39 words with 8 unique consonants:
administrable anthropology blameworthy bluestocking boustrophedon
bricklaying chemisorption christendom claustrophobia compensatory
comprehensive counterexample demonstrable disciplinary discriminable
geochemistry hypertensive indecipherable indecomposable indiscoverable
lexicography manslaughter misanthropic mockingbird monkeyflower
neuropathology paralinguistic pharmacology pitchblende playwriting
shipbuilding shortcoming springfield stenography stockholder
switchblade switchboard switzerland thunderclap
 
Found 130 words with 7 unique consonants:
acknowledge algorithmic alphanumeric ambidextrous amphibology
anchoritism atmospheric autobiography bakersfield bartholomew
bidirectional bloodstream boardinghouse cartilaginous centrifugal
chamberlain charlemagne clairvoyant combinatorial compensable
complaisant conflagrate conglomerate conquistador consumptive
convertible cosmopolitan counterflow countryside countrywide
declamatory decomposable decomposition deliquescent description
descriptive dilogarithm discernible discriminate disturbance
documentary earthmoving encephalitis endothermic epistemology
everlasting exchangeable exclamatory exclusionary exculpatory
explanatory extemporaneous extravaganza filamentary fluorescent
galvanometer geophysical glycerinate groundskeep herpetology
heterozygous homebuilding honeysuckle hydrogenate hyperboloid
impenetrable imperceivable imperishable imponderable impregnable
improvident improvisation incomparable incompatible incomputable
incredulity indefatigable indigestible indisputable inexhaustible
inextricable inhospitable inscrutable jurisdiction lawbreaking
leatherback leatherneck leavenworth logarithmic loudspeaking
maidservant malnourished marketplace merchandise methodology
misanthrope mitochondria molybdenite nearsighted obfuscatory
oceanography palindromic paradigmatic paramagnetic perfectible
phraseology politicking predicament presidential problematic
proclamation promiscuity providential purchasable pythagorean
quasiparticle quicksilver radiotelephone sedimentary selfadjoint
serendipity sovereignty subjunctive superfluity terminology
valedictorian valedictory verisimilitude vigilantism voluntarism
 
Found 152 words with 6 unique consonants:
aboveground advantageous adventurous aerodynamic anglophobia
anisotropic archipelago automorphic baltimorean beneficiary
borosilicate cabinetmake californium codetermine coextensive
comparative compilation composition confabulate confederate
considerate consolidate counterpoise countervail decisionmake
declamation declaration declarative deemphasize deformation
deliverance demountable denumerable deoxyribose depreciable
deprivation destabilize diagnosable diamagnetic dichotomize
dichotomous disambiguate eigenvector elizabethan encapsulate
enforceable ephemerides epidemiology evolutionary exceptional
exclamation exercisable exhaustible exoskeleton expenditure
experiential exploration fluorescein geometrician hemosiderin
hereinbelow hermeneutic heterogamous heterogeneous heterosexual
hexadecimal hexafluoride homebuilder homogeneity housebroken
icosahedral icosahedron impersonate imprecision improvisate
inadvisable increasable incredulous indivisible indomitable
ineradicable inescapable inestimable inexcusable infelicitous
informatica informative inseparable insuperable ionospheric
justiciable kaleidescope kaleidoscope legerdemain liquefaction
loudspeaker machinelike magisterial maladaptive mantlepiece
manufacture masterpiece meetinghouse meteorology minesweeper
ministerial multifarious musculature observation patrimonial
peasanthood pediatrician persecution pertinacious picturesque
planetarium pleistocene pomegranate predominate prejudicial
prohibition prohibitive prolegomena prosecution provisional
provocation publication quasiperiodic reclamation religiosity
renegotiable residential rooseveltian safekeeping saloonkeeper
serviceable speedometer subrogation sulfonamide superficial
superlative teaspoonful trapezoidal tridiagonal troublesome
vainglorious valediction venturesome vermiculite vocabularian
warehouseman wisenheimer
 
Found 22 words with 5 unique consonants:
acquisition acquisitive acrimonious ceremonious deleterious
diatomaceous egalitarian equilibrate equilibrium equinoctial
expeditious hereinabove homogeneous inequitable injudicious
inoperative inquisitive interviewee leeuwenhoek onomatopoeic
radioactive requisition
 
Found 3 words with 4 unique consonants:
audiovisual bourgeoisie onomatopoeia
</pre>
 
=={{header|R}}==
Far and away the hardest part of this task is filtering down the dict until it only contains words with no repeated consonants. If we only had to find the word with the most consonants, this would be easy.
<langsyntaxhighlight lang="rsplus">dict <- scan("https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt", what = character())
dictBig <- dict[nchar(dict) > 10]
consonants <- letters[!letters %in% c("a", "e", "i", "o", "u")]
Line 2,024 ⟶ 3,373:
cat("Biggest:", paste(biggestWords(0), collapse = ", "),
"\n \n Second biggest:", paste(biggestWords(1), collapse = ", "),
"\n \n Third biggest:", paste(biggestWords(2), collapse = ", "))</langsyntaxhighlight>
{{out}}
<pre>Read 25104 items
Line 2,035 ⟶ 3,384:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
(define (consonant-count s)
Line 2,051 ⟶ 3,400:
group-with-max-consonant-count
(printf "with: ~a consonants in each word"
(group-count group-with-max-consonant-count)))</langsyntaxhighlight>
 
{{out}}
Line 2,062 ⟶ 3,411:
Hmm. Depends on how you define "most".
 
<syntaxhighlight lang="raku" perl6line>unit sub MAIN ($min = 11);
my @vowel = <a e i o u>;
my $vowel = rx/ @vowel /;
Line 2,076 ⟶ 3,425:
say "\nNumber found, ratio and list of words with the highest ratio of unique, unrepeated consonants to vowels:";
say +.value, ' @ ', $_ for 'unixdict.txt'.IO.slurp.words.grep( {.chars >= $min and so all(.comb.Bag{@consonant}) <= 1} )
.classify( { +.comb(/$vowel/) ?? (+.comb(/$consonant/) / +.comb(/$vowel/) ) !! Inf } ).sort(-*.key).head(3);</langsyntaxhighlight>
{{out}}
<pre style="max-width:100%;">Minimum characters in a word: 11
Line 2,107 ⟶ 3,456:
 
It also allows the minimum length to be specified on the command line (CL) as well as the dictionary file identifier.
<langsyntaxhighlight lang="rexx">/*REXX pgm finds words (within an identified dict.) which contain the most consonants.*/
parse arg minl iFID . /*obtain optional arguments from the CL*/
if minl=='' | minl=="," then minl= 11 /*Not specified? Then use the default.*/
Line 2,150 ⟶ 3,499:
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1)</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
 
Line 2,524 ⟶ 3,873:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 2,591 ⟶ 3,940:
next
return aList
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,649 ⟶ 3,998:
 
done...
</pre>
 
=={{header|RPL}}==
The only way to use <code>unixdict.txt</code> as input is to convert it into a list of 25104 strings. Fortunately, emulators can handle such a big data structure in RAM.
{{works with|Halcyon Calc|4.2.7}}
≪ → words ncons
≪ { }
1 words EVAL SIZE '''FOR''' j
words j GET
'''IF''' DUP SIZE 10 ≤ '''THEN''' DROP '''ELSE'''
{ 21 } 0 CON
1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB
NUM R→B #DFh AND B→R CHR
'''IF''' "BCDFGHJKLMNPQRSTVWXYZ" SWAP POS '''THEN'''
LAST DUP2 GET 1 + PUT END
'''NEXT'''
1 SF
1 21 '''FOR''' j
'''IF''' DUP j GET 1 > '''THEN''' 1 CF 21 'j' STO '''END'''
NEXT
'''IF''' DUP 1 CON DOT ncons < 1 FC? OR '''THEN''' DROP '''ELSE''' + '''END'''
'''END NEXT'''
≫ ≫ ‘<span style="color:blue">CONSONANTS</span>’ STO
 
'Unixdict' 9 <span style="color:blue">CONSONANTS</span>
'Unixdict' 8 <span style="color:blue">CONSONANTS</span>
{{out}}
<pre>
2: { "comprehensible" }
1: { "administrable" "anthropology" "blameworthy" "bluestocking" "boustrophedon" "bricklaying" "chemisorption" "christendom" "claustrophobia" "compensatory" "comprehensive" "counterexample" "demonstrable" "disciplinary" "discriminable" "geochemistry" "hypertensive" "indecipherable" "indecomposable" "indiscoverable" "lexicography" "manslaughter" "misanthropic" "mockingbird" "monkeyflower" "neuropathology" "paralinguistic" "pharmacology" "pitchblende" "playwriting" "shipbuilding" "shortcoming" "springfield" "stenography" "stockholder" "switchblade" "switchboard" "switzerland" "thunderclap" }
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">filtered = File.open("unixdict.txt").each( chomp: true).select do |word|
next unless word.size > 10
cons = word.delete('aeiou')
cons.chars.uniq.join == cons
end
 
grouped = filtered.group_by{|word| word.count('^aeiou')}
grouped.sort_by{|k,v| -k}.each do |chunk|
puts"\n#{chunk.first} consonants (#{chunk.last.size}):"
puts chunk.last.first(10)
puts "..." if chunk.last.size > 10
end
</syntaxhighlight>
{{out}}
<pre>9 consonants (1):
comprehensible
 
8 consonants (39):
administrable
anthropology
blameworthy
bluestocking
boustrophedon
bricklaying
chemisorption
christendom
claustrophobia
compensatory
...
 
7 consonants (130):
acknowledge
algorithmic
alphanumeric
ambidextrous
amphibology
anchoritism
atmospheric
autobiography
bakersfield
bartholomew
...
 
6 consonants (152):
aboveground
advantageous
adventurous
aerodynamic
anglophobia
anisotropic
archipelago
automorphic
baltimorean
beneficiary
...
 
5 consonants (22):
acquisition
acquisitive
acrimonious
ceremonious
deleterious
diatomaceous
egalitarian
equilibrate
equilibrium
equinoctial
...
 
4 consonants (3):
audiovisual
bourgeoisie
onomatopoeia
</pre>
 
=={{header|TypeScript}}==
<syntaxhighlight lang="typescript">
import { readFileSync } from 'node:fs';
 
const words = readFileSync('unixdict.txt', { encoding: 'utf-8' })
.split('\n')
.filter(word => word.length > 10)
.map(word => ({ word, wordWithoutVowels: word.replaceAll(/[aeiou]/g, '') }))
.map(data => ({ ...data, numUniqueConsonants: new Set(data.wordWithoutVowels).size }))
.filter(({ wordWithoutVowels, numUniqueConsonants }) => wordWithoutVowels.length === numUniqueConsonants);
 
const groupedWords = groupBy(words, ({ numUniqueConsonants }) => numUniqueConsonants);
 
const countsDescending = Array.from(groupedWords.keys()).sort((a, b) => b - a);
 
for (const count of countsDescending) {
const words = groupedWords.get(count)!.map(data => data.word);
const output = words.length <= 30 ? words.join(' ') : `${words.length} words`;
console.log(`${count}: ${output}`);
}
 
function groupBy<T, Group>(items: T[], getGroup: (item: T) => Group) {
const result = new Map<Group, T[]>();
 
for (const item of items) {
const group = getGroup(item);
let array = result.get(group);
if (!array) {
array = [];
result.set(group, array);
}
 
array.push(item);
}
 
return result;
}
</syntaxhighlight>
{{out}}
<pre>
9: comprehensible
8: 39 words
7: 130 words
6: 152 words
5: acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition
4: audiovisual bourgeoisie onomatopoeia
</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
 
dim b(25) 'strings with lists of words
dim c(128)
'use regexp to count consonants
with new regexp
.pattern="([^aeiou])"
.global=true
for each i in a
if len(trim(i))>10 then
set matches= .execute(i) 'matches.count has the nr of consonants
rep=false
for each m in matches 'remove words with repeated consonants
x=asc(m)
c(x)=c(x)+1
if c(x)>1 then rep=true :exit for
next
erase c
if not rep then 'add item to its list
x1=matches.count
b(x1)=b(x1)&" "&i 'create strings of words with same nr
end if
end if
next
end with
 
'print strings with most consonants first
for i=25 to 0 step -1
if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf
next
</syntaxhighlight>
{{out}}
<pre>
9 comprehensible
 
8 administrable anthropology blameworthy bluestocking boustrophedon bricklaying chemisorption christendom claustrophobia compensatory comprehensive counterexample demonstrable disciplinary discriminable geochemistry hypertensive indecipherable indecomposable indiscoverable lexicography manslaughter misanthropic mockingbird monkeyflower neuropathology paralinguistic pharmacology pitchblende playwriting shipbuilding shortcoming springfield stenography stockholder switchblade switchboard switzerland thunderclap
 
7 acknowledge algorithmic alphanumeric ambidextrous amphibology anchoritism atmospheric autobiography bakersfield bartholomew bidirectional bloodstream boardinghouse cartilaginous centrifugal chamberlain charlemagne clairvoyant combinatorial compensable complaisant conflagrate conglomerate conquistador consumptive convertible cosmopolitan counterflow countryside countrywide declamatory decomposable decomposition deliquescent description descriptive dilogarithm discernible discriminate disturbance documentary earthmoving encephalitis endothermic epistemology everlasting exchangeable exclamatory exclusionary exculpatory explanatory extemporaneous extravaganza filamentary fluorescent galvanometer geophysical glycerinate groundskeep herpetology heterozygous homebuilding honeysuckle hydrogenate hyperboloid impenetrable imperceivable .....
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "io" for File
{{libheader|Wren-seq}}
<lang ecmascript>import "io./fmt" for FileFmt
import "/fmt" for Fmt
import "/seq" for Lst
 
var wordList = "unixdict.txt" // local copy
Line 2,690 ⟶ 4,242:
var s = (count == 1) ? "" : "s"
System.print("%(count) word%(s) found with %(i) unique consonants:")
for (chunk in Lst.chunks(wordGroups[i], 5)) Fmt.printtprint("$-14s", chunkwordGroups[i], 5)
System.print()
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,783 ⟶ 4,335:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">string 0; \use zero-terminated strings
int MaxCon, Con, Set, I, Ch;
char Word(25), MaxWord(25);
Line 2,808 ⟶ 4,360:
until Ch = EOF;
Text(0, MaxWord);
]</langsyntaxhighlight>
 
{{out}}
9,476

edits