Find words which contain the most consonants
- Task
Use the dictionary unixdict.txt
Find the words which contains most consonants, but each consonant should appear only once in a word.
The length of any word shown should have a length > 10.
- Metrics
- Counting
- Word frequency
- Letter frequency
- Jewels and stones
- I before E except after C
- Bioinformatics/base count
- Count occurrences of a substring
- Count how many vowels and consonants occur in a string
- Remove/replace
- XXXX redacted
- Conjugate a Latin verb
- Remove vowels from a string
- String interpolation (included)
- Strip block comments
- Strip comments from a string
- Strip a set of characters from a string
- Strip whitespace from a string -- top and tail
- Strip control codes and extended characters from a string
- Anagrams/Derangements/shuffling
- Word wheel
- ABC problem
- Sattolo cycle
- Knuth shuffle
- Ordered words
- Superpermutation minimisation
- Textonyms (using a phone text pad)
- Anagrams
- Anagrams/Deranged anagrams
- Permutations/Derangements
- Find/Search/Determine
- ABC words
- Odd words
- Word ladder
- Semordnilap
- Word search
- Wordiff (game)
- String matching
- Tea cup rim text
- Alternade words
- Changeable words
- State name puzzle
- String comparison
- Unique characters
- Unique characters in each string
- Extract file extension
- Levenshtein distance
- Palindrome detection
- Common list elements
- Longest common suffix
- Longest common prefix
- Compare a list of strings
- Longest common substring
- Find common directory path
- Words from neighbour ones
- Change e letters to i in words
- Non-continuous subsequences
- Longest common subsequence
- Longest palindromic substrings
- Longest increasing subsequence
- Words containing "the" substring
- Sum of the digits of n is substring of n
- Determine if a string is numeric
- Determine if a string is collapsible
- Determine if a string is squeezable
- Determine if a string has all unique characters
- Determine if a string has all the same characters
- Longest substrings without repeating characters
- Find words which contains all the vowels
- Find words which contain the most consonants
- Find words which contains more than 3 vowels
- Find words whose first and last three letters are equal
- Find words with alternating vowels and consonants
- Formatting
- Substring
- Rep-string
- Word wrap
- String case
- Align columns
- Literals/String
- Repeat a string
- Brace expansion
- Brace expansion using ranges
- Reverse a string
- Phrase reversals
- Comma quibbling
- Special characters
- String concatenation
- Substring/Top and tail
- Commatizing numbers
- Reverse words in a string
- Suffixation of decimal numbers
- Long literals, with continuations
- Numerical and alphabetical suffixes
- Abbreviations, easy
- Abbreviations, simple
- Abbreviations, automatic
- Song lyrics/poems/Mad Libs/phrases
- Mad Libs
- Magic 8-ball
- 99 bottles of beer
- The Name Game (a song)
- The Old lady swallowed a fly
- The Twelve Days of Christmas
- Tokenize
- Text between
- Tokenize a string
- Word break problem
- Tokenize a string with escaping
- Split a character string based on change of character
- Sequences
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(‘ ’))
- Output:
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
Action!
In the following solution the input file 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.
CHAR ARRAY line(256)
BYTE FUNC ConsonantsCount(CHAR ARRAY word)
BYTE len,i,c,count
BYTE ARRAY chars(128)
len=word(0)
IF len<=10 THEN RETURN (0) FI
SetBlock(chars,128,0)
count=0
FOR i=1 TO len
DO
c=word(i)
IF c#'a AND c#'e AND c#'i AND c#'o AND c#'u THEN
IF chars(c) THEN RETURN (0) FI
chars(c)=1
count==+1
FI
OD
RETURN (count)
BYTE FUNC FindMostConsonants(CHAR ARRAY fname)
BYTE max,count,dev=[1]
max=0
Close(dev)
Open(dev,fname,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
count=ConsonantsCount(line)
IF max<count THEN
max=count
FI
OD
Close(dev)
RETURN (max)
PROC FindWords(CHAR ARRAY fname BYTE n)
BYTE count,dev=[1]
Close(dev)
Open(dev,fname,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
count=ConsonantsCount(line)
IF count=n THEN
Print(line) Put(32)
FI
OD
Close(dev)
PutE() PutE()
RETURN
PROC Main()
CHAR ARRAY fname="H6:UNIXDICT.TXT"
BYTE i,max
PrintE("Finding the most consonants...")
PutE()
max=FindMostConsonants(fname)
i=max
WHILE i>=max-1
DO
PrintF("%B consonants:%E",i)
FindWords(fname,i)
i==-1
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
Finding the most consonants... 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
Ada
with Ada.Text_Io;
with Ada.Strings.Fixed;
with Ada.Containers.Indefinite_Vectors;
procedure Most_Consonants is
use Ada.Text_Io;
package String_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => String);
function Is_Vowel (Letter : Character) return Boolean
is (Ada.Strings.Fixed.Index ("aeiou", "" & Letter) /= 0);
type Consonant_Count is range 0 .. 15;
Filename : constant String := "unixdict.txt";
File : File_Type;
Words : array (Consonant_Count) of String_Vectors.Vector;
begin
Open (File, In_File, Filename);
while not End_Of_File (File) loop
declare
Word : constant String := Get_Line (File);
Found : array (Character) of Boolean := (others => False);
Conso : Consonant_Count := 0;
Bad : Boolean := False;
begin
for Letter of Word loop
if Is_Vowel (Letter) then
null;
elsif Found (Letter) then
Bad := True;
else
Found (Letter) := True;
Conso := Conso + 1;
end if;
end loop;
if not Bad and Word'Length > 10 then
Words (Conso).Append (Word);
end if;
end;
end loop;
Close (File);
for Cons in Words'Range loop
if not Words (Cons).Is_Empty then
Put (Cons'Image & " consonants: ");
Put (Words (Cons).Length'Image & " words");
New_Line;
end if;
declare
Column : Natural := 0;
Image : String (1 .. 15);
begin
for Word of Words (Cons) loop
Ada.Strings.Fixed.Move (Word, Image);
Put (Image);
Column := Column + 1;
if Column mod 8 = 0 then
New_Line;
end if;
end loop;
end;
if not Words (Cons).Is_Empty then
New_Line;
end if;
end loop;
end Most_Consonants;
- Output:
4 consonants: 3 words audiovisual bourgeoisie onomatopoeia 5 consonants: 22 words acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition 6 consonants: 152 words 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 7 consonants: 130 words 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 8 consonants: 39 words 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 9 consonants: 1 words comprehensible
ALGOL 68
Note that the sources of files.incl.a68 and sort.incl.a68 are available on Rosetta Code on separate pages - see the above links.
BEGIN # find words longer than 10 characters that contain unique consonants #
# and sort them by the number of consonants they contain #
PR read "files.incl.a68" PR # include file utilities #
PR read "sort.incl.a68" PR # include sort utilities #
# 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 max length := 0;
# returns TRUE if word is longer than 10 characters and contains #
# consonants that only occur once, FALSE otherwise #
# if the result is TRUE, the word is added to words, prefixed with the #
# max abs char complement of the number of consonants #
# count so far will contain the number of such words found so far #
# max length is set to the length of the longest such word encountered #
PROC store unique consonant words = ( STRING word, INT count so far )BOOL:
IF INT w length = LENGTH word;
w length <= 10
THEN FALSE # word is too short #
ELIF INT consonants = UNIQUECONSONANTS word;
consonants <= 0
THEN FALSE # word has non-unique consonents or no consonants #
ELSE # 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[ count so far + 1 ] := REPR ( max abs char - consonants ) + word;
IF w length > max length THEN max length := w length FI;
TRUE
FI # store unique consonant words # ;
IF INT w count = "unixdict.txt" EACHLINE store unique consonant words;
w count < 0
THEN print( ( "Unable to open unixdict.txt", newline ) )
ELSE words QUICKSORT ELEMENTS( 1, w count ); # sort the words #
INT prev count := 0; # display the words #
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;
TO max length - w length DO print( ( " " ) ) OD;
print( ( " ", word ) );
IF NOT ( need nl := ( p count +:= 1 ) MOD 5 /= 0 ) THEN
print( ( newline ) )
FI
OD
FI
END
- Output:
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
ALGOL W
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 );
% structure to hold lists of words %
record WordList ( reference(WordListElement) first, last );
% lists of words indexed by number of consonants %
reference(WordList) array words ( 1 :: 32 );
string(32) word;
integer aCode, aPos, ePos, iPos, oPos, uPos;
for wPos := 1 until 32 do words( wPos ) := null;
% allow the program to continue after reaching end-of-file %
ENDFILE := EXCEPTION( false, 1, 0, false, "EOF" );
% handle the input %
aCode := decode( "a" );
aPos := 0;
ePos := decode( "e" ) - aCode;
iPos := decode( "i" ) - aCode;
oPos := decode( "o" ) - aCode;
uPos := decode( "u" ) - aCode;
readcard( word );
while not XCPNOTED(ENDFILE) do begin
integer len;
len := 31;
while len > 0 and word( len // 1 ) = " " do len := len - 1;
len := len + 1;
if len > 10 then begin % word is at least 11 characters long %
logical noRepeatedletters;
integer consonants;
integer array letterCount ( 0 :: 25 );
for cPos := 0 until 25 do letterCount( cPos ) := 0;
for cPos := 0 until len do begin
integer c;
c := decode( word( cPos // 1 ) ) - aCode;
if c >= 0 and c <= 25 then % have a letter % letterCount( c ) := letterCount( c ) + 1;
end for_cPos;
% reset the vowel counts %
letterCount( aPos ) := letterCount( ePos ) := letterCount( iPos ) := letterCount( oPos ) := letterCOunt( uPos ) := 0;
% check at most 1 of each letter and at least one non-vowel %
noRepeatedletters := true;
consonants := 0;
for cPos := 0 until 25 do begin
if letterCount( cPos ) = 1 then consonants := consonants + 1
else if letterCount( cPos ) > 1 then begin
% a repeated letter %
noRepeatedletters := false;
goto endLookFOrRepeatedLetters;
end if_single_letter__repeated_letter
end for_cPos ;
endLookFOrRepeatedLetters:
if consonants > 0 and noRepeatedLetters then begin
% have a word with more than 10 characters that has no repeated consonants %
if words( consonants ) not = null then begin
% second or subsequent word with this many consonants %
last( words( consonants ) ) := next( last( words( consonants ) ) ) := WordListElement( word, null );
end
else begin
% first word with this many consonants %
words( consonants ) := WordList( WordListElement( word, null ), null );
last( words( consonants ) ) := first( words( consonants ) )
end if_words_consonants_ne_null__
end if_have_no_repeated_consonants
end if_len_gt_10 ;
readcard( word );
end while_not_eof ;
% show the words %
for wPos := 32 step -1 until 1 do begin
if words( wPos ) not = null then begin
% have words with wPos consonants %
reference(WordListElement) rWord;
integer wNumber;
write( i_w := 1, s_w := 0,"Words with ", wPos, " consonants:" );
rWord := first( words( wPos ) );
wNumber := 0;
while rWord not = null do begin
if wNumber rem 5 = 0
then write( " ", w( rWord )( 0 // 18 ) )
else writeon( w( rWord )( 0 // 18 ) )
;
wNumber := wNUmber + 1;
rWord := next( rWord )
end while_rWord_ne_null
end if_words_wPos_ne_null
end for_wPos
end.
- Output:
Words with 9 consonants: comprehensible Words with 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 Words with 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 Words with 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 Words with 5 consonants: acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition Words with 4 consonants: audiovisual bourgeoisie onomatopoeia
Arturo
words: read.lines relative "unixdict.txt"
vowels: ["a" "e" "i" "o" "u"]
nofConsonants: function [w][
cons: (split w) -- vowels
if? cons = unique cons -> return size cons
else -> return 0
]
freqs: array.of: 20 []
loop words 'word [
if 10 < size word [
noc: nofConsonants word
if noc > 0 [
freqs\[noc]: freqs\[noc] ++ word
]
]
]
loop.with:'i reverse freqs 'freq [
if not? empty? freq [
print "-----------------------------------------------"
print ~"Found |size freq| words with |dec 20-i| different consonants"
print "-----------------------------------------------"
print join.with:"\n" freq
print ""
]
]
- Output:
----------------------------------------------- Found 1 words with 9 different consonants ----------------------------------------------- comprehensible ----------------------------------------------- Found 39 words with 8 different 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 different 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 different 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 different 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 different consonants ----------------------------------------------- audiovisual bourgeoisie onomatopoeia
AutoHotkey
FileRead, db, % A_Desktop "\unixdict.txt"
vowels := ["a", "e", "i", "o", "u"]
oRes := []
for i, word in StrSplit(db, "`n", "`r")
{
if StrLen(word) < 11
continue
tWord := word
for j, v in vowels
word := StrReplace(word, v)
if !(word ~= "(.)(?=.*?\1)")
oRes[0-StrLen(word), tword] := 1 ; result .= tword "`n"
}
for l, obj in oRes
{
result .= 0-l " Unique consonants, word count: " obj.Count() "`n"
for word in obj
result .= word (!Mod(A_Index, 9) ? "`n" : "`t")
result .= "`n`n"
}
MsgBox, 262144, , % result
- Output:
9 Unique consonants, word count: 1 comprehensible 8 Unique consonants, word count: 39 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 Unique consonants, word count: 130 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 Unique consonants, word count: 152 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 Unique consonants, word count: 22 acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition 4 Unique consonants, word count: 3 audiovisual bourgeoisie onomatopoeia
AWK
# syntax: GAWK -f FIND_WORDS_WHICH_CONTAINS_MOST_CONSONANTS.AWK unixdict.txt
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
a2z = "abcdefghijklmnopqrstuvwxyz"
gsub(/[aeiou]/,"",a2z) # remove vowels
leng = length(a2z)
}
{ if (length($0) <= 10) {
next
}
consonants = 0
for (i=1; i<=leng; i++) {
c = substr(a2z,i,1)
if (gsub(c,"&",$0) > 1) {
next
}
if (gsub(c,"&",$0) == 1) {
consonants++
}
}
arr[consonants][$0] = ""
words++
}
END {
show = 4
PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
for (i in arr) {
printf("%1d %3d ",i,length(arr[i]))
shown = 0
for (j in arr[i]) {
if (++shown <= show) {
printf("%s ",j)
}
}
printf("%s\n",(length(arr[i])>show)?(" ... "j):"")
}
printf("%5d words\n",words)
exit(0)
}
- Output:
4 3 audiovisual bourgeoisie onomatopoeia 5 22 acquisition acquisitive acrimonious ceremonious ... requisition 6 152 aboveground advantageous adventurous aerodynamic ... wisenheimer 7 130 acknowledge algorithmic alphanumeric ambidextrous ... voluntarism 8 39 administrable anthropology blameworthy bluestocking ... thunderclap 9 1 comprehensible 347 words
C++
#include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
// Returns number of consonants in the word if they are all unique,
// otherwise zero.
size_t consonants(const std::string& word) {
std::bitset<26> bits;
size_t bit = 0;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
if (ch < 'a' || ch > 'z')
continue;
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
bit = ch - 'a';
if (bits.test(bit))
return 0;
bits.set(bit);
break;
}
}
return bits.count();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
std::map<size_t, std::vector<std::string>, std::greater<int>> map;
while (getline(in, word)) {
if (word.size() <= 10)
continue;
size_t count = consonants(word);
if (count != 0)
map[count].push_back(word);
}
const int columns = 4;
for (const auto& p : map) {
std::cout << p.first << " consonants (" << p.second.size() << "):\n";
int n = 0;
for (const auto& word : p.second) {
std::cout << std::left << std::setw(18) << word;
++n;
if (n % columns == 0)
std::cout << '\n';
}
if (n % columns != 0)
std::cout << '\n';
std::cout << '\n';
}
return EXIT_SUCCESS;
}
- Output:
9 consonants (1): comprehensible 8 consonants (39): 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 (130): 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 (152): 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 (22): acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition 4 consonants (3): audiovisual bourgeoisie onomatopoeia
CLU
% If a word has no repeated consonants, return the amount
% of consonants. If it does have repeated consonants, return
% -1.
consonants = proc (word: string) returns (int)
own vowels: string := "aeiou" % shorter than listing all consonants
letters: array[int] := array[int]$fill(0,26,0)
for c: char in string$chars(word) do
if string$indexc(c,vowels) ~= 0 then continue end
if c<'a' cor c>'z' then continue end
i: int := char$c2i(c) - char$c2i('a')
letters[i] := letters[i] + 1
end
total: int := 0
for i: int in array[int]$elements(letters) do
if i>1 then return(-1) end
total := total + i
end
return(total)
end consonants
start_up = proc ()
dictfile: file_name := file_name$parse("unixdict.txt")
dict: stream := stream$open(dictfile, "read")
words: array[array[string]] :=
array[array[string]]$fill_copy(0,10,array[string]$[])
while true do
word: string := stream$getl(dict)
if string$size(word) <= 10 then continue end
n: int := consonants(word)
array[string]$addh(words[n], word)
except when bounds: end
end
except when end_of_file:
stream$close(dict)
end
po: stream := stream$primary_output()
for word_list: array[string] in array[array[string]]$elements(words) do
if array[string]$empty(word_list) then continue end
size: int := array[string]$size(word_list)
cons: int := consonants(array[string]$bottom(word_list))
stream$putl(po, int$unparse(cons) || " consonants - "
|| int$unparse(size) || " words:")
col: int := 0
for word: string in array[string]$elements(word_list) do
stream$putleft(po, word, 20)
col := col + 1
if col = 4 then
stream$putl(po, "")
col := 0
end
end
if col ~= 0 then stream$putl(po, "") end
stream$putl(po, "")
end
end start_up
- Output:
4 consonants - 3 words: audiovisual bourgeoisie onomatopoeia 5 consonants - 22 words: acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition 6 consonants - 152 words: 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 7 consonants - 130 words: 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 8 consonants - 39 words: 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 9 consonants - 1 words: comprehensible
Delphi
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.
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.
- Output:
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
DuckDB
# Helper functions
create or replace function consonants(word) as
regexp_extract_all(word, '[bcdfghjklmnpqrstvwxyz]');
create or replace function all_consonants_are_singletons(word) as (
select histogram(c).map_values().list_filter(x -> x > 1).length() = 0
from (select unnest(regexp_extract_all(word, '[bcdfghjklmnpqrstvwxyz]')) as c)
);
# Read a pertinent selection from unixdict.txt
create or replace table unixdict_selection (word VARCHAR PRIMARY KEY) ;
insert into unixdict_selection
select lower(word)
from read_csv('unixdict.txt', header=false, sep='\t', columns= {'word': 'VARCHAR'})
where length(word)>10
and all_consonants_are_singletons(word);
To find the single-consonant words with the max number of consonants:
select max_by(word, nc) from (select word, length(consonants(word)) as nc from unixdict_selection); ┌──────────────────┐ │ max_by(word, nc) │ │ varchar │ ├──────────────────┤ │ comprehensible │ └──────────────────┘
Statistical synopsis
select length(consonants(word)) as nc, array_agg(word) as words, length(words) as n from unixdict_selection group by nc order by nc desc ; ┌───────┬────────────────────────────────────────────────────────────────────────────────────┬───────┐ │ nc │ words │ n │ │ int64 │ varchar[] │ int64 │ ├───────┼────────────────────────────────────────────────────────────────────────────────────┼───────┤ │ 9 │ [comprehensible] │ 1 │ │ 8 │ [administrable, anthropology, blameworthy, bluestocking, boustrophedon, bricklay… │ 39 │ │ 7 │ [acknowledge, algorithmic, alphanumeric, ambidextrous, amphibology, anchoritism,… │ 130 │ │ 6 │ [aboveground, advantageous, adventurous, aerodynamic, anglophobia, anisotropic, … │ 152 │ │ 5 │ [acquisition, acquisitive, acrimonious, ceremonious, deleterious, diatomaceous, … │ 22 │ │ 4 │ [audiovisual, bourgeoisie, onomatopoeia] │ 3 │ └───────┴────────────────────────────────────────────────────────────────────────────────────┴───────┘
EasyLang
func cntcons s$ .
len a[] 26
for c$ in strchars s$
if strpos "aeiou" c$ = 0
c = strcode c$ - 96
if c >= 1
a[c] = 1
.
.
.
for h in a[]
s += h
.
return s
.
repeat
s$ = input
until s$ = ""
if len s$ >= 11
cnt = cntcons s$
if cnt >= max
if cnt > max
max = cnt
wrds$[] = [ ]
.
wrds$[] &= s$
.
.
.
print wrds$[] & " (" & max & ")"
#
# the content of unixdict.txt
input_data
10th
.
1st
ackerman
ackley
acknowledge
bremsstrahlung
handicraftsmen
F#
// 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)
- Output:
(9, seq ["comprehensible"])
Factor
USING: assocs formatting io.encodings.ascii io.files kernel math
prettyprint prettyprint.config sequences sets sets.extras ;
FROM: namespaces => set ;
"unixdict.txt" ascii file-lines
[ length 10 > ] filter
[ "aeiou" without all-unique? ] filter dup length
"Found %d words with unique consonants (length > 10).\n" printf
[ [ "aeiou" member? not ] count ] collect-by >alist reverse
6 length-limit set 100 margin set .
- Output:
Found 347 words with unique consonants (length > 10). { { 9 V{ "comprehensible" } } { 8 V{ "administrable" "anthropology" "blameworthy" "bluestocking" "boustrophedon" ~34 more~ } } { 7 V{ "acknowledge" "algorithmic" "alphanumeric" "ambidextrous" "amphibology" ~125 more~ } } { 6 V{ "aboveground" "advantageous" "adventurous" "aerodynamic" "anglophobia" ~147 more~ } } { 5 V{ "acquisition" "acquisitive" "acrimonious" "ceremonious" "deleterious" ~17 more~ } } { 4 V{ "audiovisual" "bourgeoisie" "onomatopoeia" } } }
Forth
: vowel? ( c -- t/f )
case
'a' of true endof
'e' of true endof
'i' of true endof
'o' of true endof
'u' of true endof
false swap
endcase ;
: consonant? ( c -- t/f )
dup 'a' 'z' 1+ within if
vowel? invert
else
drop false
then ;
: consonants ( addr u -- count )
0 0 { count unique }
0 do
dup c@ dup consonant? if
'a' - 1 swap lshift dup
unique and if
2drop 0 unloop exit
endif
unique or to unique
count 1+ to count
else
drop
endif
1+
loop
drop
count ;
256 constant max-line
create line-buffer max-line 2 + allot
20 constant max-consonant
create word-list-heads max-consonant cells allot
create word-list-tails max-consonant cells allot
create word-list-counts max-consonant cells allot
: word-list-head ( n -- addr )
word-list-heads swap cells + ;
: word-list-tail ( n -- addr )
word-list-tails swap cells + ;
: word-list-count ( n -- addr )
word-list-counts swap cells + ;
: word-list-init
word-list-heads max-consonant cells erase
word-list-counts max-consonant cells erase
max-consonant 0 do
i word-list-head i word-list-tail !
loop ;
: word-list-append { addr length index -- }
0 here !
length here cell+ !
here index word-list-tail @ !
here index word-list-tail !
2 cells allot
addr here length cmove
length allot align
1 index word-list-count +! ;
: word-list-print { index -- }
index word-list-count @
dup 0= if drop exit then
index . ." consonants (" 1 .r ." ):" cr
index word-list-head @
begin
dup 0 <>
while
dup 2 cells +
over cell+ @
type cr
@
repeat
drop cr ;
: main
word-list-init
0 { fd-in }
s" unixdict.txt" r/o open-file throw to fd-in
begin
line-buffer max-line fd-in read-line throw
while
dup 10 > if
line-buffer swap 2dup consonants
dup 0= if
drop 2drop
else
word-list-append
then
else
drop
then
repeat
drop
fd-in close-file throw
max-consonant 0 do
max-consonant i - 1- word-list-print
loop ;
main
bye
- Output:
9 consonants (1): comprehensible 8 consonants (39): 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 (130): 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 (152): 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 (22): acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition 4 consonants (3): audiovisual bourgeoisie onomatopoeia
FreeBASIC
function uniq_cons( s as string ) as integer
dim letter( 1 to 26 ) as boolean
dim as uinteger n, i
dim as string*1 c
for i = 1 to len(s)
c = lcase(mid(s,i,1))
if c = "a" or c = "e" or c = "i" or c = "o" or c = "u" then continue for
if letter(asc(c)-97)=true then return 0
letter(asc(c)-97)=true
n+=1
next i
return n
end function
dim as string ln
dim as integer u
open "unixdict.txt" for input as #1
while not eof(1)
line input #1, ln
if len(ln)<11 then continue while
u=uniq_cons(ln)
if u>0 then print ln;": ";u;" distint consonants"
wend
close #1
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
- Output:
comprehensible
Go
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func contains(list []int, value int) bool {
for _, v := range list {
if v == value {
return true
}
}
return false
}
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 10 {
words = append(words, s)
}
}
vowelIndices := []int{0, 4, 8, 14, 20}
wordGroups := make([][]string, 12)
for _, word := range words {
letters := make([]int, 26)
for _, c := range word {
index := c - 97
if index >= 0 && index < 26 {
letters[index]++
}
}
eligible := true
uc := 0 // number of unique consonants
for i := 0; i < 26; i++ {
if !contains(vowelIndices, i) {
if letters[i] > 1 {
eligible = false
break
} else if letters[i] == 1 {
uc++
}
}
}
if eligible {
wordGroups[uc] = append(wordGroups[uc], word)
}
}
for i := 11; i >= 0; i-- {
count := len(wordGroups[i])
if count > 0 {
s := "s"
if count == 1 {
s = ""
}
fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i)
for j := 0; j < count; j++ {
fmt.Printf("%-15s", wordGroups[i][j])
if j > 0 && (j+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println()
if count%5 != 0 {
fmt.Println()
}
}
}
}
- Output:
Same as Wren example.
Haskell
{-# LANGUAGE LambdaCase #-}
-- Given a list of words on stdin, write to stdout the set of words having the
-- greatest number of distinct, English consonants. In any given word, each
-- consonant may appear only once. We consider Y to always be a consonant.
import Data.Bifunctor (first)
import Data.Char (toUpper)
import Data.Function (on)
import Data.List ((\\), groupBy, intersect, nub, sortOn)
import Data.Ord (Down(..))
-- The consonants.
consonants :: String
consonants = cons ++ map toUpper cons
where cons = ['a'..'z'] \\ "aeiou"
-- Only the consonants in the argument.
onlyConsonants :: String -> String
onlyConsonants = (`intersect` consonants)
-- The list of all strings having the greatest number of distinct consonants.
mostDistinctConsonants :: [String] -> [String]
mostDistinctConsonants = map snd
. head'
. groupBy ((==) `on` fst)
. sortOn (Down . fst)
. map (first length)
. filter (allDistinct . fst)
. map (\s -> (onlyConsonants s, s))
where head' = \case { [] -> []; (xs:_) -> xs; }
allDistinct s = s == nub s
main :: IO ()
main = interact (unlines . mostDistinctConsonants . filter longEnough . words)
where longEnough xs = length xs > 10
- Output:
comprehensible
Or, in terms of Data.Set, choosing just one of various possible interpretations of an ambiguous task description.
import Data.Char (toLower)
import Data.Function (on)
import Data.List (groupBy, sortOn, (\\))
import Data.Ord (Down (..))
import qualified Data.Set as S
-- WORDS USING LARGEST SUBSET OF GIVEN SET OF CHARACTERS -
uniqueGlyphCounts :: S.Set Char -> [String] -> [[(String, Int)]]
uniqueGlyphCounts glyphs ws =
groupBy (on (==) snd) . sortOn (Down . snd) $
((,) <*> (S.size . S.intersection glyphs . S.fromList))
<$> ws
--------------------------- TEST -------------------------
consonants :: S.Set Char
consonants =
S.fromList $
((<>) <*> fmap toLower)
(['A' .. 'Z'] \\ "AEIOU")
main :: IO ()
main =
readFile "unixdict.txt"
>>= mapM_ (mapM_ print)
. take 1
. uniqueGlyphCounts consonants
. lines
- Output:
("bremsstrahlung",9) ("comprehensible",9) ("crystallographer",9) ("crystallography",9) ("electroencephalogram",9) ("electroencephalography",9) ("handicraftsman",9) ("handicraftsmen",9) ("immunoelectrophoresis",9) ("incomprehensible",9) ("knightsbridge",9)
or adjusting the test above to return only words which use no consonant twice:
main :: IO ()
main =
readFile "unixdict.txt"
>>= mapM_ (mapM_ print)
. fmap (filter noConsonantTwice)
. take 1
. uniqueGlyphCounts consonants
. lines
noConsonantTwice :: (String, Int) -> Bool
noConsonantTwice =
uncurry
( (==)
. length
. filter (`S.member` consonants)
)
- Output:
("comprehensible",9)
J
>(#~ [: (= >./) #@(~.#~ ~.-:])@-.&'aeiou'@>) cutLF fread'unixdict.txt'
comprehensible
Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public final class FindWordsWhichContainTheMostConsonants {
public static void main(String[] args) throws IOException {
Map<Long, List<String>> wordMap = new TreeMap<Long, List<String>>(Comparator.reverseOrder());
Files.lines(Path.of("unixdict.txt")).forEach( word -> {
long count = 0;
if ( word.length() > 10 && ( count = uniqueConsonantCount(word) ) > 0 ) {
wordMap.computeIfAbsent(count, v -> new ArrayList<String>()).addLast(word);
}
} );
wordMap.forEach( (k, v) -> {
System.out.println("Word count with " + k + " unique consonants: " + v.size());
for ( int i = 0; i< v.size(); i++ ) {
System.out.print(String.format("%-18s%s", v.get(i), ( i % 6 == 5 ? "\n" : " " )));
}
System.out.println(System.lineSeparator());
} );
}
private static long uniqueConsonantCount(String word) {
List<Character> consonants = word.chars()
.mapToObj( i -> (char) i )
.map( ch -> Character.toLowerCase(ch) )
.filter( ch -> ch >= 'a' && ch <= 'z' && ! VOWELS.contains(ch) ).toList();
final long distinctConsonants = consonants.stream().distinct().count();
return ( consonants.size() == distinctConsonants ) ? distinctConsonants : 0;
}
private static final List<Character> VOWELS = List.of( 'a', 'e', 'i', 'o', 'u' );
}
- Output:
Word count with 9 unique consonants: 1 comprehensible Word count with 8 unique consonants: 39 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 Word count with 7 unique consonants: 130 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 Word count with 6 unique consonants: 152 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 Word count with 5 unique consonants: 22 acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition Word count with 4 unique consonants: 3 audiovisual bourgeoisie onomatopoeia
JavaScript
For file IO, this version relies on the macOS ObjC classes exposed to JavaScript for Automation.
(() => {
"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());
})();
- Output:
[["comprehensible",9]]
jq
Works with gojq, the Go implementation of jq
In this entry, two subtasks are considered:
(a) determine the eligible words with the maximal number of consonants;
(b) group the eligible words by the number of consonants, and show these groups if the number of consonants is greater than 7.
Preliminaries
# "bag of words"
def bow(stream):
reduce stream as $word ({}; .[($word|tostring)] += 1);
# Given an array of values as input, generate a stream of values of the maximal elements as determined by f.
# Notes:
# 1. If the input is [] then the output stream is empty.
# 2. If f evaluates to null for all the input elements, then the output stream will be the stream of all the input items.
def maximal_by(f):
(map(f) | max) as $mx
| .[] | select(f == $mx);
def consonants: gsub("[aeiou]";"");
def letters_are_distinct:
bow(explode[])
| all(.[]; . == 1);
The Tasks
def tasks:
def taskA:
maximal_by(.[1]) | .[0];
def taskB:
map(select(.[1]|length > 7))
| group_by(.[1])
| map( .[0][1] as $m | [$m, map(.[0])] )
| .[]
| if .[1]|length==1
then "\nThe eligible word with \(.[0]) consonants is:"
else "\nThe eligible words with \(.[0]) consonants are:"
end,
.[1] ;
[inputs
| select(length>10)
| consonants as $c
| select($c | letters_are_distinct)
| [., ($c|length)] ]
| ("Eligible words with the maximal number of consonants:",
taskA,
taskB) ;
tasks
- Output:
Invocation example: jq -nRrM program.jq unixdict.txt
Eligible words with the maximal number of consonants: comprehensible The eligible words with 8 consonants are: ["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"] The eligible word with 9 consonants is: ["comprehensible"]
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))
mostc(word) = [-length(filter(consonant, word)), word]
const res = sort(map(mostc, filter(over10sc, split(read("unixdict.txt", String), r"\s+"))))
println(length(res), " words found.\n\nWord Consonants\n----------------------")
foreach(a -> println(rpad(a[2], 16), -a[1]), res)
- Output:
347 words found. Word Consonants ---------------------- comprehensible 9 administrable 8 anthropology 8 blameworthy 8 bluestocking 8 boustrophedon 8 bricklaying 8 chemisorption 8 christendom 8 claustrophobia 8 compensatory 8 comprehensive 8 counterexample 8 -- multiple lines deleted -- audiovisual 4 bourgeoisie 4 onomatopoeia 4
M2000 Interpeter
"Find the words which contains most consonants" means consonants are more than 50% of word length.
module Find_words{
boolean skip
k=0
L=queue
open "unixdict.txt" for input as #f
while not eof(#f)
line input #f, o$
if len(o$)>10 else continue
skip=false
l$=filter$(o$, "aeiou")
j=len(l$)-1
for i=1 to j+1
if len(filter$(l$,mid$(l$, i,1)))<>j then skip=true:exit for
next
if skip then continue
if len(l$)/len(o$)>0.5 then k++: append L, len(l$):=o$
end while
close #f
document doc$="Found:"+k+ {
}
sort descending L
m=each(L, 1, 10)
while m
doc$=format$("{0::-4} {1:20} {2}", m^+1, eval$(m), eval$(m!))+{
}
end while
doc$={ ------------------
}
m=each(L, -10, -1)
while m
doc$=format$("{0::-4} {1:20} {2}", m^+1, eval$(m), eval$(m!))+{
}
end while
// process new line using -2 (to screen)
Print #-2, doc$
clipboard doc$
}
Find_words
- Output:
Found:290 1 comprehensible 9 2 administrable 8 3 anthropology 8 4 blameworthy 8 5 bluestocking 8 6 boustrophedon 8 7 bricklaying 8 8 chemisorption 8 9 christendom 8 10 claustrophobia 8 ------------------ 281 superficial 6 282 superlative 6 283 teaspoonful 6 284 trapezoidal 6 285 tridiagonal 6 286 troublesome 6 287 valediction 6 288 venturesome 6 289 vermiculite 6 290 wisenheimer 6
Mathematica /Wolfram Language
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"] &;
dict //= Select[StringLength /* GreaterThan[10]];
dict = {#, Select[Characters[#], MemberQ[consonants, #] &]} & /@ dict;
dict //= Select[Last /* DuplicateFreeQ];
SortBy[GatherBy[dict, Last /* Length], First /* Last /* Length][[All, All, 1]] // Column
- Output:
{audiovisual,bourgeoisie,onomatopoeia} {acquisition,acquisitive,acrimonious,ceremonious,deleterious,diatomaceous,egalitarian,equilibrate,equilibrium,equinoctial,expeditious,hereinabove,homogeneous,inequitable,injudicious,inoperative,inquisitive,interviewee,leeuwenhoek,onomatopoeic,radioactive,requisition} {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} {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} {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} {comprehensible}
Nim
import strformat, strutils, tables
const Vowels = {'a', 'e', 'i', 'o', 'u'}
template plural(n: int): string = (if n > 1: "s" else: "")
var results: array[0..9, seq[string]]
for word in "unixdict.txt".lines:
if word.len <= 10: continue
block checkWord:
let letterCounts = word.toCountTable
var consonantCount = 0
for key, count in letterCounts.pairs:
if key notin Vowels:
if count > 1: break checkWord
if count == 1: inc consonantCount
results[consonantCount].add word
for n in countdown(9, 4):
let count = results[n].len
echo &"\nFound {count} word{plural(count)} with {n} unique consonants:"
for i, word in results[n]:
stdout.write word.align(14), if (i + 1) mod 9 == 0: '\n' else: ' '
echo()
- Output:
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
Perl
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Find_words_which_contains_most_consonants
use warnings;
my @most;
@ARGV = 'unixdict.txt';
length > 11 and !/([^aeiou]).*\1/ and $most[ tr/aeiou\n//c ] .= $_ while <>;
$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;
- Output:
9 Unique consonants, word count: 1 comprehensible 8 Unique consonants, word count: 39 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 Unique consonants, word count: 130 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 Unique consonants, word count: 152 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 Unique consonants, word count: 22 acquisition acquisitive acrimonious ceremonious deleterious diatomaceous egalitarian equilibrate equilibrium equinoctial expeditious hereinabove homogeneous inequitable injudicious inoperative inquisitive interviewee leeuwenhoek onomatopoeic radioactive requisition 4 Unique consonants, word count: 3 audiovisual bourgeoisie onomatopoeia
Phix
with javascript_semantics function consonant(integer ch) return find(ch,"aeiou")=0 end function function singlec(string consonants) return length(unique(consonants))=length(consonants) end function function over10sc(string word) return length(word)>10 and singlec(filter(word,consonant)) end function function mostc(string word) return {length(filter(word,consonant)),word} end function sequence res = sort_columns(apply(filter(unix_dict(),over10sc),mostc),{-1,2}) printf(1,"%d most consonant words: %v\n",{length(res),shorten(res,"",2)})
It does not escape me that the use of lambda expressions would make this slightly easier to write but much harder to comprehend...
Admittedly adding a dozen or so line breaks to the above might (actually) improve matters, but I'm sure you'll cope somehow.
- Output:
347 most consonant words: {{9,"comprehensible"},{8,"administrable"},"...",{4,"bourgeoisie"},{4,"onomatopoeia"}}
Python
"Use Python," they say, "it's comprehensible," they say.
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)
- Output:
9: comprehensible 8: 39 words 7: 130 words 6: 152 words 5: acquisition acquisitive ...<snip>... onomatopoeic radioactive requisition 4: audiovisual bourgeoisie onomatopoeia
The above is roughly equivalent to the following:
import re
from collections import defaultdict
with open('unixdict.txt') as f:
lines = [l.rstrip() for l in f] # all lines of text without newline
# keep only lines that's long enough and has no non-letters
words = [w for w in lines if len(w) > 10 and not re.match(r'[^a-z]', w)]
good = defaultdict(list)
for word in words:
# take all consonants in word
c = re.sub(r'[aeiou]', '', word)
# check if there are duplicates
if sorted(c) == sorted(set(c)):
good[len(c)].append(word)
for k, v in sorted(good.items(), reverse=True):
if len(v) > 30:
print(f'{k}: {len(v)} words')
else:
print(f'{k}:', ' '.join(sorted(v)))
Or, aiming for some degree of legibility, and showing results for two of the possible interpretations of an ambiguous task description:
'''Words using largest sets of consonants'''
from itertools import groupby
from os.path import expanduser
from string import ascii_letters
# uniqueGlyphCounts :: Set Char -> [String] -> [[(String, Int)]]
def uniqueGlyphCounts(glyphs):
'''The words in a given list ordered and grouped by,
the descending number of unique consonants which
they contain, each word tupled with that number.
'''
def go(ws):
return [
list(snd(ab)) for ab in groupby(
sorted(
[
(
w,
len(set(w).intersection(glyphs))
)
for w in ws
],
key=snd,
reverse=True
),
key=snd
)
]
return go
# noGlyphRepeated :: Set Char -> (String, Int) -> Bool
def noGlyphRepeated(glyphs):
'''True if the string in a given (String, Int)
tuple contains no multiple uses of any of
the given set of glyphs.
'''
def go(sn):
s, n = sn
return n == len([c for c in s if c in glyphs])
return go
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Words drawn from a given list which use the largest
set of consonants, and contain no repeated consonants.
'''
consonants = set(ascii_letters).difference(
set("AEIOUaeiou")
)
largestConsonantSet = uniqueGlyphCounts(consonants)(
readFile("unixdict.txt").splitlines()
)[0]
noConsonantsReused = noGlyphRepeated(consonants)
print("Words using largest sets of unique consonants:")
for x in largestConsonantSet:
print(x)
print("\nExcluding words which reuse any consonants:")
for sn in largestConsonantSet:
if noConsonantsReused(sn):
print(sn)
# ----------------------- GENERIC ------------------------
# readFile :: FilePath -> IO String
def readFile(fp):
'''The contents of any file at the path
derived by expanding any ~ in fp.
'''
with open(expanduser(fp), 'r', encoding='utf-8') as f:
return f.read()
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
# MAIN ---
if __name__ == '__main__':
main()
- Output:
Words using largest sets of unique consonants: ('bremsstrahlung', 9) ('comprehensible', 9) ('crystallographer', 9) ('crystallography', 9) ('electroencephalogram', 9) ('electroencephalography', 9) ('handicraftsman', 9) ('handicraftsmen', 9) ('immunoelectrophoresis', 9) ('incomprehensible', 9) ('knightsbridge', 9) Excluding words which reuse any consonants: ('comprehensible', 9)
Using generator functions
"""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()
- Output:
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
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.
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")]
#The following line is equivalent to sapply(consonants, function(x) stringr::str_count(dictBig, x))
#As with all things with strings in R, life is easier with stringr or stringi.
consonantCount <- sapply(consonants, function(x) lengths(regmatches(dictBig, gregexec(x, dictBig))))
wordsWithNoRepeatedConsts <- dictBig[apply(consonantCount, MARGIN = 1, function(x) all(x <= 1))]
uniqueConstCount <- rowSums(sapply(consonants, function(x) grepl(x, wordsWithNoRepeatedConsts)))
biggestWords <- function(offset) wordsWithNoRepeatedConsts[which(uniqueConstCount == max(uniqueConstCount) - offset)]
cat("Biggest:", paste(biggestWords(0), collapse = ", "),
"\n \n Second biggest:", paste(biggestWords(1), collapse = ", "),
"\n \n Third biggest:", paste(biggestWords(2), collapse = ", "))
- Output:
Read 25104 items Biggest: comprehensible Second biggest: 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 Third biggest: 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
Racket
#lang racket
(define (consonant-count s)
(set-count (set-subtract (list->set (string->list s))
(set #\a #\e #\i #\o #\u))))
(define words-by-consonant-count
(group-by consonant-count (file->lines "../../data/unixdict.txt")))
(module+ main
(define group-count (compose consonant-count first))
(define group-with-max-consonant-count
(argmax group-count words-by-consonant-count))
(displayln "Group with gratest consonant count:")
group-with-max-consonant-count
(printf "with: ~a consonants in each word"
(group-count group-with-max-consonant-count)))
- Output:
Group with gratest consonant count: '("bremsstrahlung" "comprehensible" "crystallographer" "crystallography" "electroencephalogram" "electroencephalography" "handicraftsman" "handicraftsmen" "immunoelectrophoresis" "incomprehensible" "knightsbridge") with: 9 consonants in each word
Raku
Hmm. Depends on how you define "most".
unit sub MAIN ($min = 11);
my @vowel = <a e i o u>;
my $vowel = rx/ @vowel /;
my @consonant = ('a'..'z').grep: { $_ ∉ @vowel };
my $consonant = rx/ @consonant /;
say "Minimum characters in a word: $min";
say "Number found, consonant count and list of words with the largest absolute number of unique, unrepeated consonants:";
say +.value, ' @ ', $_ for 'unixdict.txt'.IO.words.grep( {.chars >= $min and so all(.comb.Bag{@consonant}) <= 1} )
.classify( { +.comb(/$consonant/) } ).sort(-*.key).head(2);
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);
- Output:
Minimum characters in a word: 11 Number found, consonant count and list of words with the largest absolute number of unique, unrepeated consonants: 1 @ 9 => [comprehensible] 39 @ 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] Number found, ratio and list of words with the highest ratio of unique, unrepeated consonants to vowels: 14 @ 2.666667 => [blameworthy bricklaying christendom mockingbird pitchblende playwriting shortcoming springfield stenography stockholder switchblade switchboard switzerland thunderclap] 13 @ 2 => [anthropology bluestocking compensatory demonstrable disciplinary geochemistry hypertensive lexicography manslaughter misanthropic monkeyflower pharmacology shipbuilding] 1 @ 1.8 => [comprehensible]
Character count of 11 minimum is rather arbitrary. If we feed it a character count minimum of 5, the first one returns a pretty similar answer, 8 additional words at 8 consonants (all with 10 characters.)
The second would actually come up with some infinite ratios (since we somewhat bogusly don't count 'y' as a vowel.):
Minimum characters in a word: 5 Number found, consonant count and list of words with the largest absolute number of unique, unrepeated consonants: 1 @ 9 => [comprehensible] 47 @ 8 => [administrable anthropology bankruptcy blacksmith blameworthy bluestocking boustrophedon bricklaying chemisorption christendom claustrophobia compensatory comprehensive counterexample crankshaft demonstrable disciplinary discriminable geochemistry hypertensive indecipherable indecomposable indiscoverable lexicography lynchburg manslaughter misanthropic mockingbird monkeyflower neuropathology paralinguistic pharmacology pitchblende playwright playwriting shipbuilding shortcoming sprightly springfield stenography stockholder strickland stronghold switchblade switchboard switzerland thunderclap] Number found, ratio and list of words with the highest ratio of unique, unrepeated consonants to vowels: 6 @ Inf => [crypt glyph lymph lynch nymph psych] 2 @ 8 => [lynchburg sprightly] 5 @ 7 => [klystron mcknight schwartz skylight splotchy]
REXX
This REXX version doesn't care what order the words in the dictionary are in, nor does it care what
case (lower/upper/mixed) the words are in, the search for the words is caseless.
It also allows the minimum length to be specified on the command line (CL) as well as the dictionary file identifier.
/*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.*/
if iFID=='' | iFID=="," then iFID='unixdict.txt' /* " " " " " " */
do #=1 while lines(iFID)\==0 /*read each word in the file (word=X).*/
x= strip( linein( iFID) ) /*pick off a word from the input line. */
@.#= x /*save: the original case of the word.*/
end /*#*/
#= # - 1 /*adjust word count because of DO loop.*/
say copies('─', 30) # "words in the dictionary file: " iFID
xyz= 'bcdfghjklmnpqrstvwxyz'; upper xyz /*list of the 21 uppercase consonants. */
L= length(xyz) /*number of consonants in the alphabet.*/
maxCnt= 0 /*max # unique consonants in a max set.*/
!.=; !!.= 0 /* " " " " " " word. */
do j=1 for #; $= @.j; upper $ /*obtain an uppercased word from dict. */
if length($)<minl then iterate /*Is word long enough? No, then skip.*/
cnt= 0 /*the number of consonants (so far). */
do k=1 for L; q= substr(xyz, K, 1) /*examine all consonants for uniqueness*/
_= pos(q, $)
if _==0 then iterate /*Is this consonant present? No, skip.*/
if pos(q, $, _ + 1)>0 then iterate j /*More than 1 same consonant? Then skip*/
cnt= cnt + 1 /*bump the number of consonants so far.*/
end /*k*/
!.cnt= !.cnt @.j /*append a word to a specific len list.*/
!!.cnt= cnt /*keep track of # of unique consonants.*/
maxCnt= max(maxCNT, cnt) /*save the maximum count (so far). */
end /*j*/
/*show sets of words, unique consonants*/
do m=maxCnt to 1 by -1; n= words(!.m) /*get the number of words in this set. */
if n==0 then iterate /*Any word in this set? No, then skip.*/
say; say /*show some blank lines between sets. */
do y=1 for n /*show individual words in the set. */
say right(y, L#)':' right( left( word(!.m, y), 30), 40) /*indent words.*/
end /*y*/
say copies('─', 30) n " word"s(n) 'found which have ' !!.m " unique" ,
"consonants and having a minimum word length of: " minl
end /*m*/
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)
- output when using the default inputs:
(Shown at three-quarter size.)
────────────────────────────── 25104 words in the dictionary file: unixdict.txt 1: comprehensible ────────────────────────────── 1 word found which have 9 unique consonants and having a minimum word length of: 11 1: administrable 2: anthropology 3: blameworthy 4: bluestocking 5: boustrophedon 6: bricklaying 7: chemisorption 8: christendom 9: claustrophobia 10: compensatory 11: comprehensive 12: counterexample 13: demonstrable 14: disciplinary 15: discriminable 16: geochemistry 17: hypertensive 18: indecipherable 19: indecomposable 20: indiscoverable 21: lexicography 22: manslaughter 23: misanthropic 24: mockingbird 25: monkeyflower 26: neuropathology 27: paralinguistic 28: pharmacology 29: pitchblende 30: playwriting 31: shipbuilding 32: shortcoming 33: springfield 34: stenography 35: stockholder 36: switchblade 37: switchboard 38: switzerland 39: thunderclap ────────────────────────────── 39 words found which have 8 unique consonants and having a minimum word length of: 11 1: acknowledge 2: algorithmic 3: alphanumeric 4: ambidextrous 5: amphibology 6: anchoritism 7: atmospheric 8: autobiography 9: bakersfield 10: bartholomew 11: bidirectional 12: bloodstream 13: boardinghouse 14: cartilaginous 15: centrifugal 16: chamberlain 17: charlemagne 18: clairvoyant 19: combinatorial 20: compensable 21: complaisant 22: conflagrate 23: conglomerate 24: conquistador 25: consumptive 26: convertible 27: cosmopolitan 28: counterflow 29: countryside 30: countrywide 31: declamatory 32: decomposable 33: decomposition 34: deliquescent 35: description 36: descriptive 37: dilogarithm 38: discernible 39: discriminate 40: disturbance 41: documentary 42: earthmoving 43: encephalitis 44: endothermic 45: epistemology 46: everlasting 47: exchangeable 48: exclamatory 49: exclusionary 50: exculpatory 51: explanatory 52: extemporaneous 53: extravaganza 54: filamentary 55: fluorescent 56: galvanometer 57: geophysical 58: glycerinate 59: groundskeep 60: herpetology 61: heterozygous 62: homebuilding 63: honeysuckle 64: hydrogenate 65: hyperboloid 66: impenetrable 67: imperceivable 68: imperishable 69: imponderable 70: impregnable 71: improvident 72: improvisation 73: incomparable 74: incompatible 75: incomputable 76: incredulity 77: indefatigable 78: indigestible 79: indisputable 80: inexhaustible 81: inextricable 82: inhospitable 83: inscrutable 84: jurisdiction 85: lawbreaking 86: leatherback 87: leatherneck 88: leavenworth 89: logarithmic 90: loudspeaking 91: maidservant 92: malnourished 93: marketplace 94: merchandise 95: methodology 96: misanthrope 97: mitochondria 98: molybdenite 99: nearsighted 100: obfuscatory 101: oceanography 102: palindromic 103: paradigmatic 104: paramagnetic 105: perfectible 106: phraseology 107: politicking 108: predicament 109: presidential 110: problematic 111: proclamation 112: promiscuity 113: providential 114: purchasable 115: pythagorean 116: quasiparticle 117: quicksilver 118: radiotelephone 119: sedimentary 120: selfadjoint 121: serendipity 122: sovereignty 123: subjunctive 124: superfluity 125: terminology 126: valedictorian 127: valedictory 128: verisimilitude 129: vigilantism 130: voluntarism ────────────────────────────── 130 words found which have 7 unique consonants and having a minimum word length of: 11 1: aboveground 2: advantageous 3: adventurous 4: aerodynamic 5: anglophobia 6: anisotropic 7: archipelago 8: automorphic 9: baltimorean 10: beneficiary 11: borosilicate 12: cabinetmake 13: californium 14: codetermine 15: coextensive 16: comparative 17: compilation 18: composition 19: confabulate 20: confederate 21: considerate 22: consolidate 23: counterpoise 24: countervail 25: decisionmake 26: declamation 27: declaration 28: declarative 29: deemphasize 30: deformation 31: deliverance 32: demountable 33: denumerable 34: deoxyribose 35: depreciable 36: deprivation 37: destabilize 38: diagnosable 39: diamagnetic 40: dichotomize 41: dichotomous 42: disambiguate 43: eigenvector 44: elizabethan 45: encapsulate 46: enforceable 47: ephemerides 48: epidemiology 49: evolutionary 50: exceptional 51: exclamation 52: exercisable 53: exhaustible 54: exoskeleton 55: expenditure 56: experiential 57: exploration 58: fluorescein 59: geometrician 60: hemosiderin 61: hereinbelow 62: hermeneutic 63: heterogamous 64: heterogeneous 65: heterosexual 66: hexadecimal 67: hexafluoride 68: homebuilder 69: homogeneity 70: housebroken 71: icosahedral 72: icosahedron 73: impersonate 74: imprecision 75: improvisate 76: inadvisable 77: increasable 78: incredulous 79: indivisible 80: indomitable 81: ineradicable 82: inescapable 83: inestimable 84: inexcusable 85: infelicitous 86: informatica 87: informative 88: inseparable 89: insuperable 90: ionospheric 91: justiciable 92: kaleidescope 93: kaleidoscope 94: legerdemain 95: liquefaction 96: loudspeaker 97: machinelike 98: magisterial 99: maladaptive 100: mantlepiece 101: manufacture 102: masterpiece 103: meetinghouse 104: meteorology 105: minesweeper 106: ministerial 107: multifarious 108: musculature 109: observation 110: patrimonial 111: peasanthood 112: pediatrician 113: persecution 114: pertinacious 115: picturesque 116: planetarium 117: pleistocene 118: pomegranate 119: predominate 120: prejudicial 121: prohibition 122: prohibitive 123: prolegomena 124: prosecution 125: provisional 126: provocation 127: publication 128: quasiperiodic 129: reclamation 130: religiosity 131: renegotiable 132: residential 133: rooseveltian 134: safekeeping 135: saloonkeeper 136: serviceable 137: speedometer 138: subrogation 139: sulfonamide 140: superficial 141: superlative 142: teaspoonful 143: trapezoidal 144: tridiagonal 145: troublesome 146: vainglorious 147: valediction 148: venturesome 149: vermiculite 150: vocabularian 151: warehouseman 152: wisenheimer ────────────────────────────── 152 words found which have 6 unique consonants and having a minimum word length of: 11 1: acquisition 2: acquisitive 3: acrimonious 4: ceremonious 5: deleterious 6: diatomaceous 7: egalitarian 8: equilibrate 9: equilibrium 10: equinoctial 11: expeditious 12: hereinabove 13: homogeneous 14: inequitable 15: injudicious 16: inoperative 17: inquisitive 18: interviewee 19: leeuwenhoek 20: onomatopoeic 21: radioactive 22: requisition ────────────────────────────── 22 words found which have 5 unique consonants and having a minimum word length of: 11 1: audiovisual 2: bourgeoisie 3: onomatopoeia ────────────────────────────── 3 words found which have 4 unique consonants and having a minimum word length of: 11
Ring
load "stdlib.ring"
cStr = read("unixdict.txt")
wordList = str2list(cStr)
consonants = []
result = []
num = 0
see "working..." + nl
ln = len(wordList)
for n = ln to 1 step -1
if len(wordList[n]) < 11
del(wordList,n)
ok
next
for n = 1 to len(wordList)
flag = 1
numcon = 0
str = wordList[n]
for m = 1 to len(str) - 1
for p = m+1 to len(str)
if not isvowel(str[m]) and (str[m] = str[p])
flag = 0
exit 2
ok
next
next
if flag = 1
add(consonants,wordList[n])
ok
next
for n = 1 to len(consonants)
con = 0
str = consonants[n]
for m = 1 to len(str)
if not isvowel(str[m])
con = con + 1
ok
next
add(result,[consonants[n],con])
next
result = sortsecond(result)
result = reverse(result)
for n = 1 to len(result)
see "" + n + ". " + result[n][1] + " " + result[n][2] + nl
next
see "done..." + nl
func sortsecond(alist)
aList = sort(alist,2)
for n=1 to len(alist)-1
for m=n to len(aList)-1
if alist[m+1][2] = alist[m][2] and strcmp(alist[m+1][1],alist[m][1]) > 0
temp = alist[m+1]
alist[m+1] = alist[m]
alist[m] = temp
ok
next
next
return aList
- Output:
working... 1. comprehensible 9 2. administrable 8 3. anthropology 8 4. blameworthy 8 5. bluestocking 8 6. boustrophedon 8 7. bricklaying 8 8. chemisorption 8 9. christendom 8 10. claustrophobia 8 ... 50. bartholomew 7 51. bidirectional 7 52. bloodstream 7 53. boardinghouse 7 54. cartilaginous 7 55. centrifugal 7 56. chamberlain 7 57. charlemagne 7 58. clairvoyant 7 59. combinatorial 7 60. compensable 7 ... 180. beneficiary 6 181. borosilicate 6 182. cabinetmake 6 183. californium 6 184. codetermine 6 185. coextensive 6 186. comparative 6 187. compilation 6 188. composition 6 189. confabulate 6 190. confederate 6 ... 330. equilibrate 5 331. equilibrium 5 332. equinoctial 5 333. expeditious 5 334. hereinabove 5 335. interviewee 5 336. leeuwenhoek 5 337. homogeneous 5 338. inequitable 5 339. injudicious 5 340. onomatopoeic 5 ... 345. audiovisual 4 346. bourgeoisie 4 347. onomatopoeia 4 done...
RPL
The only way to use unixdict.txt
as input is to convert it into a list of 25104 strings. Fortunately, emulators can handle such a big data structure in RAM.
≪ → 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
≫ ≫ ‘CONSONANTS’ STO
'Unixdict' 9 CONSONANTS 'Unixdict' 8 CONSONANTS
- Output:
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" }
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
- Output:
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
Rust
use itertools::Itertools;
use std::fs;
const VOWELS: [char; 5] = ['a', 'e', 'i', 'o', 'u'];
fn is_c(ch: &char) -> bool {
return !VOWELS.contains(ch);
}
fn all_c_uniq(w: &str, n: usize, cmin: usize) -> bool {
return w.len() >= n && {
let nunique = w.chars().sorted().dedup().filter(|c| is_c(c)).count();
return nunique >= cmin && nunique == w.chars().filter(|c| is_c(c)).count();
};
}
fn mostc(w: &str) -> Option<(i32, String)> {
return if all_c_uniq(w, 11, 4) {
Some((-(w.chars().filter(|c| is_c(c)).count() as i32), w.to_string()))
} else {
None
};
}
fn main() {
let wordsfile = fs::read_to_string("unixdict.txt").unwrap().to_lowercase();
let results = wordsfile.split_whitespace().filter_map(|w| mostc(w)).collect_vec();
println!(
"{} words found.\n\nWord Consonants\n----------------------",
results.len()
);
for (len, word) in results.iter().sorted() {
println!("{:<16} {}", word, -len);
}
}
- Output:
347 words found. Word Consonants ---------------------- comprehensible 9 administrable 8 anthropology 8 blameworthy 8 bluestocking 8 boustrophedon 8 bricklaying 8 chemisorption 8 christendom 8 claustrophobia 8 compensatory 8 comprehensive 8 counterexample 8 demonstrable 8 disciplinary 8 discriminable 8 geochemistry 8 hypertensive 8 indecipherable 8 indecomposable 8 indiscoverable 8 lexicography 8 manslaughter 8 misanthropic 8 mockingbird 8 monkeyflower 8 neuropathology 8 paralinguistic 8 pharmacology 8 pitchblende 8 playwriting 8 shipbuilding 8 shortcoming 8 springfield 8 stenography 8 stockholder 8 switchblade 8 switchboard 8 switzerland 8 thunderclap 8 acknowledge 7 algorithmic 7 alphanumeric 7 ambidextrous 7 amphibology 7 anchoritism 7 atmospheric 7 autobiography 7 bakersfield 7 bartholomew 7 bidirectional 7 bloodstream 7 boardinghouse 7 cartilaginous 7 centrifugal 7 chamberlain 7 charlemagne 7 clairvoyant 7 combinatorial 7 compensable 7 complaisant 7 conflagrate 7 conglomerate 7 conquistador 7 consumptive 7 convertible 7 cosmopolitan 7 counterflow 7 countryside 7 countrywide 7 declamatory 7 decomposable 7 decomposition 7 deliquescent 7 description 7 descriptive 7 dilogarithm 7 discernible 7 discriminate 7 disturbance 7 documentary 7 earthmoving 7 encephalitis 7 endothermic 7 epistemology 7 everlasting 7 exchangeable 7 exclamatory 7 exclusionary 7 exculpatory 7 explanatory 7 extemporaneous 7 extravaganza 7 filamentary 7 fluorescent 7 galvanometer 7 geophysical 7 glycerinate 7 groundskeep 7 herpetology 7 heterozygous 7 homebuilding 7 honeysuckle 7 hydrogenate 7 hyperboloid 7 impenetrable 7 imperceivable 7 imperishable 7 imponderable 7 impregnable 7 improvident 7 improvisation 7 incomparable 7 incompatible 7 incomputable 7 incredulity 7 indefatigable 7 indigestible 7 indisputable 7 inexhaustible 7 inextricable 7 inhospitable 7 inscrutable 7 jurisdiction 7 lawbreaking 7 leatherback 7 leatherneck 7 leavenworth 7 logarithmic 7 loudspeaking 7 maidservant 7 malnourished 7 marketplace 7 merchandise 7 methodology 7 misanthrope 7 mitochondria 7 molybdenite 7 nearsighted 7 obfuscatory 7 oceanography 7 palindromic 7 paradigmatic 7 paramagnetic 7 perfectible 7 phraseology 7 politicking 7 predicament 7 presidential 7 problematic 7 proclamation 7 promiscuity 7 providential 7 purchasable 7 pythagorean 7 quasiparticle 7 quicksilver 7 radiotelephone 7 sedimentary 7 selfadjoint 7 serendipity 7 sovereignty 7 subjunctive 7 superfluity 7 terminology 7 valedictorian 7 valedictory 7 verisimilitude 7 vigilantism 7 voluntarism 7 aboveground 6 advantageous 6 adventurous 6 aerodynamic 6 anglophobia 6 anisotropic 6 archipelago 6 automorphic 6 baltimorean 6 beneficiary 6 borosilicate 6 cabinetmake 6 californium 6 codetermine 6 coextensive 6 comparative 6 compilation 6 composition 6 confabulate 6 confederate 6 considerate 6 consolidate 6 counterpoise 6 countervail 6 decisionmake 6 declamation 6 declaration 6 declarative 6 deemphasize 6 deformation 6 deliverance 6 demountable 6 denumerable 6 deoxyribose 6 depreciable 6 deprivation 6 destabilize 6 diagnosable 6 diamagnetic 6 dichotomize 6 dichotomous 6 disambiguate 6 eigenvector 6 elizabethan 6 encapsulate 6 enforceable 6 ephemerides 6 epidemiology 6 evolutionary 6 exceptional 6 exclamation 6 exercisable 6 exhaustible 6 exoskeleton 6 expenditure 6 experiential 6 exploration 6 fluorescein 6 geometrician 6 hemosiderin 6 hereinbelow 6 hermeneutic 6 heterogamous 6 heterogeneous 6 heterosexual 6 hexadecimal 6 hexafluoride 6 homebuilder 6 homogeneity 6 housebroken 6 icosahedral 6 icosahedron 6 impersonate 6 imprecision 6 improvisate 6 inadvisable 6 increasable 6 incredulous 6 indivisible 6 indomitable 6 ineradicable 6 inescapable 6 inestimable 6 inexcusable 6 infelicitous 6 informatica 6 informative 6 inseparable 6 insuperable 6 ionospheric 6 justiciable 6 kaleidescope 6 kaleidoscope 6 legerdemain 6 liquefaction 6 loudspeaker 6 machinelike 6 magisterial 6 maladaptive 6 mantlepiece 6 manufacture 6 masterpiece 6 meetinghouse 6 meteorology 6 minesweeper 6 ministerial 6 multifarious 6 musculature 6 observation 6 patrimonial 6 peasanthood 6 pediatrician 6 persecution 6 pertinacious 6 picturesque 6 planetarium 6 pleistocene 6 pomegranate 6 predominate 6 prejudicial 6 prohibition 6 prohibitive 6 prolegomena 6 prosecution 6 provisional 6 provocation 6 publication 6 quasiperiodic 6 reclamation 6 religiosity 6 renegotiable 6 residential 6 rooseveltian 6 safekeeping 6 saloonkeeper 6 serviceable 6 speedometer 6 subrogation 6 sulfonamide 6 superficial 6 superlative 6 teaspoonful 6 trapezoidal 6 tridiagonal 6 troublesome 6 vainglorious 6 valediction 6 venturesome 6 vermiculite 6 vocabularian 6 warehouseman 6 wisenheimer 6 acquisition 5 acquisitive 5 acrimonious 5 ceremonious 5 deleterious 5 diatomaceous 5 egalitarian 5 equilibrate 5 equilibrium 5 equinoctial 5 expeditious 5 hereinabove 5 homogeneous 5 inequitable 5 injudicious 5 inoperative 5 inquisitive 5 interviewee 5 leeuwenhoek 5 onomatopoeic 5 radioactive 5 requisition 5 audiovisual 4 bourgeoisie 4 onomatopoeia 4
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;
}
- Output:
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
VBScript
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
- Output:
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 .....
Wren
import "io" for File
import "./fmt" for Fmt
var wordList = "unixdict.txt" // local copy
var vowelIndices = [0, 4, 8, 14, 20]
var words = File.read(wordList).trimEnd().split("\n").where { |w| w.count > 10 }
var wordGroups = List.filled(12, null) // should be enough
for (i in 0..11) wordGroups[i] = []
for (word in words) {
var letters = List.filled(26, 0)
for (c in word) {
var index = c.bytes[0] - 97
if (index >= 0 && index < 26) letters[index] = letters[index] + 1
}
var eligible = true
var uc = 0 // number of unique consonants
for (i in 0..25) {
if (!vowelIndices.contains(i)) {
if (letters[i] > 1) {
eligible = false
break
} else if (letters[i] == 1) {
uc = uc + 1
}
}
}
if (eligible) wordGroups[uc].add(word)
}
for (i in 11..0) {
var count = wordGroups[i].count
if (count > 0) {
var s = (count == 1) ? "" : "s"
System.print("%(count) word%(s) found with %(i) unique consonants:")
Fmt.tprint("$-14s", wordGroups[i], 5)
System.print()
}
}
- Output:
1 word found with 9 unique consonants: comprehensible 39 words found 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 130 words found 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 152 words found 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 22 words found 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 3 words found with 4 unique consonants: audiovisual bourgeoisie onomatopoeia
XPL0
string 0; \use zero-terminated strings
int MaxCon, Con, Set, I, Ch;
char Word(25), MaxWord(25);
def LF=$0A, CR=$0D, EOF=$1A;
[FSet(FOpen("unixdict.txt", 0), ^I);
OpenI(3);
MaxCon:= 0;
repeat I:= 0; Con:= 0; Set:= 0;
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;
case Ch of ^a,^e,^i,^o,^u: [] \assume lowercase words
other [Con:= Con+1; \count constant
if Set & 1<<(Ch-^a) then Con:= 0; \reject if not unique
Set:= Set ! 1<<(Ch-^a);
];
];
Word(I):= 0; \terminate string
if Con > MaxCon then \save Word with maximum
[MaxCon:= Con; \ constants
CopyMem(MaxWord, Word, 25);
];
until Ch = EOF;
Text(0, MaxWord);
]
- Output:
comprehensible
- Draft Programming Tasks
- 11l
- Action!
- Ada
- ALGOL 68
- ALGOL 68-files
- ALGOL 68-sort
- ALGOL W
- Arturo
- AutoHotkey
- AWK
- C++
- CLU
- Delphi
- SysUtils,StdCtrls
- DuckDB
- EasyLang
- F Sharp
- Factor
- Forth
- FreeBASIC
- FutureBasic
- Go
- Haskell
- J
- Java
- JavaScript
- Jq
- Julia
- M2000 Interpeter
- Mathematica
- Wolfram Language
- Nim
- Perl
- Phix
- Python
- R
- Racket
- Raku
- REXX
- Ring
- RPL
- Ruby
- Rust
- TypeScript
- VBScript
- Wren
- Wren-fmt
- XPL0