Find words with alternating vowels and consonants
- Task
Using the dictionary unixdict.txt, find words which odd letters are consonants and even letters are vowels or vice versa.
Display the words here (on this page).
The length of any word shown should have a length > 9.
- Metrics
- Counting
- Word frequency
- Letter frequency
- Jewels and stones
- I before E except after C
- Bioinformatics/base count
- Count occurrences of a substring
- Count how many vowels and consonants occur in a string
- Remove/replace
- XXXX redacted
- Conjugate a Latin verb
- Remove vowels from a string
- String interpolation (included)
- Strip block comments
- Strip comments from a string
- Strip a set of characters from a string
- Strip whitespace from a string -- top and tail
- Strip control codes and extended characters from a string
- Anagrams/Derangements/shuffling
- Word wheel
- ABC problem
- Sattolo cycle
- Knuth shuffle
- Ordered words
- Superpermutation minimisation
- Textonyms (using a phone text pad)
- Anagrams
- Anagrams/Deranged anagrams
- Permutations/Derangements
- Find/Search/Determine
- ABC words
- Odd words
- Word ladder
- Semordnilap
- Word search
- Wordiff (game)
- String matching
- Tea cup rim text
- Alternade words
- Changeable words
- State name puzzle
- String comparison
- Unique characters
- Unique characters in each string
- Extract file extension
- Levenshtein distance
- Palindrome detection
- Common list elements
- Longest common suffix
- Longest common prefix
- Compare a list of strings
- Longest common substring
- Find common directory path
- Words from neighbour ones
- Change e letters to i in words
- Non-continuous subsequences
- Longest common subsequence
- Longest palindromic substrings
- Longest increasing subsequence
- Words containing "the" substring
- Sum of the digits of n is substring of n
- Determine if a string is numeric
- Determine if a string is collapsible
- Determine if a string is squeezable
- Determine if a string has all unique characters
- Determine if a string has all the same characters
- Longest substrings without repeating characters
- Find words which contains all the vowels
- Find words which contain the most consonants
- Find words which contains more than 3 vowels
- Find words whose first and last three letters are equal
- Find words with alternating vowels and consonants
- Formatting
- Substring
- Rep-string
- Word wrap
- String case
- Align columns
- Literals/String
- Repeat a string
- Brace expansion
- Brace expansion using ranges
- Reverse a string
- Phrase reversals
- Comma quibbling
- Special characters
- String concatenation
- Substring/Top and tail
- Commatizing numbers
- Reverse words in a string
- Suffixation of decimal numbers
- Long literals, with continuations
- Numerical and alphabetical suffixes
- Abbreviations, easy
- Abbreviations, simple
- Abbreviations, automatic
- Song lyrics/poems/Mad Libs/phrases
- Mad Libs
- Magic 8-ball
- 99 bottles of beer
- The Name Game (a song)
- The Old lady swallowed a fly
- The Twelve Days of Christmas
- Tokenize
- Text between
- Tokenize a string
- Word break problem
- Tokenize a string with escaping
- Split a character string based on change of character
- Sequences
11l
V vowels = ‘aeiou’
V count = 0
L(word) File(‘unixdict.txt’).read().split("\n")
I word.len > 9
V first = word[0] C vowels
L(i) (2 .< word.len).step(2)
I (word[i] C vowels) != first
L.break
L.was_no_break
L(i) (1 .< word.len).step(2)
I (word[i] C vowels) == first
L.break
L.was_no_break
count++
print(word.rjust(14), end' I count % 7 == 0 {"\n"} E ‘ ’)
print()
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
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.
BYTE FUNC IsVovel(CHAR c)
IF c='a OR c='e OR c='i OR c='o OR c='u THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC IsValidWord(CHAR ARRAY word)
BYTE i,len,v
len=word(0)
IF len<=9 THEN RETURN (0) FI
v=IsVovel(word(1))
FOR i=2 TO len STEP 2
DO
IF IsVovel(word(i))=v THEN RETURN (0) FI
OD
FOR i=3 TO len STEP 2
DO
IF IsVovel(word(i))#v THEN RETURN (0) FI
OD
RETURN (1)
PROC FindWords(CHAR ARRAY fname)
CHAR ARRAY line(256)
CHAR ARRAY tmp(256)
BYTE pos,dev=[1]
pos=2
Close(dev)
Open(dev,fname,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
IF IsValidWord(line) THEN
IF pos+line(0)>=39 THEN
PutE() pos=2
FI
Print(line) Put(32)
pos==+line(0)+1
FI
OD
Close(dev)
RETURN
PROC Main()
CHAR ARRAY fname="H6:UNIXDICT.TXT"
FindWords(fname)
RETURN
- Output:
Screenshot from Atari 8-bit computer
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Ada
with Ada.Text_Io;
with Ada.Strings.Fixed;
procedure Find_Alternating is
use Ada.Text_Io;
function Is_Vowel (Letter : Character) return Boolean
is (Ada.Strings.Fixed.Index ("aeiou", "" & Letter) /= 0);
Filename : constant String := "unixdict.txt";
File : File_Type;
begin
Open (File, In_File, Filename);
while not End_Of_File (File) loop
declare
Word : constant String := Get_Line (File);
Failed : Boolean := False;
Vowel : Boolean := not Is_Vowel (Word (Word'First));
begin
for Letter of Word loop
if Vowel = Is_Vowel (letter) then
Failed := True;
exit;
end if;
Vowel := not Vowel;
end loop;
if not Failed and Word'Length > 9 then
Put_Line (Word);
end if;
end;
end loop;
Close (File);
end Find_Alternating;
ALGOL 68
# read the list of words and show words with alternating vowels and #
# consonants #
IF FILE input file;
STRING file name = "unixdict.txt";
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
print( ( "Unable to open """ + file name + """", newline ) )
ELSE
# file opened OK #
BOOL at eof := FALSE;
# set the EOF handler for the file #
on logical file end( input file, ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the #
# latest read #
at eof := TRUE;
# return TRUE so processing can continue #
TRUE
END
);
# returns the length of the string w #
OP LENGTH = ( STRING w )INT: ( UPB w - LWB w ) + 1;
# returns TRUE if c is a vowel, FALSE otherwise #
OP ISVOWEL = ( CHAR c )BOOL: ( c = "a" OR c = "e" OR c = "i" OR c = "o" OR c = "u" );
# blank pads s on the left to width characters #
PRIO PAD = 1;
OP PAD = ( INT width, STRING s )STRING: IF LENGTH s >= width THEN s ELSE ( " " * ( width - LENGTH s ) ) + s FI;
INT alternating count := 0;
WHILE STRING word;
get( input file, ( word, newline ) );
NOT at eof
DO
IF LENGTH word >= 10
THEN
# the word is at least 10 characters #
BOOL is alternating := TRUE;
BOOL have vowel := ISVOWEL word[ LWB word ];
FOR w pos FROM LWB word + 1 TO UPB word
WHILE BOOL had vowel = have vowel;
have vowel := ISVOWEL word[ w pos ];
is alternating := have vowel = NOT had vowel
DO SKIP OD;
IF is alternating THEN
# the characters of word alternate between vowels and #
# non-vowels #
alternating count +:= 1;
print( ( " ", 15 PAD word ) );
IF LENGTH word > 15 OR alternating count MOD 6 = 0 THEN
print( ( newline ) )
FI
FI
FI
OD;
close( input file );
print( ( newline, whole( alternating count, 0 ), " words of alternating vowels and consonants found", newline ) )
FI
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude 67 words of alternating vowels and consonants found
AppleScript
Idiomatic
The handler here is case- and diacritical-insensitive and has an option to treat "y" as a vowel. With the text file located on the computer's startup disk, it performs the set task in just under a third of a second on my machine, which is probably good enough for such a silly task.
(*
With AppleScript's text item delimiters set to all the vowels, the 'text items' of a word with alternating
vowels and consonants are single-character strings (the consonants), with the possibility of an empty
string at the beginning and/or end representing a leading and/or trailing vowel.
*)
on findWordsWithAlternatingVowelsAndConsonants from theText given minLength:minLength, yAsVowel:yAsVowel
script o
property wordList : theText's words
property output : {}
end script
set astid to AppleScript's text item delimiters
if (yAsVowel) then
set AppleScript's text item delimiters to {"a", "e", "i", "o", "u", "y"}
else
set AppleScript's text item delimiters to {"a", "e", "i", "o", "u"}
end if
ignoring case and diacriticals
repeat with thisWord in o's wordList
set thisWord to thisWord's contents
if ((count thisWord) ≥ minLength) then
set textItems to thisWord's text items
set a to 1
if ((count beginning of textItems) is 0) then set a to 2
set b to (count textItems)
if ((count end of textItems) is 0) then set b to b - 1
repeat with i from a to b
set alternating to ((count item i of textItems) is 1)
if (not alternating) then exit repeat
end repeat
if (alternating) then set end of o's output to thisWord
end if
end repeat
end ignoring
set AppleScript's text item delimiters to astid
return o's output
end findWordsWithAlternatingVowelsAndConsonants
-- Task code:
local theText
set theText to (read file ((path to desktop as text) & "unixdict.txt") as «class utf8»)
findWordsWithAlternatingVowelsAndConsonants from theText without yAsVowel given minLength:10
- Output:
{"aboriginal", "apologetic", "bimolecular", "borosilicate", "calorimeter", "capacitate", "capacitive", "capitoline", "capitulate", "caricature", "colatitude", "coloratura", "colorimeter", "debilitate", "decelerate", "decolonize", "definitive", "degenerate", "deliberate", "demodulate", "denominate", "denotative", "deregulate", "desiderata", "desideratum", "dilapidate", "diminutive", "epigenetic", "facilitate", "hemosiderin", "heretofore", "hexadecimal", "homogenate", "inoperative", "judicature", "latitudinal", "legitimate", "lepidolite", "literature", "locomotive", "manipulate", "metabolite", "nicotinamide", "oratorical", "paragonite", "pejorative", "peridotite", "peripatetic", "polarimeter", "recitative", "recuperate", "rehabilitate", "rejuvenate", "remunerate", "repetitive", "reticulate", "savonarola", "similitude", "solicitude", "tananarive", "telekinesis", "teratogenic", "topologize", "unilateral", "unimodular", "uninominal", "verisimilitude"}
Or if you want to treat "y" as a vowel:
-- Task code:
local theText
set theText to (read file ((path to desktop as text) & "unixdict.txt") as «class utf8»)
findWordsWithAlternatingVowelsAndConsonants from theText with yAsVowel given minLength:10
- Output:
{"aboriginal", "apologetic", "bimolecular", "borosilicate", "calorimeter", "capacitate", "capacitive", "capitoline", "capitulate", "caricature", "cohomology", "colatitude", "coloratura", "colorimeter", "debilitate", "decelerate", "decolonize", "definitive", "degeneracy", "degenerate", "dehumidify", "deliberate", "demodulate", "denominate", "denotative", "depositary", "depository", "deregulate", "deregulatory", "derogatory", "desiderata", "desideratum", "dicotyledon", "dilapidate", "diminutive", "epigenetic", "facilitate", "generosity", "hemosiderin", "hereditary", "heretofore", "heterodyne", "hexadecimal", "homogenate", "hypotenuse", "inoperative", "judicatory", "judicature", "laboratory", "latitudinal", "latitudinary", "legitimacy", "legitimate", "lepidolite", "literature", "locomotive", "locomotory", "luminosity", "manipulate", "metabolite", "mineralogy", "monocotyledon", "musicology", "nicotinamide", "numerology", "oratorical", "paragonite", "paramilitary", "pejorative", "peridotite", "peripatetic", "polarimeter", "polymerase", "pyrimidine", "pyroxenite", "recitative", "recuperate", "regulatory", "rehabilitate", "rejuvenate", "remunerate", "repetitive", "repository", "reticulate", "revelatory", "savonarola", "similitude", "solicitude", "solidarity", "tananarive", "telekinesis", "teratogenic", "teratology", "topologize", "toxicology", "unilateral", "unimodular", "uninominal", "verisimilitude", "veterinary", "vocabulary"}
Functional
Listing 'alternating' words for both {a,e,i,o,u} and {a,e,i,o,u,y} interpretations of 'vowel':
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
------------ ALTERNATING VOWELS AND CONSONANTS -----------
-- alternatingWordQuery :: String -> String
on alternatingWordQuery(vowels)
set regex to "^.*([" & vowels & "]{2}|[^" & vowels & "]{2}).*$"
"(9 < self.length) and not (self matches '" & regex & "')"
end alternatingWordQuery
-- matchingWords :: NSString -> String -> String
on matchingWords(lexicon)
script
on |λ|(vowels)
set query to alternatingWordQuery(vowels)
set matches to filteredLines(query, lexicon)
set intMatches to length of matches
("Assuming " & vowels & " – " & intMatches as text) & ¬
" matches:" & linefeed & linefeed & ¬
inColumns(4, matches)
end |λ|
end script
end matchingWords
--------------------------- TEST -------------------------
on run
set fpWordList to scriptFolder() & "unixdict.txt"
if doesFileExist(fpWordList) then
intercalate(linefeed & linefeed, ¬
map(matchingWords(readFile(fpWordList)), ¬
{"aeiou", "aeiouy"}))
else
display dialog "Word list not found in this script's folder:" & ¬
linefeed & tab & fpWordList
end if
end run
----------- GENERIC :: FILTERED LINES FROM FILE ----------
-- doesFileExist :: FilePath -> IO Bool
on doesFileExist(strPath)
set ca to current application
set oPath to (ca's NSString's stringWithString:strPath)'s ¬
stringByStandardizingPath
set {bln, int} to (ca's NSFileManager's defaultManager's ¬
fileExistsAtPath:oPath isDirectory:(reference))
bln and (int ≠ 1)
end doesFileExist
-- filteredLines :: String -> NSString -> [a]
on filteredLines(predicateString, s)
-- A list of lines filtered by an NSPredicate string
set ca to current application
set predicate to ca's NSPredicate's predicateWithFormat:predicateString
set array to ca's NSArray's ¬
arrayWithArray:(s's componentsSeparatedByString:(linefeed))
(array's filteredArrayUsingPredicate:(predicate)) as list
end filteredLines
-- readFile :: FilePath -> IO NSString
on readFile(strPath)
set ca to current application
set e to reference
set {s, e} to (ca's NSString's ¬
stringWithContentsOfFile:((ca's NSString's ¬
stringWithString:strPath)'s ¬
stringByStandardizingPath) ¬
encoding:(ca's NSUTF8StringEncoding) |error|:(e))
if missing value is e then
s
else
(localizedDescription of e) as string
end if
end readFile
-- scriptFolder :: () -> IO FilePath
on scriptFolder()
-- The path of the folder containing this script
try
tell application "Finder" to ¬
POSIX path of ((container of (path to me)) as alias)
on error
display dialog "Script file must be saved"
end try
end scriptFolder
-------------- GENERIC :: COLUMNAR FORMATTING ------------
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
-- Constructor for a pair of values,
-- possibly of two different types.
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- chunksOf :: Int -> [a] -> [[a]]
on chunksOf(k, xs)
script
on go(ys)
set ab to splitAt(k, ys)
set a to |1| of ab
if {} ≠ a then
{a} & go(|2| of ab)
else
a
end if
end go
end script
result's go(xs)
end chunksOf
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to {}
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & (|λ|(item i of xs, i, xs))
end repeat
end tell
if {text, string} contains class of xs then
acc as text
else
acc
end if
end concatMap
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- inColumns :: Int -> [String] -> String
on inColumns(n, xs)
-- The strings in xs displayed in n columns
-- of equal width.
set widest to maximum(map(my |length|, xs))
unlines(map(my unwords, chunksOf(n, ¬
map(justifyLeft(widest, space), xs))))
end inColumns
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set s to xs as text
set my text item delimiters to dlm
s
end intercalate
-- justifyLeft :: Int -> Char -> String -> String
on justifyLeft(n, cFiller)
script
on |λ|(s)
if n > length of s then
text 1 thru n of (s & replicate(n, cFiller))
else
s
end if
end |λ|
end script
end justifyLeft
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- maximum :: Ord a => [a] -> a
on maximum(xs)
script
on |λ|(a, b)
if a is missing value or b > a then
b
else
a
end if
end |λ|
end script
foldl(result, missing value, xs)
end maximum
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function
-- lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- replicate :: Int -> String -> String
on replicate(n, s)
-- Egyptian multiplication - progressively doubling a list,
-- appending stages of doubling to an accumulator where needed
-- for binary assembly of a target length
script p
on |λ|({n})
n ≤ 1
end |λ|
end script
script f
on |λ|({n, dbl, out})
if (n mod 2) > 0 then
set d to out & dbl
else
set d to out
end if
{n div 2, dbl & dbl, d}
end |λ|
end script
set xs to |until|(p, f, {n, s, ""})
item 2 of xs & item 3 of xs
end replicate
-- splitAt :: Int -> [a] -> ([a], [a])
on splitAt(n, xs)
if n > 0 and n < length of xs then
if class of xs is text then
Tuple(items 1 thru n of xs as text, ¬
items (n + 1) thru -1 of xs as text)
else
Tuple(items 1 thru n of xs, items (n + 1) thru -1 of xs)
end if
else
if n < 1 then
Tuple({}, xs)
else
Tuple(xs, {})
end if
end if
end splitAt
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set v to x
set mp to mReturn(p)
set mf to mReturn(f)
repeat until mp's |λ|(v)
set v to mf's |λ|(v)
end repeat
v
end |until|
-- unwords :: [String] -> String
on unwords(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, space}
set s to xs as text
set my text item delimiters to dlm
return s
end unwords
- Output:
Assuming aeiou – 67 matches: aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude Assuming aeiouy – 101 matches: aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature cohomology colatitude coloratura colorimeter debilitate decelerate decolonize definitive degeneracy degenerate dehumidify deliberate demodulate denominate denotative depositary depository deregulate deregulatory derogatory desiderata desideratum dicotyledon dilapidate diminutive epigenetic facilitate generosity hemosiderin hereditary heretofore heterodyne hexadecimal homogenate hypotenuse inoperative judicatory judicature laboratory latitudinal latitudinary legitimacy legitimate lepidolite literature locomotive locomotory luminosity manipulate metabolite mineralogy monocotyledon musicology nicotinamide numerology oratorical paragonite paramilitary pejorative peridotite peripatetic polarimeter polymerase pyrimidine pyroxenite recitative recuperate regulatory rehabilitate rejuvenate remunerate repetitive repository reticulate revelatory savonarola similitude solicitude solidarity tananarive telekinesis teratogenic teratology topologize toxicology unilateral unimodular uninominal verisimilitude veterinary vocabulary
Arturo
words: read.lines relative "unixdict.txt"
vowels: [`a` `e` `i` `o` `u`]
alternatingVC?: function [w][
lookForConsonant: true
if contains? vowels first w -> lookForConsonant: false
loop w 'c [
if xnor? lookForConsonant
contains? vowels c -> return false
lookForConsonant: not? lookForConsonant
]
return true
]
loop words 'word [
if 9 < size word [
if alternatingVC? word ->
print word
]
]
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
AutoHotkey
FileRead, db, % A_Desktop "\unixdict.txt"
vowels := {"a":1, "e":1, "i":1, "o":1, "u":1}, c := 0
Main:
for i, word in StrSplit(db, "`n", "`r")
{
if StrLen(word) < 10
continue
vCount := cCount := 0
while (letter := SubStr(word, A_Index, 1))
{
if vowels[letter]
vCount++, cCount:=0
else
vCount:=0, cCount++
if (vCount > 1 || cCount > 1)
continue main
}
c++
result .= word (Mod(c, 9) ? "`t" : "`n")
}
MsgBox, 262144, , % result
return
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
AWK
( length( $1 ) >= 10 ) \
{
# have an appropriate length word
word = $1;
haveVowel = word ~ /^[aeiou]/;
isAlternating = 1;
for( wPos = 2; isAlternating && wPos <= length( word ); wPos ++ )
{
hadVowel = haveVowel;
haveVowel = substr( word, wPos, 1 ) ~ /^[aeiou]/;
isAlternating = ( hadVowel && ! haveVowel ) || ( ! hadVowel && haveVowel );
} # for wPos
if( isAlternating )
{
printf( " %16s%s", word, ( alternatingCount % 6 == 5 ) ? "\n" : "" );
alternatingCount += 1;
} # if isAlternating
}
END \
{
printf( "\n%d words with alternating vowels and consonants found\n", alternatingCount );
} # END
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude 67 words with alternating vowels and consonants found
C
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 80
bool is_vowel(char ch) {
switch (ch) {
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
return true;
}
return false;
}
bool alternating_vowels_and_consonants(const char* str, size_t len) {
for (size_t i = 1; i < len; ++i) {
if (is_vowel(str[i]) == is_vowel(str[i - 1]))
return false;
}
return true;
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* fp = fopen(filename, "r");
if (!fp) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
int n = 1;
while (fgets(line, sizeof(line), fp)) {
size_t len = strlen(line) - 1; // last character is \n
if (len > 9 && alternating_vowels_and_consonants(line, len))
printf("%2d: %s", n++, line);
}
fclose(fp);
return EXIT_SUCCESS;
}
- Output:
1: aboriginal 2: apologetic 3: bimolecular 4: borosilicate 5: calorimeter 6: capacitate 7: capacitive 8: capitoline 9: capitulate 10: caricature 11: colatitude 12: coloratura 13: colorimeter 14: debilitate 15: decelerate 16: decolonize 17: definitive 18: degenerate 19: deliberate 20: demodulate 21: denominate 22: denotative 23: deregulate 24: desiderata 25: desideratum 26: dilapidate 27: diminutive 28: epigenetic 29: facilitate 30: hemosiderin 31: heretofore 32: hexadecimal 33: homogenate 34: inoperative 35: judicature 36: latitudinal 37: legitimate 38: lepidolite 39: literature 40: locomotive 41: manipulate 42: metabolite 43: nicotinamide 44: oratorical 45: paragonite 46: pejorative 47: peridotite 48: peripatetic 49: polarimeter 50: recitative 51: recuperate 52: rehabilitate 53: rejuvenate 54: remunerate 55: repetitive 56: reticulate 57: savonarola 58: similitude 59: solicitude 60: tananarive 61: telekinesis 62: teratogenic 63: topologize 64: unilateral 65: unimodular 66: uninominal 67: verisimilitude
C++
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
bool is_vowel(char ch) {
switch (ch) {
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
return true;
}
return false;
}
bool alternating_vowels_and_consonants(const std::string& str) {
for (size_t i = 1, len = str.size(); i < len; ++i) {
if (is_vowel(str[i]) == is_vowel(str[i - 1]))
return false;
}
return true;
}
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 line;
for (int n = 1; getline(in, line); ) {
if (line.size() > 9 && alternating_vowels_and_consonants(line))
std::cout << std::setw(2) << n++ << ": " << line << '\n';
}
return EXIT_SUCCESS;
}
- Output:
1: aboriginal 2: apologetic 3: bimolecular 4: borosilicate 5: calorimeter 6: capacitate 7: capacitive 8: capitoline 9: capitulate 10: caricature 11: colatitude 12: coloratura 13: colorimeter 14: debilitate 15: decelerate 16: decolonize 17: definitive 18: degenerate 19: deliberate 20: demodulate 21: denominate 22: denotative 23: deregulate 24: desiderata 25: desideratum 26: dilapidate 27: diminutive 28: epigenetic 29: facilitate 30: hemosiderin 31: heretofore 32: hexadecimal 33: homogenate 34: inoperative 35: judicature 36: latitudinal 37: legitimate 38: lepidolite 39: literature 40: locomotive 41: manipulate 42: metabolite 43: nicotinamide 44: oratorical 45: paragonite 46: pejorative 47: peridotite 48: peripatetic 49: polarimeter 50: recitative 51: recuperate 52: rehabilitate 53: rejuvenate 54: remunerate 55: repetitive 56: reticulate 57: savonarola 58: similitude 59: solicitude 60: tananarive 61: telekinesis 62: teratogenic 63: topologize 64: unilateral 65: unimodular 66: uninominal 67: verisimilitude
Delphi
Runtime = 4.3 ms.
var Dict: TStringList; {List holds dictionary}
function IsVowel(C: char): boolean;
begin
Result:=C in ['a','e','i','o','u'];
end;
function DoesAlternate(S: string): boolean;
var I: integer;
var Vowel: boolean;
begin
Result:=False;
Vowel:=IsVowel(S[1]);
for I:=2 to Length(S) do
begin
if not (Vowel xor IsVowel(S[I])) then exit;
Vowel:=IsVowel(S[I]);
end;
Result:=True;
end;
procedure AlternateVowelConsonant(Memo: TMemo);
{Find words where the letters alternate vowel,consonant}
var I,Cnt: integer;
var S: string;
begin
S:=''; Cnt:=0;
for I:=0 to Dict.Count-1 do
if Length(Dict[I])>9 then
begin
if DoesAlternate(Dict[I]) then
begin
Inc(Cnt);
S:=S+Format('%-23s',[Dict[I]]);
if (Cnt mod 4)=0 then S:=S+#$0D#$0A
end
end;
Memo.Lines.Add(IntToStr(Cnt)+' Alternate Vowel/Consonant words found.');
Memo.Lines.Add(S);
end;
initialization
{Create/load dictionary}
Dict:=TStringList.Create;
Dict.LoadFromFile('unixdict.txt');
Dict.Sorted:=True;
finalization
Dict.Free;
end.
- Output:
67 Alternate Vowel/Consonant words found. aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
F#
// Find words with alternating vowels and consonants. Nigel Galloway: January 20th., 2020
let vowels=set['a';'e';'i';'o';'u']
let fN g=let rec fN g=function h::t->(if g<>vowels.Contains h then fN (not g) t else false)|_->true
fN (vowels.Contains(Seq.head g)) (Seq.tail g|>List.ofSeq)
seq{use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()}
|>Seq.filter(fun g->g.Length>9 && fN g)|>Seq.iter(printfn "%s")
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Factor
group-by
is used to group words by vowels and consonants. For example, "hello" [ "aeiou" member? ] group-by
produces a sequence like { 'h' 'e' 'll' 'o' }
. The number of elements in this grouping is the same as the length of the original word if and only if it has alternating vowels and consonants.
USING: grouping.extras io.encodings.ascii io.files kernel math
prettyprint sequences ;
"unixdict.txt" ascii file-lines
[ length 9 > ] filter
[ dup [ "aeiou" member? ] group-by [ length ] same? ] filter .
- Output:
{ "aboriginal" "apologetic" "bimolecular" "borosilicate" "calorimeter" "capacitate" "capacitive" "capitoline" "capitulate" "caricature" "colatitude" "coloratura" "colorimeter" "debilitate" "decelerate" "decolonize" "definitive" "degenerate" "deliberate" "demodulate" "denominate" "denotative" "deregulate" "desiderata" "desideratum" "dilapidate" "diminutive" "epigenetic" "facilitate" "hemosiderin" "heretofore" "hexadecimal" "homogenate" "inoperative" "judicature" "latitudinal" "legitimate" "lepidolite" "literature" "locomotive" "manipulate" "metabolite" "nicotinamide" "oratorical" "paragonite" "pejorative" "peridotite" "peripatetic" "polarimeter" "recitative" "recuperate" "rehabilitate" "rejuvenate" "remunerate" "repetitive" "reticulate" "savonarola" "similitude" "solicitude" "tananarive" "telekinesis" "teratogenic" "topologize" "unilateral" "unimodular" "uninominal" "verisimilitude" }
Forth
: vowel? ( c -- ? )
case
'a' of true endof
'e' of true endof
'i' of true endof
'o' of true endof
'u' of true endof
0 swap
endcase ;
: alternating-vowels-and-consonants { addr len -- ? }
len 9 <= if false exit then
len 1 do
addr i + c@ vowel? addr i 1- + c@ vowel? = if
unloop false exit
then
loop true ;
256 constant max-line
: main
0 0 { count fd-in }
s" unixdict.txt" r/o open-file throw to fd-in
begin
here max-line fd-in read-line throw
while
here swap 2dup alternating-vowels-and-consonants if
count 1+ to count
count 2 .r ." : " type cr
else
2drop
then
repeat
drop
fd-in close-file throw ;
main
bye
- Output:
1: aboriginal 2: apologetic 3: bimolecular 4: borosilicate 5: calorimeter 6: capacitate 7: capacitive 8: capitoline 9: capitulate 10: caricature 11: colatitude 12: coloratura 13: colorimeter 14: debilitate 15: decelerate 16: decolonize 17: definitive 18: degenerate 19: deliberate 20: demodulate 21: denominate 22: denotative 23: deregulate 24: desiderata 25: desideratum 26: dilapidate 27: diminutive 28: epigenetic 29: facilitate 30: hemosiderin 31: heretofore 32: hexadecimal 33: homogenate 34: inoperative 35: judicature 36: latitudinal 37: legitimate 38: lepidolite 39: literature 40: locomotive 41: manipulate 42: metabolite 43: nicotinamide 44: oratorical 45: paragonite 46: pejorative 47: peridotite 48: peripatetic 49: polarimeter 50: recitative 51: recuperate 52: rehabilitate 53: rejuvenate 54: remunerate 55: repetitive 56: reticulate 57: savonarola 58: similitude 59: solicitude 60: tananarive 61: telekinesis 62: teratogenic 63: topologize 64: unilateral 65: unimodular 66: uninominal 67: verisimilitude
FreeBASIC
dim as string s, c
dim as boolean v = false, lv = false
dim as integer i, n, a=0
open "unixdict.txt" for input as #1
while not eof(1)
line input #1, s
n = len(s)
if n<10 then continue while
for i = 1 to n
c = mid(s,i,1)
if c="a" or c="e" or c="i" or c="o" or c="u" then
v = true
else
v = false
end if
'print c, v, lv
if v = lv and i>1 then continue while
lv = v
next i
a+=1
print s;" ";
if a mod 10 = 0 then print
wend
close #1
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
FutureBasic
include "NSLog.incl"
local fn LoadDictionaryIntoMemory
CFURLRef url = fn URLWithString( @"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" )
CFStringRef dictStr = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
AppSetProperty( @"dictionary", dictStr )
end fn
local fn HasAlternatingVowelsAndConsonants( wordStr as CFStringRef ) as BOOL
NSUInteger i, count = len( wordStr )
CFCharacterSetRef vowels = fn CharacterSetWithCharactersInString( @"aeiouAEIOU" )
CFMutableCharacterSetRef consonants = fn MutableCharacterSetLetterSet
MutableCharacterSetRemoveCharactersInString( consonants, @"aeiouAEIOU" )
CFCharacterSetRef vowelsInvertedSet = fn CharacterSetInvertedSet( vowels )
BOOL isVowelExpected = fn CharacterSetCharacterIsMember( vowelsInvertedSet, fn StringCharacterAtIndex( wordStr, 0 ) )
for i = 1 to count - 1
unichar chr = fn StringCharacterAtIndex( wordStr, i )
BOOL isVowel = fn CharacterSetCharacterIsMember( vowels, chr )
if ( (isVowel && isVowelExpected) || (!isVowel && !isVowelExpected) )
isVowelExpected = !isVowelExpected
else
exit fn = NO
end if
next
end fn = YES
local fn FindQualifiers
CFStringRef testWord
NSUInteger i = 1
CFStringRef dictStr = fn AppProperty( @"dictionary" )
CFArrayRef dictArray = fn StringComponentsSeparatedByString( dictStr, @"\n" )
CFMutableStringRef mutStr = fn MutableStringNew
for testWord in dictArray
if ( len( testWord ) > 9 )
if ( fn HasAlternatingVowelsAndConsonants( testWord ) )
MutableStringAppendString( mutStr, fn StringWithFormat( @"%3d. %@\n", i, testWord ) )
i++
end if
end if
next
NSLog( @"%@", mutStr )
end fn
fn LoadDictionaryIntoMemory
fn FindQualifiers
HandleEvents
- Output:
1. aboriginal 2. apologetic 3. bimolecular 4. borosilicate 5. calorimeter 6. capacitate 7. capacitive 8. capitoline 9. capitulate 10. caricature 11. colatitude 12. coloratura 13. colorimeter 14. debilitate 15. decelerate 16. decolonize 17. definitive 18. degenerate 19. deliberate 20. demodulate 21. denominate 22. denotative 23. deregulate 24. desiderata 25. desideratum 26. dilapidate 27. diminutive 28. epigenetic 29. facilitate 30. hemosiderin 31. heretofore 32. hexadecimal 33. homogenate 34. inoperative 35. judicature 36. latitudinal 37. legitimate 38. lepidolite 39. literature 40. locomotive 41. manipulate 42. metabolite 43. nicotinamide 44. oratorical 45. paragonite 46. pejorative 47. peridotite 48. peripatetic 49. polarimeter 50. recitative 51. recuperate 52. rehabilitate 53. rejuvenate 54. remunerate 55. repetitive 56. reticulate 57. savonarola 58. similitude 59. solicitude 60. tananarive 61. telekinesis 62. teratogenic 63. topologize 64. unilateral 65. unimodular 66. uninominal 67. verisimilitude
Go
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
"unicode/utf8"
)
func isVowel(c rune) bool { return strings.ContainsRune("aeiou", c) }
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) > 9 {
words = append(words, s)
}
}
count := 0
fmt.Println("Words with alternate consonants and vowels in", wordList, "\b:\n")
for _, word := range words {
found := true
for i, c := range word {
if (i%2 == 0 && isVowel(c)) || (i%2 == 1 && !isVowel(c)) {
found = false
break
}
}
if !found {
found = true
for i, c := range word {
if (i%2 == 0 && !isVowel(c)) || (i%2 == 1 && isVowel(c)) {
found = false
break
}
}
}
if found {
count++
fmt.Printf("%2d: %s\n", count, word)
}
}
}
- Output:
Words with alternate consonants and vowels in unixdict.txt: 1: aboriginal 2: apologetic 3: bimolecular 4: borosilicate 5: calorimeter 6: capacitate 7: capacitive 8: capitoline 9: capitulate 10: caricature 11: colatitude 12: coloratura 13: colorimeter 14: debilitate 15: decelerate 16: decolonize 17: definitive 18: degenerate 19: deliberate 20: demodulate 21: denominate 22: denotative 23: deregulate 24: desiderata 25: desideratum 26: dilapidate 27: diminutive 28: epigenetic 29: facilitate 30: hemosiderin 31: heretofore 32: hexadecimal 33: homogenate 34: inoperative 35: judicature 36: latitudinal 37: legitimate 38: lepidolite 39: literature 40: locomotive 41: manipulate 42: metabolite 43: nicotinamide 44: oratorical 45: paragonite 46: pejorative 47: peridotite 48: peripatetic 49: polarimeter 50: recitative 51: recuperate 52: rehabilitate 53: rejuvenate 54: remunerate 55: repetitive 56: reticulate 57: savonarola 58: similitude 59: solicitude 60: tananarive 61: telekinesis 62: teratogenic 63: topologize 64: unilateral 65: unimodular 66: uninominal 67: verisimilitude
Haskell
import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.List.Split (chunksOf)
------- WORDS WITH ALTERNATING VOWELS AND CONSONANTS -----
isLongAlternator :: String -> Bool
isLongAlternator s =
9 < length s
&& all alternating (zip s $ tail s)
alternating :: (Char, Char) -> Bool
alternating = uncurry (/=) . join bimap isVowel
isVowel :: Char -> Bool
isVowel = flip elem "aeiou"
--------------------------- TEST -------------------------
main :: IO ()
main =
readFile "unixdict.txt"
>>= mapM_ putStrLn
. ( ((:) . (<> " matching words:\n") . show . length)
<*> inColumns 4
)
. filter isLongAlternator
. lines
------------------------ FORMATTING ----------------------
inColumns :: Int -> [String] -> [String]
inColumns n xs = unwords <$> chunksOf n (justifyLeft w ' ' <$> xs)
where
w = maximum (length <$> xs)
justifyLeft :: Int -> Char -> String -> String
justifyLeft n c s = take n (s <> replicate n c)
- Output:
67 matching words: aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
J
We're looking for words which have more than 9 letters and where any adjacent pair of letters has both a vowel and a consonant.
>(#~ (*/@(2 ~:/\ e.&'aeiou')*9<#)@>) cutLF fread'unixdict.txt'
aboriginal
apologetic
bimolecular
borosilicate
calorimeter
capacitate
capacitive
capitoline
capitulate
caricature
colatitude
coloratura
colorimeter
debilitate
decelerate
decolonize
definitive
degenerate
deliberate
demodulate
denominate
denotative
deregulate
desiderata
desideratum
dilapidate
diminutive
epigenetic
facilitate
hemosiderin
heretofore
hexadecimal
homogenate
inoperative
judicature
latitudinal
legitimate
lepidolite
literature
locomotive
manipulate
metabolite
nicotinamide
oratorical
paragonite
pejorative
peridotite
peripatetic
polarimeter
recitative
recuperate
rehabilitate
rejuvenate
remunerate
repetitive
reticulate
savonarola
similitude
solicitude
tananarive
telekinesis
teratogenic
topologize
unilateral
unimodular
uninominal
verisimilitude
JavaScript
As a standard for an embedded language which may have no access to a file-system, ECMAScript doesn't define any syntax or types for file operations.
This draft defines a readFile function for the Automation library of a macOS osascript instance of a JSContext.
(() => {
'use strict';
// -- WORDS WITH ALTERNATING VOWELS AND CONSONANTS ---
// isLongAlternator :: String -> Bool
const isLongAlternator = s =>
9 < s.length && all(
ab => isVowel(ab[0]) !== isVowel(ab[1])
)(
zip(s)(s.slice(1))
);
// isVowel :: Char -> Bool
const isVowel = c =>
'aeiou'.includes(c);
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
const
matches = lines(
readFile('unixdict.txt')
).filter(isLongAlternator);
return `${matches.length} matches:\n\n` + (
inColumns(4)(matches)
);
};
// ------------------- FORMATTING --------------------
// inColumns :: Int -> [String] -> String
const inColumns = n =>
xs => (
w => unlines(
chunksOf(n)(
xs.map(justifyLeft(w)(' '))
)
.map(unwords)
)
)(
maximum(xs.map(length))
);
// --------------------- GENERIC ---------------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// all :: (a -> Bool) -> [a] -> Bool
const all = p =>
// True if p(x) holds for every x in xs.
xs => [...xs].every(p);
// chunksOf :: Int -> [a] -> [[a]]
const chunksOf = n => {
// xs split into sublists of length n.
// The last sublist will be short if n
// does not evenly divide the length of xs .
const go = xs => {
const
chunk = xs.slice(0, n),
rest = xs.slice(n);
return 0 < chunk.length ? (
[chunk].concat(go(rest))
) : [];
};
return go;
};
// justifyLeft :: Int -> Char -> String -> String
const justifyLeft = n =>
// The string s, followed by enough padding (with
// the character c) to reach the string length n.
c => s => n > s.length ? (
s.padEnd(n, c)
) : s;
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
'GeneratorFunction' !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
// lines :: String -> [String]
const lines = s =>
// A list of strings derived from a single
// string delimited by newline and or CR.
0 < s.length ? (
s.split(/[\r\n]+/)
) : [];
// list :: StringOrArrayLike b => b -> [a]
const list = xs =>
// xs itself, if it is an Array,
// or an Array derived from xs.
Array.isArray(xs) ? (
xs
) : Array.from(xs || []);
// maximum :: Ord a => [a] -> a
const maximum = xs => (
// The largest value in a non-empty list.
ys => 0 < ys.length ? (
ys.slice(1).reduce(
(a, y) => y > a ? (
y
) : a, ys[0]
)
) : undefined
)(list(xs));
// readFile :: FilePath -> IO String
const readFile = fp => {
// The contents of a text file at the
// filepath fp.
const
e = $(),
ns = $.NSString
.stringWithContentsOfFileEncodingError(
$(fp).stringByStandardizingPath,
$.NSUTF8StringEncoding,
e
);
return ObjC.unwrap(
ns.isNil() ? (
e.localizedDescription
) : ns
);
};
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
// unwords :: [String] -> String
const unwords = xs =>
// A space-separated string derived
// from a list of words.
xs.join(' ');
// zip :: [a] -> [b] -> [(a, b)]
const zip = xs =>
// The paired members of xs and ys, up to
// the length of the shorter of the two lists.
ys => Array.from({
length: Math.min(xs.length, ys.length)
}, (_, i) => Tuple(xs[i])(ys[i]));
// MAIN ---
return main();
})();
- Output:
67 matches: aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
jq
Works with gojq, the Go implementation of jq
# input: an array
# output: if the $parity elements are all in $array then true, else false
def check($parity; $array):
. as $in
| all( range(0+$parity; length; 2); $in[.]|IN($array[]));
def alternating:
def c: explode[0];
("aeiou" | explode) as $vowels
| ([range("a"|c; ("z"|c)+1)] - $vowels) as $consonants
| inputs
| select(length>9)
| . as $word
| explode
| select(
(check(0; $consonants) and check(1; $vowels)) or
(check(1; $consonants) and check(0; $vowels)) )
| $word ;
alternating
- Output:
Invocation example: jq -nrR -f program.jq unixdict.txt
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Julia
See Alternade_words#Julia for the foreachword function.
isvowel(c) = c in ['a', 'e', 'i', 'o', 'u'] # NB. leaves out 'α' and similar unicode vowels, and what about y?
onlyodds(f, s) = all(c -> f(c), s[1:2:length(s)]) && !any(c -> f(c), s[2:2:length(s)])
onlyevens(f, s) = !any(c -> f(c), s[1:2:length(s)]) && all(c -> f(c), s[2:2:length(s)])
eitheronlyvowels(w, _) = onlyodds(isvowel, w) || onlyevens(isvowel, w) ? w : ""
foreachword("unixdict.txt", eitheronlyvowels, minlen = 10)
- Output:
Word source: unixdict.txt aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Ksh
#!/bin/ksh
# Find words with alternating vowels and consonants
# # Variables:
#
dict='../unixdict.txt'
integer MINLENGTH=10
vowels='a|e|i|o|u'
# # Functions:
#
# # Function _isvowel(ch) - Return 1 if letter is a vowel
#
function _isvowel {
typeset _ch ; typeset -l -L1 _ch="$1"
[[ ${_ch} == @(${vowels}) ]] && return 1
return 0
}
# # Function _isalternating(str) - Return 1 if letter alternate vowel/const.
#
function _isalternating {
typeset _str ; typeset -l _str="$1"
typeset _i _rc ; integer _i _rc
for ((_i=0; _i<${#_str}-1; _i++)); do
_isvowel ${_str:${_i}:1} ; _rc=$?
_isvowel ${_str:$((_i+1)):1}
(( $? == _rc )) && return 0
done
return 1
}
######
# main #
######
while read; do
(( ${#REPLY} < MINLENGTH )) && continue
_isalternating "$REPLY"
(( $? )) && print "$REPLY"
done < ${dict}
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal
verisimilitude
Mathematica /Wolfram Language
vowels = Characters["euioa"];
consonants = DeleteCases[Alphabet[], Alternatives @@ vowels];
dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]];
dict //= StringSplit[#, "\n"] &;
dict //= Select[StringLength /* GreaterThan[9]];
dict //=
Select[(ContainsAll[vowels, Characters[StringTake[#, {1, -1, 2}]]] &&
ContainsAll[consonants,
Characters[StringTake[#, {2, -1, 2}]]]) || (ContainsAll[
consonants, Characters[StringTake[#, {1, -1, 2}]]] &&
ContainsAll[vowels, Characters[StringTake[#, {2, -1, 2}]]]) &]
- Output:
{aboriginal, apologetic, bimolecular, borosilicate, calorimeter, capacitate, capacitive, capitoline, capitulate, caricature, colatitude, coloratura, colorimeter, debilitate, decelerate, decolonize, definitive, degenerate, deliberate, demodulate, denominate, denotative, deregulate, desiderata, desideratum, dilapidate, diminutive, epigenetic, facilitate, hemosiderin, heretofore, hexadecimal, homogenate, inoperative, judicature, latitudinal, legitimate, lepidolite, literature, locomotive, manipulate, metabolite, nicotinamide, oratorical, paragonite, pejorative, peridotite, peripatetic, polarimeter, recitative, recuperate, rehabilitate, rejuvenate, remunerate, repetitive, reticulate, savonarola, similitude, solicitude, tananarive, telekinesis, teratogenic, topologize, unilateral, unimodular, uninominal, verisimilitude}
MiniScript
This implementation is for use with the Mini Micro version of MiniScript. The command-line version does not include a HTTP library. The script can be modified to use the file class to read a local copy of the word list.
isVowel = function(c)
return "aeiou".indexOf(c) != null
end function
isAlternating = function(word)
compVowelState= isVowel(word[0])
for i in range(1, word.len - 1)
if isVowel(word[i]) == compVowelState then return false
compVowelState = not compVowelState
end for
return true
end function
wordList = http.get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").split(char(10))
results = []
for word in wordList
if word.len >9 and isAlternating(word) then results.push(word)
end for
c = 0
for word in results
word = (word + " " * 5)[:15] // padded for printing
print word, ""
c = c + 1
if c % 4 == 0 then print
end for
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Nim
import strutils
const Vowels = {'a', 'e', 'i', 'o', 'u'}
var count = 0
for word in "unixdict.txt".lines:
if word.len > 9:
block checkWord:
let first = word[0] in Vowels
for i in countup(2, word.high, 2):
if word[i] in Vowels != first: break checkWord
for i in countup(1, word.high, 2):
if word[i] in Vowels == first: break checkWord
inc count
stdout.write word.align(14), if count mod 7 == 0: '\n' else: ' '
echo()
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Perl
Translated from AWK
Used a2p.
# 20210104 added Perl programming solution
use strict;
use warnings;
my $alternatingCount = 0;
while (<>) {
(my $Fld1) = split(' ', $_, -1);
if ((length($Fld1) >= 10)) { # have an arpropriate length word
my $word = $Fld1;
my $haveVowel = $word =~ /^[aeiou]/;
my $isAlternating = 1;
for (my $wPos = 2; $isAlternating && $wPos <= length($word); $wPos++) {
my $hadVowel = $haveVowel;
$haveVowel = substr($word, ($wPos)-1, 1) =~ /^[aeiou]/;
$isAlternating = ($hadVowel && !$haveVowel) || (!$hadVowel && $haveVowel);
} # for wPos
if ($isAlternating) {
printf ' %16s%s', $word, ($alternatingCount % 6 == 5) ? "\n" : '';
$alternatingCount += 1;
} # if isAlternating
}
}
printf "\n%d words with alternating vowels and consonants found\n", $alternatingCount;
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude 67 words with alternating vowels and consonants found
Regex solution
I've heard rumors that there are more than 5 vowels...
$vowels = 'aeiou';
$v = qr/[$vowels]/;
$c = qr/[^$vowels]/;
/^ ( ($c$v)+ $c? | ($v$c)+ $v? ) $/ix and say for grep { /.{10}/ } split "\n", do { (@ARGV, $/) = 'unixdict.txt'; <> };
- Output:
aboriginal apologetic bimolecular ... verisimilitude
Phix
with javascript_semantics function vowel(integer ch) return find(ch,"aeiou")!=0 end function function oddeven(string word) if length(word)<=9 then return false end if sequence consonants = apply(word,vowel), ohoneohone = apply(tagset(length(word)),odd) return find(consonants,{ohoneohone,sq_not(ohoneohone)}) end function sequence words = filter(unix_dict(),oddeven) printf(1,"%d avac words found: %s\n",{length(words),join(shorten(words,"",3),", ")})
- Output:
67 avac words found: aboriginal, apologetic, bimolecular, ..., unimodular, uninominal, verisimilitude
Plain English
To run:
Start up.
Put "c:\unixdict.txt" into a path.
Read the path into a buffer.
Slap a rider on the buffer.
Loop.
Move the rider (text file rules).
Subtract 1 from the rider's token's last. \remove the newline
Put the rider's token into a word string.
If the word is blank, break.
If the word's length is less than 10, repeat.
If the word is alternating between vowels and consonants, write the word on the console.
Repeat.
Wait for the escape key.
Shut down.
To decide if a string is alternating between vowels and consonants:
Slap a substring on the string.
Put the substring's first plus 1 into the substring's last.
Loop.
If the substring's last's target is noise, say yes.
If the substring is double, say no.
Add 1 to the substring's first.
Add 1 to the substring's last.
Repeat.
To decide if a string is double:
If the string's first's target is any consonant, set a flag.
If the string's last's target is any consonant, set another flag.
If the flag is the other flag, say yes.
Say no.
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Prolog
main:-
open("unixdict.txt", read, Stream),
main(Stream, 0),
close(Stream).
main(Stream, Count):-
read_line_to_string(Stream, String),
String \= end_of_file,
!,
process_line(String, Count, Count1),
main(Stream, Count1).
main(_, _).
process_line(String, Count, Count1):-
string_chars(String, Chars),
length(Chars, Length),
Length > 9,
alternating_vowels_and_consonants(Chars),
!,
Count1 is Count + 1,
writef('%3r: %w\n', [Count1, String]).
process_line(_, Count, Count).
vowel('a').
vowel('e').
vowel('i').
vowel('o').
vowel('u').
alternating_vowels_and_consonants([_]):-!.
alternating_vowels_and_consonants([Ch1, Ch2|Chars]):-
(vowel(Ch1) -> \+vowel(Ch2) ; vowel(Ch2)),
alternating_vowels_and_consonants([Ch2|Chars]).
- Output:
1: aboriginal 2: apologetic 3: bimolecular 4: borosilicate 5: calorimeter 6: capacitate 7: capacitive 8: capitoline 9: capitulate 10: caricature 11: colatitude 12: coloratura 13: colorimeter 14: debilitate 15: decelerate 16: decolonize 17: definitive 18: degenerate 19: deliberate 20: demodulate 21: denominate 22: denotative 23: deregulate 24: desiderata 25: desideratum 26: dilapidate 27: diminutive 28: epigenetic 29: facilitate 30: hemosiderin 31: heretofore 32: hexadecimal 33: homogenate 34: inoperative 35: judicature 36: latitudinal 37: legitimate 38: lepidolite 39: literature 40: locomotive 41: manipulate 42: metabolite 43: nicotinamide 44: oratorical 45: paragonite 46: pejorative 47: peridotite 48: peripatetic 49: polarimeter 50: recitative 51: recuperate 52: rehabilitate 53: rejuvenate 54: remunerate 55: repetitive 56: reticulate 57: savonarola 58: similitude 59: solicitude 60: tananarive 61: telekinesis 62: teratogenic 63: topologize 64: unilateral 65: unimodular 66: uninominal 67: verisimilitude
Python
'''Words with alternating vowels and consonants'''
# isLongAlternator :: String -> Bool
def isLongAlternator(s):
'''True if s has 10 or more characters,
and no two successive characters that are
both vowels, or both consonants.
'''
def p(a, b):
return isVowel(a) != isVowel(b)
return 9 < len(s) and all(map(p, s, s[1:]))
def isVowel(c):
'''True if c is in the set {a, e, i, o, u}
'''
return c in 'aeiou'
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Words without successive vowels or consonants
found in the file 'unixdict.txt'
'''
matches = [
x for x in readFile('unixdict.txt').splitlines()
if isLongAlternator(x)
]
w = max(len(x) for x in matches)
print(str(len(matches)) + ' matching words:\n')
print(
'\n'.join(
' '.join(s) for s in chunksOf(4)([
x.ljust(w, ' ') for x in matches
])
)
)
# ----------------------- GENERIC ------------------------
# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
'''A series of lists of length n, subdividing the
contents of xs. Where the length of xs is not evenly
divible, the final list will be shorter than n.
'''
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
# readFile :: FilePath -> IO String
def readFile(fp):
'''The contents of any file at the path.
'''
with open(fp, 'r', encoding='utf-8') as f:
return f.read()
# MAIN ---
if __name__ == '__main__':
main()
- Output:
67 matching words: aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Quackery
[ [] swap ]'[ swap
witheach
[ dup nested
unrot over do
iff [ dip join ]
else nip ]
drop ] is filter ( [ --> [ )
[ [ 0
26 times
[ i^ char A +
bit | ]
26 times
[ i^ char a +
bit | ] ] constant ] is letters ( --> n )
[ [ 0 $ "AEIUOaeiou"
witheach [ bit | ] ]
constant ] is vowels ( --> n )
[ [ letters vowels ~ & ]
constant ] is consonants ( --> n )
[ true swap
witheach
[ bit letters & 0 =
if [ conclude not ] ] ] is onlyletters ( $ --> b )
[ stack [ ] ] is chartest ( $ --> b )
[ bit vowels & 0 > ] is isvowel ( c --> b )
[ bit consonants & 0 > ] is isconsonant ( c --> b )
forward is constest ( c --> b )
[ isvowel
' constest
chartest replace ] is voweltest ( c --> b )
[ isconsonant
' voweltest
chartest replace ] resolves constest ( c --> b )
[ behead isvowel iff
[ ' constest ]
else [ ' voweltest ]
chartest put
true swap witheach
[ chartest share do
not if
[ conclude not ] ] ] is alternating ( $ --> b )
[ dup size 10 < iff
[ drop false ] done
dup onlyletters not iff
[ drop false ] done
alternating ] is allcriteria ( $ --> b )
$ "rosetta/unixdict.txt" sharefile
drop nest$
filter allcriteria
80 wrap$
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Racket
Echoing #Raku ... this is another one that can be done with a regex.
Here's a bit of variety; the match-lambda for the regex version could also be simplified to regexp-match.
#lang racket
(define alternating?/re
(match-lambda
((regexp #rx"^[aeiou]?([^aeiou][aeiou])*[^aeiou]?$") #t)
(_ #f)))
(define/match (vowel? v)
[((or #\a #\e #\i #\o #\u)) #t]
[(_) #f])
(define consonant? (negate vowel?))
(define (alternating?/for w)
(or (string=? "" w)
(let/ec fail (or (for/fold ((expect-vowel? (consonant? (string-ref w 0))))
((c (in-string w 1)))
(if (eq? (vowel? c) expect-vowel?)
(not expect-vowel?)
(fail #f)))
#t))))
(define (alternating?/loop w)
(define w-len-- (sub1 (string-length w)))
(or (negative? w-len--)
(let loop ((expect-vowel? (consonant? (string-ref w w-len--))) (i w-len--))
(or (zero? i)
(let* ((i-- (sub1 i)) (c (string-ref w i--)))
(and (eq? (vowel? c) expect-vowel?)
(loop (not expect-vowel?) i--)))))))
(define (alternating?/letrec w)
(letrec ((l (string-length w))
(c (λ (i) (string-ref w i)))
(vc-alt? (match-lambda
[(== l) #t]
[(and (app c (? vowel?)) (app add1 i)) (cv-alt? i)]
[_ #f]))
(cv-alt? (match-lambda
[(== l) #t]
[(and (app c (? consonant?))(app add1 i)) (vc-alt? i)]
[_ #f])))
(or (vc-alt? 0) (cv-alt? 0))))
(define (filtered-word? pred)
(match-lambda [(and (? pred) (? (λ (w) (> (string-length w) 9)))) #t] [_ #f]))
(define all-words (file->lines "../../data/unixdict.txt"))
(module+ main
(filter (filtered-word? alternating?/re) all-words))
(module+ test
(require rackunit)
(define words/re (filter (filtered-word? alternating?/re) all-words))
(define words/fold (filter (filtered-word? alternating?/for) all-words))
(define words/loop (filter (filtered-word? alternating?/loop) all-words))
(define words/letrec (filter (filtered-word? alternating?/letrec) all-words))
(check-equal? words/re words/fold)
(check-equal? words/re words/loop)
(check-equal? words/re words/letrec))
- Output:
'("aboriginal" "apologetic" "bimolecular" "borosilicate" "calorimeter" "capacitate" "capacitive" "capitoline" "capitulate" "caricature" "colatitude" "coloratura" "colorimeter" "debilitate" "decelerate" "decolonize" "definitive" "degenerate" "deliberate" "demodulate" "denominate" "denotative" "deregulate" "desiderata" "desideratum" "dilapidate" "diminutive" "epigenetic" "facilitate" "hemosiderin" "heretofore" "hexadecimal" "homogenate" "inoperative" "judicature" "latitudinal" "legitimate" "lepidolite" "literature" "locomotive" "manipulate" "metabolite" "nicotinamide" "oratorical" "paragonite" "pejorative" "peridotite" "peripatetic" "polarimeter" "recitative" "recuperate" "rehabilitate" "rejuvenate" "remunerate" "repetitive" "reticulate" "savonarola" "similitude" "solicitude" "tananarive" "telekinesis" "teratogenic" "topologize" "unilateral" "unimodular" "uninominal" "verisimilitude")
Raku
Sigh. Yet another "Filter a word list" task. In a effort to make it a little more interesting, rather than just doing a one-liner, build a grammar and use that to filter.
grammar VOWCON {
token TOP { <|w> <vowel>? ( <consonant> <vowel> )* <consonant>? <|w> }
token vowel { <[aeiou]> }
token consonant { <[a..z] - [aeiou]> }
}
say ( grep { VOWCON.parse: .lc }, grep { .chars > 9 }, 'unixdict.txt'.IO.words ).batch(6)».fmt('%-15s').join: "\n";
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
REXX
/*REXX program finds all the caseless words (within an identified dictionary) that */
/*──────────────────────────────────────── either have odd letters that are vowels, and */
/*──────────────────────────────────────── even letters that consonants, or vice versa.*/
parse arg minL iFID . /*obtain optional arguments from the CL*/
if minL=='' | minL=="," then minL= 10 /*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: original case and the semaphore*/
end /*#*/ /* [↑] semaphore name is uppercased. */
#= # - 1 /*adjust the record count (DO loop). */
say copies('─', 30) # "words in the dictionary file: " iFID; say
finds= 0 /*count of the words found (so far). */
vow= 'aeiou'; con= "bcdfghjklmnpqrstvwxyz" /*list of vowels; list of consonants. */
@@@=; upper vow con /*@@@: list of words found (so far). */
w= 0 /*the maximum length of any word found.*/
do j=1 for #; L= length($.j) /*process all the words that were found*/
if L<minL then iterate /*Is word too short? Then ignore it. */
y= $.j; upper y /*obtain a word; and also uppercase it.*/
ovec= 1; ocev= 1 /*for now, set both test cases: passed.*/
/*only scan odd indexed letters in word*/
do ov=1 by 2 to L; z= substr(y, ov, 1) /*examine the odd letters in the word. */
if verify(z, vow)>0 then ovec= 0 /*Odd letter not a vowel? Then flunk. */
end /*k*/
/*only scan eve indexed letters in word*/
do ev=2 by 2 to L; z= substr(y, ev, 1) /*examine the odd letters in the word. */
if verify(z, con)>0 then ovec= 0 /*Even letter not a consonant? Flunk. */
end /*k*/
/*only scan odd indexed letters in word*/
do oc=1 by 2 to L; z= substr(y, oc, 1) /*examine the odd letters in the word. */
if verify(z, con)>0 then ocev= 0 /*Odd letter not a consonant? Flunk. */
end /*k*/
/*only scan eve indexed letters in word*/
do ec=2 by 2 to L; z= substr(y, ec, 1) /*examine the odd letters in the word. */
if verify(z, vow)>0 then ocev= 0 /*Even letter not a vowel? Then flunk.*/
end /*k*/
if ovec==0 & ocev==0 then iterate /*Did the word pass any test? No, skip*/
finds= finds + 1 /*bump the count of "odd words" found. */
w= max(w, L) /*obtain the maximum length word found.*/
@@@= @@@ $.j /*add a word to the list of words found*/
end /*j*/
/*stick a fork in it, we're all done. */
say copies('─', 30) finds " words found with a minimum length of " minL
_=
do out=1 for finds; z= word(@@@, out) /*build a list that will be displayed. */
if length(_ right(z, w))>130 then do; say substr(_, 2); _=; end /*show a line.*/
_= _ right(z, w) /*append (aligned word) to output line.*/
end /*out*/
/*stick a fork in it, we're all done. */
if _\=='' then say substr(_, 2) /*Any residual words? Then show a line*/
- output when using the default inputs:
────────────────────────────── 25104 words in the dictionary file: unixdict.txt ────────────────────────────── 67 words found with a minimum length of 10 aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
Ring
cStr = read("unixdict.txt")
wordList = str2list(cStr)
words = []
num = 0
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
see "working..." + nl
ln = len(wordList)
for n = ln to 1 step -1
if len(wordList[n]) < 10
del(wordList,n)
ok
next
see "Words are:" + nl + nl
for n = 1 to len(wordList)
cflag = 0
vflag = 0
len = len(wordList[n])
for m = 1 to len
if m % 2 = 1
cons = substr(consonants,wordList[n][m])
if cons > 0
cflag = 1
else
cflag = 0
exit
ok
ok
if m % 2 = 0
cons = substr(vowels,wordList[n][m])
if cons > 0
vflag = 1
else
vflag = 0
exit
ok
ok
next
if cflag = 1 and vflag = 1
add(words,wordList[n])
ok
next
for n = 1 to len(wordList)
cflag = 0
vflag = 0
len = len(wordList[n])
for m = 1 to len
if m % 2 = 1
cons = substr(vowels,wordList[n][m])
if cons > 0
cflag = 1
else
cflag = 0
exit
ok
ok
if m % 2 = 0
cons = substr(consonants,wordList[n][m])
if cons > 0
vflag = 1
else
vflag = 0
exit
ok
ok
next
if cflag = 1 and vflag = 1
add(words,wordList[n])
ok
next
words = sort(words)
for n = 1 to len(words)
see "" + n + ". " + words[n] + nl
next
see "done..." + nl
Output:
working... Words are: 1. aboriginal 2. apologetic 3. bimolecular 4. borosilicate 5. calorimeter 6. capacitate 7. capacitive 8. capitoline 9. capitulate 10. caricature 11. colatitude 12. coloratura 13. colorimeter 14. debilitate 15. decelerate 16. decolonize 17. definitive 18. degenerate 19. deliberate 20. demodulate 21. denominate 22. denotative 23. deregulate 24. desiderata 25. desideratum 26. dilapidate 27. diminutive 28. epigenetic 29. facilitate 30. hemosiderin 31. heretofore 32. hexadecimal 33. homogenate 34. inoperative 35. judicature 36. latitudinal 37. legitimate 38. lepidolite 39. literature 40. locomotive 41. manipulate 42. metabolite 43. nicotinamide 44. oratorical 45. paragonite 46. pejorative 47. peridotite 48. peripatetic 49. polarimeter 50. recitative 51. recuperate 52. rehabilitate 53. rejuvenate 54. remunerate 55. repetitive 56. reticulate 57. savonarola 58. similitude 59. solicitude 60. tananarive 61. telekinesis 62. teratogenic 63. topologize 64. unilateral 65. unimodular 66. uninominal 67. verisimilitude done...
Ruby
VOWELS =%w(a e i o u).map(&:freeze)
res = File.open("unixdict.txt").each_line.select do |line|
word = line.chomp
word.size > 9 && word.chars.each_cons(2).all?{|c1, c2| VOWELS.include?(c1) != VOWELS.include?(c2) }
end
puts res
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
sed
#!/bin/sed -f
/^.\{10\}/!d
/^[aeiou]\{0,1\}\([^aeiou][aeiou]\)*[^aeiou]\{0,1\}$/!d
- Output:
aboriginal apologetic bimolecular [...] unimodular uninominal verisimilitude
Seed7
$include "seed7_05.s7i";
const func boolean: vowel (in char: letter) is
return letter in {'A', 'E', 'I', 'O', 'U'} |
{'a', 'e', 'i', 'o', 'u'};
const func boolean: consonant (in char: letter) is
return letter in {'B', 'C', 'D'} | {'F', 'G', 'H'} |
{'J' .. 'N'} | {'P' .. 'T'} | {'V' .. 'Z'} |
{'b', 'c', 'd'} | {'f', 'g', 'h'} |
{'j' .. 'n'} | {'p' .. 't'} | {'v' .. 'z'};
const func boolean: opposite (in char: letter1, in char: letter2) is
return vowel(letter1) and consonant(letter2) or
(consonant(letter1) and vowel(letter2));
const func boolean: alternating (in string: word) is func
result
var boolean: isAlternating is TRUE;
local
var integer: i is 2;
begin
while i <= length(word) and isAlternating do
isAlternating := opposite(word[i - 1], word[i]);
incr(i);
end while;
end func;
const proc: main is func
local
var file: dictionary is STD_NULL;
var string: word is "";
var integer: count is 1;
begin
dictionary := open("unixdict.txt", "r");
if dictionary <> STD_NULL then
while not eof(dictionary) do
readln(dictionary, word);
if length(word) > 9 and alternating(word) then
writeln(count lpad 2 <& ": " <& word);
incr(count);
end if;
end while;
close(dictionary);
end if;
end func;
- Output:
1: aboriginal 2: apologetic 3: bimolecular 4: borosilicate 5: calorimeter 6: capacitate 7: capacitive 8: capitoline 9: capitulate 10: caricature 11: colatitude 12: coloratura 13: colorimeter 14: debilitate 15: decelerate 16: decolonize 17: definitive 18: degenerate 19: deliberate 20: demodulate 21: denominate 22: denotative 23: deregulate 24: desiderata 25: desideratum 26: dilapidate 27: diminutive 28: epigenetic 29: facilitate 30: hemosiderin 31: heretofore 32: hexadecimal 33: homogenate 34: inoperative 35: judicature 36: latitudinal 37: legitimate 38: lepidolite 39: literature 40: locomotive 41: manipulate 42: metabolite 43: nicotinamide 44: oratorical 45: paragonite 46: pejorative 47: peridotite 48: peripatetic 49: polarimeter 50: recitative 51: recuperate 52: rehabilitate 53: rejuvenate 54: remunerate 55: repetitive 56: reticulate 57: savonarola 58: similitude 59: solicitude 60: tananarive 61: telekinesis 62: teratogenic 63: topologize 64: unilateral 65: unimodular 66: uninominal 67: verisimilitude
Swift
import Foundation
func isVowel(_ char: Character) -> Bool {
switch (char) {
case "a", "A", "e", "E", "i", "I", "o", "O", "u", "U":
return true
default:
return false
}
}
func alternatingVowelsAndConsonants(word: String) -> Bool {
return zip(word, word.dropFirst()).allSatisfy{isVowel($0.0) != isVowel($0.1)}
}
do {
try String(contentsOfFile: "unixdict.txt", encoding: String.Encoding.ascii)
.components(separatedBy: "\n")
.filter{$0.count > 9 && alternatingVowelsAndConsonants(word: $0)}
.enumerated()
.forEach{print(String(format: "%2d. %@", $0.0 + 1, $0.1))}
} catch {
print(error.localizedDescription)
}
- Output:
1: aboriginal 2: apologetic 3: bimolecular 4: borosilicate 5: calorimeter 6: capacitate 7: capacitive 8: capitoline 9: capitulate 10: caricature 11: colatitude 12: coloratura 13: colorimeter 14: debilitate 15: decelerate 16: decolonize 17: definitive 18: degenerate 19: deliberate 20: demodulate 21: denominate 22: denotative 23: deregulate 24: desiderata 25: desideratum 26: dilapidate 27: diminutive 28: epigenetic 29: facilitate 30: hemosiderin 31: heretofore 32: hexadecimal 33: homogenate 34: inoperative 35: judicature 36: latitudinal 37: legitimate 38: lepidolite 39: literature 40: locomotive 41: manipulate 42: metabolite 43: nicotinamide 44: oratorical 45: paragonite 46: pejorative 47: peridotite 48: peripatetic 49: polarimeter 50: recitative 51: recuperate 52: rehabilitate 53: rejuvenate 54: remunerate 55: repetitive 56: reticulate 57: savonarola 58: similitude 59: solicitude 60: tananarive 61: telekinesis 62: teratogenic 63: topologize 64: unilateral 65: unimodular 66: uninominal 67: verisimilitude
Wren
import "io" for File
import "./fmt" for Fmt
var isVowel = Fn.new { |c| "aeiou".contains(c) }
var wordList = "unixdict.txt" // local copy
var words = File.read(wordList).trimEnd().split("\n").where { |w| w.count > 9 }
var count = 0
System.print("Words with alternate consonants and vowels in %(wordList):\n")
for (word in words) {
var found = true
for (i in 0...word.count) {
var c = word[i]
if ((i%2 == 0 && isVowel.call(c)) || (i%2 == 1 && !isVowel.call(c))) {
found = false
break
}
}
if (!found) {
found = true
for (i in 0...word.count) {
var c = word[i]
if ((i%2 == 0 && !isVowel.call(c)) || (i%2 == 1 && isVowel.call(c))) {
found = false
break
}
}
}
if (found) {
count = count + 1
Fmt.print("$2d: $s", count, word)
}
}
- Output:
Words with alternate consonants and vowels in unixdict.txt: 1: aboriginal 2: apologetic 3: bimolecular 4: borosilicate 5: calorimeter 6: capacitate 7: capacitive 8: capitoline 9: capitulate 10: caricature 11: colatitude 12: coloratura 13: colorimeter 14: debilitate 15: decelerate 16: decolonize 17: definitive 18: degenerate 19: deliberate 20: demodulate 21: denominate 22: denotative 23: deregulate 24: desiderata 25: desideratum 26: dilapidate 27: diminutive 28: epigenetic 29: facilitate 30: hemosiderin 31: heretofore 32: hexadecimal 33: homogenate 34: inoperative 35: judicature 36: latitudinal 37: legitimate 38: lepidolite 39: literature 40: locomotive 41: manipulate 42: metabolite 43: nicotinamide 44: oratorical 45: paragonite 46: pejorative 47: peridotite 48: peripatetic 49: polarimeter 50: recitative 51: recuperate 52: rehabilitate 53: rejuvenate 54: remunerate 55: repetitive 56: reticulate 57: savonarola 58: similitude 59: solicitude 60: tananarive 61: telekinesis 62: teratogenic 63: topologize 64: unilateral 65: unimodular 66: uninominal 67: verisimilitude
XPL0
string 0; \Use zero-terminated strings
int Cnt, I, Ch, Len;
char Word(100); \(longest word in unixdict.txt is 22 chars)
def Tab=$09, LF=$0A, CR=$0D, EOF=$1A;
func Vowel(Ch); \Return 'true' if character is a vowel
int Ch;
case Ch of ^a, ^e, ^i, ^o, ^u: return true
other return false;
func Alternates; \Return 'true' if Word alternates vowel/consonant
int Sense, I;
[Sense:= Vowel(Word(0));
for I:= 0 to Len-1 do
[if Vowel(Word(I)) # Sense then return false;
Sense:= not Sense;
];
return true;
];
[FSet(FOpen("unixdict.txt", 0), ^I); \open dictionary and set it to device 3
OpenI(3);
Cnt:= 0;
repeat I:= 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;
];
Word(I):= 0; \terminate string
Len:= I;
if Len > 9 then
[if Alternates then
[Text(0, Word);
Cnt:= Cnt+1;
if rem(Cnt/5) then ChOut(0, Tab) else CrLf(0);
];
];
until Ch = EOF;
]
- Output:
aboriginal apologetic bimolecular borosilicate calorimeter capacitate capacitive capitoline capitulate caricature colatitude coloratura colorimeter debilitate decelerate decolonize definitive degenerate deliberate demodulate denominate denotative deregulate desiderata desideratum dilapidate diminutive epigenetic facilitate hemosiderin heretofore hexadecimal homogenate inoperative judicature latitudinal legitimate lepidolite literature locomotive manipulate metabolite nicotinamide oratorical paragonite pejorative peridotite peripatetic polarimeter recitative recuperate rehabilitate rejuvenate remunerate repetitive reticulate savonarola similitude solicitude tananarive telekinesis teratogenic topologize unilateral unimodular uninominal verisimilitude
- Draft Programming Tasks
- 11l
- Action!
- Ada
- ALGOL 68
- AppleScript
- Arturo
- AutoHotkey
- AWK
- C
- C++
- Delphi
- Classes,StdCtrls,SysUtils
- F Sharp
- Factor
- Forth
- FreeBASIC
- FutureBasic
- Go
- Haskell
- J
- JavaScript
- Jq
- Julia
- Ksh
- Mathematica
- Wolfram Language
- MiniScript
- Nim
- Perl
- Phix
- Plain English
- Prolog
- Python
- Quackery
- Racket
- Raku
- REXX
- Ring
- Ruby
- Sed
- Seed7
- Swift
- Wren
- Wren-fmt
- XPL0