Find words which contain the most consonants: Difference between revisions
(→{{header|Python}}: added word length > 10 requirement; improved efficiency (har har) by not reading dictionary file multiple times) |
|||
Line 1,862:
<lang python>import re
print('\n'.join(map(lambda x: f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) <
{{out}}
<pre>9: comprehensible
7:
6:
5:
4: aeronautic aficionado ...<bunch of words>... univariate</pre>
▲1: 277 words
=={{header|R}}==
|
Revision as of 04:11, 26 July 2022
- 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 contains most consonants
- Find words which contains more than 3 vowels
- Find words which first and last three letters are equals
- Find words which odd letters are consonants and even letters are vowels or vice_versa
- 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
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. <lang Action!>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</lang>
- 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
<lang 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;</lang>
- 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 W
<lang algolw>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.</lang>
- 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
<lang rebol>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 "" ]
]</lang>
- 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
<lang 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</lang>
- 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
<lang 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)
} </lang>
- 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++
<lang cpp>#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;
}</lang>
- 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
<lang 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</lang>
- 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
F#
<lang fsharp> // Word(s) containing most consonants. Nigel Galloway: February 18th., 2021 let vowels=set['a';'e';'i';'o';'u'] let fN g=let g=g|>Seq.filter(vowels.Contains>>not)|>Array.ofSeq in if g=(g|>Array.distinct) then g.Length else 0 printfn "%A" (seq{use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(fun n->n.Length>10)|>Seq.groupBy fN|>Seq.sortBy fst|>Seq.last) </lang>
- Output:
(9, seq ["comprehensible"])
Factor
<lang 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 .</lang>
- 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" } } }
FreeBASIC
<lang 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</lang>
Go
<lang 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() } } }
}</lang>
- Output:
Same as Wren example.
Haskell
<lang 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</lang>
- Output:
comprehensible
Or, in terms of Data.Set, choosing just one of various possible interpretations of an ambiguous task description.
<lang haskell>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</lang>
- 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:
<lang haskell>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) )</lang>
- Output:
("comprehensible",9)
J
<lang J> >(#~ [: (= >./) #@(~.#~ ~.-:])@-.&'aeiou'@>) cutLF fread'unixdict.txt' comprehensible</lang>
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 <lang jq># "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);
</lang> The Tasks <lang jq>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</lang>
- 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
<lang julia>consonant(ch) = !(ch in ['a', 'e', 'i', 'o', 'u']) singlec(consonants) = length(unique(consonants)) == length(consonants) over10sc(word) = length(word) > 10 && singlec(filter(consonant, word)) 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)
</lang>
- 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
Mathematica/Wolfram Language
<lang Mathematica>consonants = DeleteCases[Alphabet[], Alternatives @@ Characters["euioa"]]; dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]]; dict //= StringSplit[#, "\n"] &; 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</lang>
- 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
<lang 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()</lang>
- 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
<lang 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;</lang>
- 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. <lang python>import re
print('\n'.join(map(lambda x: f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 40 else f'{x[0]}: {len(x[1])} words', filter(lambda x: x[1], reversed([(n, [x[1] for x in l if x[0] == n]) for n in range(maxlen)])))) if (maxlen := max(l := list(sorted([(len(c), w) for w in [l.rstrip() for l in open('unixdict.txt') if not re.match(r'[^a-z]', l) and len(l) > 10] if list(sorted(c := re.sub(r'[aeiou]', , w))) == list(sorted(set(c)))], reverse=True)))[0] + 1) else None)</lang>
- Output:
9: comprehensible 8: 45 words 7: 217 words 6: 455 words 5: 229 words 4: aeronautic aficionado ...<bunch of words>... univariate
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. <lang rsplus>dict <- scan("https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt", what = character()) dictBig <- dict[nchar(dict) > 10] consonants <- letters[!letters %in% c("a", "e", "i", "o", "u")]
- 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 = ", "))</lang>
- 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>#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)))</lang>
- 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".
<lang perl6>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);</lang>
- 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. <lang rexx>/*REXX pgm finds words (within an identified dict.) which contain the most consonants.*/ parse arg minl iFID . /*obtain optional arguments from the CL*/ if minl== | minl=="," then minl= 11 /*Not specified? Then use the default.*/ 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)</lang>
- 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
<lang 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
</lang>
- 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...
Wren
<lang ecmascript>import "io" for File import "/fmt" for Fmt import "/seq" for Lst
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:") for (chunk in Lst.chunks(wordGroups[i], 5)) Fmt.print("$-14s", chunk) System.print() }
}</lang>
- 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
<lang 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); ]</lang>
- Output:
comprehensible