I before E except after C: Difference between revisions

m
m (→‎{{header|Phix}}: improved comment)
m (→‎{{header|Wren}}: Minor tidy)
(45 intermediate revisions by 23 users not shown)
Line 22:
 
''Show your output here as well as your program.''
 
 
{{Template:Strings}}
 
 
Line 29 ⟶ 32:
* [http://ucrel.lancs.ac.uk/bncfreq/ Companion website] for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V PLAUSIBILITY_RATIO = 2
 
F plausibility_check(comment, x, y)
print("\n Checking plausibility of: #.".format(comment))
I x > :PLAUSIBILITY_RATIO * y
print(‘ PLAUSIBLE. As we have counts of #. vs #., a ratio of #2.1 times’.format(x, y, Float(x) / y))
E
I x > y
print(‘ IMPLAUSIBLE. As although we have counts of #. vs #., a ratio of #2.1 times does not make it plausible’.format(x, y, Float(x) / y))
E
print(‘ IMPLAUSIBLE, probably contra-indicated. As we have counts of #. vs #., a ratio of #2.1 times’.format(x, y, Float(x) / y))
R x > :PLAUSIBILITY_RATIO * y
 
F simple_stats()
V words = File(‘unixdict.txt’).read().split("\n")
V cie = Set(words.filter(word -> ‘cie’ C word)).len
V cei = Set(words.filter(word -> ‘cei’ C word)).len
V not_c_ie = Set(words.filter(word -> re:‘(^ie|[^c]ie)’.search(word))).len
V not_c_ei = Set(words.filter(word -> re:‘(^ei|[^c]ei)’.search(word))).len
R (cei, cie, not_c_ie, not_c_ei)
 
F print_result(cei, cie, not_c_ie, not_c_ei)
I (plausibility_check(‘I before E when not preceded by C’, not_c_ie, not_c_ei) & plausibility_check(‘E before I when preceded by C’, cei, cie))
print("\nOVERALL IT IS PLAUSIBLE!")
E
print("\nOVERALL IT IS IMPLAUSIBLE!")
print(‘(To be plausible, one count must exceed another by #. times)’.format(:PLAUSIBILITY_RATIO))
 
print(‘Checking plausibility of "I before E except after C":’)
V (cei, cie, not_c_ie, not_c_ei) = simple_stats()
print_result(cei, cie, not_c_ie, not_c_ei)</syntaxhighlight>
 
{{out}}
<pre>
Checking plausibility of "I before E except after C":
 
Checking plausibility of: I before E when not preceded by C
PLAUSIBLE. As we have counts of 465 vs 213, a ratio of 2.2 times
 
Checking plausibility of: E before I when preceded by C
IMPLAUSIBLE, probably contra-indicated. As we have counts of 13 vs 24, a ratio of 0.5 times
 
OVERALL IT IS IMPLAUSIBLE!
(To be plausible, one count must exceed another by 2 times)
</pre>
 
=={{header|8080 Assembly}}==
 
This program is written to run under CP/M. It takes the filename on the command line.
The file can be as large as you like, it does not need to fit in memory at once.
(Indeed, <code>unixdict.txt</code> is 206k.)
 
<syntaxhighlight lang="8080asm"> ;;; I before E, except after C
fcb1: equ 5Ch ; FCB 1 (populated by file on command line)
dma: equ 80h ; Standard DMA location
bdos: equ 5 ; CP/M entry point
puts: equ 9 ; CP/M call to write a string to the console
fopen: equ 0Fh ; CP/M call to open a file
fread: equ 14h ; CP/M call to read from a file
CR: equ 13
LF: equ 10
EOF: equ 26
org 100h
;;; Open the file given on the command line
lxi d,fcb1
mvi c,fopen
call bdos
inr a ; FF = error
jz die
;;; We can only read one 128-byte block at a time, and the file
;;; will not fit in memory (max 64 k). So there are two things
;;; going on here: we copy from the block into a word buffer
;;; until we see the end of a line, at which point we process
;;; the word. In the meantime, if while copying we reach the end
;;; of the block, we read the next block.
lxi b,curwrd ; Word pointer
block: push b ; Keep word pointer while reading
lxi d,fcb1 ; Read a block from the file
mvi c,fread
call bdos
pop b ; Restore word pointer
dcr a ; 1 = EOF
jz done
inr a ; otherwise, <>0 = error
jnz die
lxi h,dma ; Start reading at DMA
char: mov a,m ; Get character
cpi EOF ; If it's an EOF character, we're done
jz done
stax b ; Store character in current word
inx b
cpi LF ; If it's LF, then we've got a full word
cz word ; Process the word
inr l ; Go to next character
jz block ; If we're done with this block, get next one
jmp char
;;; When done, report the statistics
done: lxi d,scie ; CIE
call sout
lhld cie
call puthl
lxi d,sxie ; xIE
call sout
lhld xie
call puthl
lxi d,scei ; CEI
call sout
lhld cei
call puthl
lxi d,sxei ; xEI
call sout
lhld xei
call puthl
;;; Then say what is and isn't plausible
lxi d,s_ienc ; I before E when not preceded by C
call sout ; plausible if 2*xIE>CIE
lhld cie
xchg
lhld xie
call pplaus
lxi d,s_eic ; E before I when preceded by C
call sout ; plausible if 2*CEI>xEI
lhld xei
xchg
lhld cei
;;; If HL = amount of words with feature, and
;;; DE = amount of words with opposit feature, then print
;;; '(not) plausible', as appropriate.
pplaus: dad h ; 2 * feature
mov a,d ; Compare high byte
cmp h
jc plaus ; If 2*H>D then plausible
mov a,e ; Otherwise, compare low byte
cmp l
jc plaus ; If 2*L>E then plausible
lxi d,snop ; Otherwise, not plausible
jmp sout
plaus: lxi d,splau
jmp sout
;;; Process a word
word: push h ; Save file read address
xra a ; Zero out end of word
stax b
dcx b
lxi h,curwrd ; Scan word
start: mov a,m ; Get current character
inx h ; Move pointer ahead
ana a ; If zero,
jz w_end ; we're done
cpi 'c' ; Did we find a 'c'?
jz findc
cpi 'e' ; Otherwise, did we find 'e'?
jz finde
cpi 'i' ; Otherwise, did we find 'i'?
jz findi
jmp start ; Otherwise, keep going
;;; We found an 'e'
finde: mov a,m ; Get following character
cpi 'i' ; Is it 'i'?
jnz start ; If not, keep going
inx h ; Otherwise, move past it,
xchg ; keep pointer in DE,
lhld xie ; We found ie without c
inx h
shld xie
xchg
jmp start
;;; We found an 'i'
findi: mov a,m ; Get following character
cpi 'e' ; Is it 'e'?
jnz start ; If not, keep going
inx h ; Otherwise, move past it,
xchg ; keep pointer in DE,
lhld xei ; We found ei without c
inx h
shld xei
xchg
jmp start
;;; We found a 'c'
findc: mov a,m ; Get following character
cpi 'e' ; Is it 'e'?
jz findce ; Then we have 'ce'
cpi 'i' ; Is it 'i'?
jz findci ; Then we have 'ci'
jmp start ; Otherwise, just keep going
findce: mov d,h ; set DE = start of 'e?'
mov e,l
inx d ; Get next character
ldax d
cpi 'i' ; Is it 'i'?
jnz start ; If not, do nothing
lhld cei ; But if so, we found 'cei'
inx h ; Increment the counter
shld cei
xchg ; Keep scanning _after_ the 'cei'
inx h
jmp start
findci: mov d,h ; set DE = start of 'i?'
mov e,l
inx d ; Get next character
ldax d
cpi 'e' ; Is it 'e'?
jnz start ; If not, do nothing
lhld cie ; But if so, we found 'cie'
inx h ; Increment the counter
shld cie
xchg ; Keep scanning _after_ the 'cie'
inx h
jmp start
w_end: lxi b,curwrd ; Set word pointer to beginning
pop h ; Restore file read address
ret
;;; Print error message and stop the program
die: lxi d,errmsg
mvi c,puts
call bdos
rst 0
;;; Print string
sout: mvi c,puts
jmp bdos
;;; Print HL to the console as a decimal number
puthl: push h
lxi h,num
xthl
lxi b,-10
dgt: lxi d,-1
clcdgt: inx d
dad b
jc clcdgt
mov a,l
adi 10+'0'
xthl
dcx h
mov m,a
xthl
xchg
mov a,h
ora l
jnz dgt
pop d
mvi c,puts
jmp bdos
errmsg: db 'Error$' ; Good enough
s_ienc: db 'I before E when not preceded by C:$'
s_eic: db 'E before I when preceded by C:$'
snop: db ' not'
splau: db ' plausible',CR,LF,'$'
scie: db 'CIE: $' ; Report strings
sxie: db 'xIE: $'
scei: db 'CEI: $'
sxei: db 'xEI: $'
db '00000'
num: db CR,LF,'$' ; Space for number
;;; Counters
xie: dw 0 ; I before E when not preceded by C
cie: dw 0 ; I before E when preceded by C
cei: dw 0 ; E before I when preceded by C
xei: dw 0 ; E before I when not preceded by C
curwrd: equ $ ; Current word stored here</syntaxhighlight>
 
{{out}}
 
<pre>A>iec unixdict.txt
CIE: 24
xIE: 217
CEI: 13
xEI: 464
I before E when not preceded by C: plausible
E before I when preceded by C: not plausible</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}} Uses non-standard procedure to lower available in Algol 68G.
<langsyntaxhighlight lang="algol68"># tests the plausibility of "i before e except after c" using unixdict.txt #
 
# implements the plausibility test specified by the task #
Line 111 ⟶ 387:
show plausibility( "i before e in general", xie + cie, xei + cei );
show plausibility( "e before i in general", xei + cei, xie + cie )
FI</langsyntaxhighlight>
{{out}}
<pre>
Line 125 ⟶ 401:
e before i in general is not plausible
</pre>
 
=={{header|AppleScript}}==
Ignoring the fact that all exceptions to the rule in unixdict.txt occur where the rule doesn't apply anyway, such as in diphthongs, adjacent syllables, foreign or borrowed words, ''etc.'':
 
===Vanilla===
 
<syntaxhighlight lang="applescript">on ibeeac()
script o
property wordList : words of (read file ((path to desktop as text) & "www.rosettacode.org:unixdict.txt") as «class utf8»)
-- Subhandler called if thisWord contains either "ie" or "ei". Checks if there's an instance not preceded by "c".
on testWithoutC(thisWord, letterPair)
set AppleScript's text item delimiters to letterPair
repeat with i from 1 to (count thisWord's text items) - 1
if (text item i of thisWord does not end with "c") then return true
end repeat
return false
end testWithoutC
end script
-- Counters: {i before e not after c, i before e after c, e before i not after c, e before i after c}.
set {xie, cie, xei, cei} to {0, 0, 0, 0}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "ie"
repeat with thisWord in o's wordList
set thisWord to thisWord's contents
if (thisWord contains "ie") then
if (thisWord contains "cie") then set cie to cie + 1
if (o's testWithoutC(thisWord, "ie")) then set xie to xie + 1
end if
if (thisWord contains "ei") then
if (thisWord contains "cei") then set cei to cei + 1
if (o's testWithoutC(thisWord, "ei")) then set xei to xei + 1
end if
end repeat
set AppleScript's text item delimiters to astid
set |1 is plausible| to (xie / cie > 2)
set |2 is plausible| to (cei / xei > 2)
return {|"I before E not after C" is plausible|:|1 is plausible|} & ¬
{|"E before I after C" is plausible|:|2 is plausible|} & ¬
{|Both are plausible|:(|1 is plausible| and |2 is plausible|)}
end ibeeac
 
ibeeac()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{|"I before E not after C" is plausible|:true, |"E before I after C" is plausible|:false, |Both are plausible|:false}</syntaxhighlight>
 
===AppleScriptObjC===
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
 
on ibeeac()
set wordList to words of ¬
(read (((path to desktop as text) & "www.rosettacode.org:unixdict.txt") as «class furl») as «class utf8»)
set wordArray to current application's class "NSArray"'s arrayWithArray:(wordList)
set counters to {}
repeat with letterPair in {"ie", "ei"}
set filter to (current application's class "NSPredicate"'s ¬
predicateWithFormat_("(self CONTAINS[c] %@)", letterPair))
set relevants to (wordArray's filteredArrayUsingPredicate:(filter))
set filter to (current application's class "NSPredicate"'s ¬
predicateWithFormat_("NOT (self CONTAINS[c] %@)", "c" & letterPair))
set end of counters to (relevants's filteredArrayUsingPredicate:(filter))'s |count|()
set filter to (current application's class "NSPredicate"'s ¬
predicateWithFormat_("(self CONTAINS[c] %@)", "c" & letterPair))
set end of counters to (relevants's filteredArrayUsingPredicate:(filter))'s |count|()
end repeat
set {xie, cie, xei, cei} to counters
set |1 is plausible| to (xie / cie > 2)
set |2 is plausible| to (cei / xei > 2)
return {|"I before E not after C" is plausible|:|1 is plausible|} & ¬
{|"E before I after C" is plausible|:|2 is plausible|} & ¬
{|Both are plausible|:(|1 is plausible| and |2 is plausible|)}
end ibeeac
 
ibeeac()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{|"I before E not after C" is plausible|:true, |"E before I after C" is plausible|:false, |Both are plausible|:false}</syntaxhighlight>
 
 
===Functional===
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
 
 
---------------------- TEST OF CLAIMS --------------------
on run
set fpWordList to scriptFolder() & "unixdict.txt"
if doesFileExist(fpWordList) then
set patterns to {"[^c]ie", "[^c]ei", "cei", "cie"}
set counts to ap(map(matchCount, patterns), ¬
{readFile(fpWordList)})
script test
on |λ|(kvs)
set {common, rare} to kvs
set {ck, cv} to common
set {rk, rv} to rare
set ratio to roundTo(2, cv / rv)
if ratio > 2 then
set verdict to "plausible"
else
set verdict to "unsupported"
end if
unwords({ck, ">", rk, "->", cv, "/", rv, ¬
"=", ratio, "::", verdict})
end |λ|
end script
unlines(map(test, chunksOf(2, zip(patterns, counts))))
else
display dialog "Word list not found in this script's folder:" & ¬
linefeed & tab & fpWordList
end if
end run
 
 
------------------------- GENERIC ------------------------
 
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
-- Constructor for a pair of values, possibly of two different types.
{a, b}
end Tuple
 
 
-- ap (<*>) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
-- e.g. [(*2),(/2), sqrt] <*> [1,2,3]
-- --> ap([dbl, hlf, root], [1, 2, 3])
-- --> [2,4,6,0.5,1,1.5,1,1.4142135623730951,1.7320508075688772]
-- Each member of a list of functions applied to
-- each of a list of arguments, deriving a list of new values
set lst to {}
repeat with f in fs
tell mReturn(contents of f)
repeat with x in xs
set end of lst to |λ|(contents of x)
end repeat
end tell
end repeat
return lst
end ap
 
 
-- chunksOf :: Int -> [a] -> [[a]]
on chunksOf(k, xs)
script
on go(ys)
set ab to splitAt(k, ys)
set a to item 1 of ab
if {} ≠ a then
{a} & go(item 2 of ab)
else
a
end if
end go
end script
result's go(xs)
end chunksOf
 
 
-- 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
 
 
-- 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
 
 
-- matchCount :: String -> NSString -> Int
on matchCount(regexString)
-- A count of the matches for a regular expression
-- in a given NSString
script
on |λ|(s)
set ca to current application
((ca's NSRegularExpression's ¬
regularExpressionWithPattern:regexString ¬
options:(ca's NSRegularExpressionAnchorsMatchLines) ¬
|error|:(missing value))'s ¬
numberOfMatchesInString:s ¬
options:0 ¬
range:{location:0, |length|:s's |length|()}) as integer
end |λ|
end script
end matchCount
 
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
 
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
 
-- 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
 
 
-- roundTo :: Int -> Float -> Float
on roundTo(n, x)
set d to 10 ^ n
(round (x * d)) / d
end roundTo
 
 
-- scriptFolder :: () -> IO FilePath
on scriptFolder()
-- The path of the folder containing this script
tell application "Finder" to ¬
POSIX path of ((container of (path to me)) as alias)
end scriptFolder
 
 
-- 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
{items 1 thru n of xs as text, ¬
items (n + 1) thru -1 of xs as text}
else
{items 1 thru n of xs, items (n + 1) thru -1 of xs}
end if
else
if n < 1 then
{{}, xs}
else
{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
 
 
-- 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
 
 
-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
zipWith(Tuple, xs, ys)
end zip
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
if 1 > lng then
return {}
else
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end if
end zipWith</syntaxhighlight>
{{Out}}
<pre>[^c]ie > [^c]ei -> 466 / 217 = 2.15 :: plausible
cei > cie -> 13 / 24 = 0.54 :: unsupported</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">rule1: {"I before E when not preceded by C"}
rule2: {"E before I when preceded by C"}
phrase: {"I before E except after C"}
 
plausibility: #[
false: "not plausible",
true: "plausible"
]
 
checkPlausible: function [rule, count1, count2][
result: count1 > 2 * count2
print ["The rule" rule "is" plausibility\[result] ":"]
print ["\tthere were" count1 "examples and" count2 "counter-examples."]
return result
]
 
words: read.lines relative "unixdict.txt"
 
[nie,cie,nei,cei]: 0
 
loop words 'word [
if contains? word "ie" ->
inc (contains? word "cie")? -> 'cie -> 'nie
if contains? word "ei" ->
inc (contains? word "cei")? -> 'cei -> 'nei
]
 
p1: checkPlausible rule1 nie nei
p2: checkPlausible rule2 cei cie
 
print ["\nSo the phrase" phrase "is" (to :string plausibility\[and? p1 p2]) ++ "."]</syntaxhighlight>
 
{{out}}
 
<pre>The rule "I before E when not preceded by C" is plausible :
there were 465 examples and 213 counter-examples.
The rule "E before I when preceded by C" is not plausible :
there were 13 examples and 24 counter-examples.
 
So the phrase "I before E except after C" is not plausible.</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">WordList := URL_ToVar("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
WordList := RegExReplace(WordList, "i)cie", "", cieN)
WordList := RegExReplace(WordList, "i)cei", "", ceiN)
Line 148 ⟶ 805:
WebRequest.Send()
return, WebRequest.ResponseText
}</langsyntaxhighlight>
{{out}}
<pre>"I before E when not preceded by C" is plausible.
Line 159 ⟶ 816:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
/.ei/ {nei+=cnt($3)}
Line 184 ⟶ 841:
print "E before I when preceded by C: is"v2" plausible";
print "Overall rule is"v" plausible";
}</langsyntaxhighlight>
 
Usage:
Line 206 ⟶ 863:
=={{header|Batch File}}==
Download first the text file, then put it on the same directory with this sample code:
<langsyntaxhighlight lang="dos">::I before E except after C task from Rosetta Code Wiki
::Batch File Implementation
 
Line 242 ⟶ 899:
 
pause
exit /b 0</langsyntaxhighlight>
{{Out}}
<pre>Plausibility of "I before E when not preceded by C": TRUE (465 VS 213)
Line 252 ⟶ 909:
Each word is counted once if word has at least one occurrence of test string (word with 2 or more occurrences only counts once).
The same word may count toward different categories.
<langsyntaxhighlight lang="dos">@echo off
setlocal enableDelayedExpansion
for /f %%A in ('findstr /i "^ie [^c]ie" unixdict.txt ^| find /c /v ""') do set Atrue=%%A
Line 262 ⟶ 919:
echo I before E when not preceded by C: True=%Atrue% False=%Afalse% : !Answer%Aresult%!
echo E before I when preceded by C: True=%Btrue% False=%Bfalse% : !Answer%Bresult%!
echo I before E, except after C : !Answer%Result%!</langsyntaxhighlight>
{{Out}}
<pre>I before E when not preceded by C: True=465 False=213 : Plausible
Line 271 ⟶ 928:
Each word frequency is included once if word has at least one occurrence of test string (word with 2 or more occurrences only counts once).
The same word frequency may count toward different categories.
<langsyntaxhighlight lang="dos">@echo off
setlocal enableDelayedExpansion
set /a Atrue=Afalse=Btrue=Bfalse=0
Line 282 ⟶ 939:
echo I before E when not preceded by C: True=%Atrue% False=%Afalse% : !Answer%Aresult%!
echo E before I when preceded by C: True=%Btrue% False=%Bfalse% : !Answer%Bresult%!
echo I before E, except after C : !Answer%Result%!</langsyntaxhighlight>
{{Out}}
<pre>I before E when not preceded by C: True=8192 False=4826 : Implausible
E before I when preceded by C: True=327 False=994 : Implausible
I before E, except after C : Implausible</pre>
 
=={{header|BASIC}}==
<syntaxhighlight lang="basic">10 DEFINT A-Z
20 OPEN "I",1,"UNIXDICT.TXT": GOTO 60
30 LINE INPUT #1,W$
40 IF INSTR(W$,"ie") THEN IF INSTR(W$,"cie") THEN CI=CI+1 ELSE XI=XI+1
50 IF INSTR(W$,"ei") THEN IF INSTR(W$,"cei") THEN CE=CE+1 ELSE XE=XE+1
60 IF NOT EOF(1) GOTO 30 ELSE CLOSE #1
70 PRINT "CIE:";CI
80 PRINT "xIE:";XI
90 PRINT "CEI:";CE
100 PRINT "xEI:";XE
110 PRINT
120 PRINT "I before E when not preceded by C: ";
130 IF 2*XI <= CI THEN PRINT "not ";
140 PRINT "plausible."
150 PRINT "E before I when preceded by C: ";
160 IF 2*CE <= XE THEN PRINT "not ";
170 PRINT "plausible."</syntaxhighlight>
{{out}}
<pre>CIE: 24
xIE: 465
CEI: 13
xEI: 213
 
I before E when not preceded by C: plausible.
E before I when preceded by C: not plausible.</pre>
 
 
=={{header|BASIC256}}==
{{trans|BASIC}}
<syntaxhighlight lang="freebasic">CI = 0 : XI = 0 : CE = 0 : XE = 0
open 1, "unixdict.txt"
 
do
pal$ = readline (1)
if instr(pal$, "ie") then
if instr(pal$, "cie") then CI += 1 else XI += 1
endif
if instr(pal$, "ei") then
if instr(pal$, "cei") then CE += 1 else XE += 1
endif
until eof(1)
close 1
 
print "CIE: "; CI
print "xIE: "; XI
print "CEI: "; CE
print "xEI: "; XE
print
print "I before E when not preceded by C: ";
if 2 * XI <= CI then print "not ";
print "plausible."
print "E before I when preceded by C: ";
if 2 * CE <= XE then print "not ";
print "plausible."
end</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> F%=OPENIN"unixdict.txt"
IF F% == 0 ERROR 100, "unixdict not found!"
 
CI=0 : XI=0 : CE=0 : XE=0
WHILE NOT EOF#F%
Line$=GET$#F%
P%=INSTR(Line$, "ie")
WHILE P%
IF MID$(Line$, P% - 1, 1) == "c" CI+=1 ELSE XI+=1
P%=INSTR(Line$, "ie", P% + 1)
ENDWHILE
P%=INSTR(Line$, "ei")
WHILE P%
IF MID$(Line$, P% - 1, 1) == "c" CE+=1 ELSE XE+=1
P%=INSTR(Line$, "ei", P% + 1)
ENDWHILE
ENDWHILE
CLOSE#F%
 
PRINT "Instances of 'ie', proceeded by a 'c' = ";CI
PRINT "Instances of 'ie', NOT proceeded by a 'c' = ";XI
P1%=XI * 2 > CI
PRINT "Therefore 'I before E when not preceded by C' is" FNTest(P1%)
PRINT
 
PRINT "Instances of 'ei', proceeded by a 'c' = ";CE
PRINT "Instances of 'ei', NOT proceeded by a 'c' = ";XE
P2%=CE * 2 > XE
PRINT "Therefore 'E before I when preceded by C' is" FNTest(P2%)
PRINT
 
IF P1% AND P2% PRINT "B"; ELSE PRINT "Not b";
PRINT "oth sub-phrases are plausible, therefore the phrase " +\
\ "'I before E, except after C' can be said to be" FNTest(P1% AND P2%) "!"
END
 
DEF FNTest(plausible%)=MID$(" not plausible", 1 - 4 * plausible%)</syntaxhighlight>
{{out}}
<pre>Instances of 'ie', proceeded by a 'c' = 24
Instances of 'ie', NOT proceeded by a 'c' = 466
Therefore 'I before E when not preceded by C' is plausible
 
Instances of 'ei', proceeded by a 'c' = 13
Instances of 'ei', NOT proceeded by a 'c' = 217
Therefore 'E before I when preceded by C' is not plausible
 
Not both sub-phrases are plausible, therefore the phrase 'I before E, except after C' can be said to be not plausible!</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
// Read word from selected input
let readword(v) = valof
$( let ch = ?
v%0 := 0
$( ch := rdch()
if ch = endstreamch then resultis false
if ch = '*N' then resultis true
v%0 := v%0 + 1
v%(v%0) := ch
$) repeat
$)
 
// Does s1 contain s2?
let contains(s1, s2) = valof
$( for i = 1 to s1%0 - s2%0 + 1
if valof
$( for j = 1 to s2%0
unless s1%(i+j-1) = s2%j resultis false
resultis true
$) resultis true
resultis false
$)
 
// Test unixdict.txt
let start() be
$( let word = vec 2+64/BYTESPERWORD
let file = findinput("unixdict.txt")
let ncie, ncei, nxie, nxei = 0, 0, 0, 0
selectinput(file)
while readword(word)
test contains(word, "ie")
test contains(word, "cie")
do ncie := ncie + 1
or nxie := nxie + 1
or if contains(word, "ei")
test contains(word, "cei")
do ncei := ncei + 1
or nxei := nxei + 1
endread()
// Show results
writef("CIE: %N*N", ncie)
writef("xIE: %N*N", nxie)
writef("CEI: %N*N", ncei)
writef("xEI: %N*N", nxei)
writef("I before E when not preceded by C: %Splausible.*N",
2*nxie > ncie -> "", "not ")
writef("E before I when preceded by C: %Splausible.*N",
2*ncei > nxei -> "", "not ")
$)</syntaxhighlight>
{{out}}
<pre>CIE: 24
xIE: 465
CEI: 13
xEI: 209
I before E when not preceded by C: plausible.
E before I when preceded by C: not plausible.</pre>
 
=={{header|C}}==
Line 293 ⟶ 1,122:
This may in turn motivate me to provide a second J solution as a single pass FSM.
Please find the program output hidden at the top of the source as part of the build and example run.
<syntaxhighlight lang="c">
<lang c>
%{
/*
Line 326 ⟶ 1,155:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.IO;
Line 384 ⟶ 1,213:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Plausible count: 384
Line 397 ⟶ 1,226:
:* (Test used 4.4, so only a limited number of C++11 features were used.)
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <fstream>
#include <string>
Line 498 ⟶ 1,327:
return 0;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 513 ⟶ 1,342:
The output here was generated with the files as of 21st June 2016.
 
<langsyntaxhighlight lang="clojure">
(ns i-before-e.core
(:require [clojure.string :as s])
Line 567 ⟶ 1,396:
(with-open [rdr (clojure.java.io/reader "http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt")]
(i-before-e-except-after-c-plausible? "Word frequencies (stretch goal)" (map format-freq-line (drop 1 (line-seq rdr))))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 585 ⟶ 1,414:
Overall the rule 'I before E except after C' is implausible
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">report = cluster is new, classify, results
rep = record[cie, xie, cei, xei, words: int]
new = proc () returns (cvt)
return(rep${cie: 0, xie: 0, cei: 0, xei: 0, words: 0})
end new
classify = proc (r: cvt, word: string)
r.words := r.words + 1
if string$indexs("ie", word) ~= 0 then
if string$indexs("cie", word) ~= 0
then r.cie := r.cie + 1
else r.xie := r.xie + 1
end
elseif string$indexs("ei", word) ~= 0 then
if string$indexs("cei", word) ~= 0
then r.cei := r.cei + 1
else r.xei := r.xei + 1
end
end
end classify
stat = proc (s: stream, name: string, val: int)
stream$puts(s, name)
stream$puts(s, ": ")
stream$putl(s, int$unparse(val))
end stat
plausible = proc (s: stream, feature: string, match, nomatch: int)
returns (bool)
stream$puts(s, feature)
stream$puts(s, ": ")
plaus: bool := 2 * match > nomatch;
if ~plaus then stream$puts(s, "not ") end
stream$putl(s, "plausible.");
return(plaus)
end plausible
results = proc (r: cvt) returns (string)
ss: stream := stream$create_output()
stat(ss, "Amount of words", r.words)
stat(ss, "CIE", r.cie)
stat(ss, "xIE", r.xie)
stat(ss, "CEI", r.cei)
stat(ss, "xEI", r.xei)
stream$putl(ss, "")
xie_p: bool := plausible(ss, "I before E when not preceded by C", r.xie, r.cie)
cei_p: bool := plausible(ss, "E before I when preceded by C", r.cei, r.xei)
stream$puts(ss, "I before E, except after C: ")
if ~(xie_p & cei_p) then stream$puts(ss, "not ") end
stream$putl(ss, "plausible.")
return(stream$get_contents(ss))
end results
end report
 
lines = iter (s: stream) yields (string)
while true do
yield(stream$getl(s))
except when end_of_file: break end
end
end lines
 
start_up = proc ()
po: stream := stream$primary_output()
file: file_name := file_name$parse("unixdict.txt")
fstream: stream := stream$open(file, "read")
r: report := report$new()
for line: string in lines(fstream) do
report$classify(r, line)
end
stream$close(fstream)
stream$puts(po, report$results(r))
end start_up </syntaxhighlight>
{{out}}
<pre>Amount of words: 25104
CIE: 24
xIE: 465
CEI: 13
xEI: 209
 
I before E when not preceded by C: plausible.
E before I when preceded by C: not plausible.
I before E, except after C: not plausible.</pre>
 
=={{header|Coco}}==
Line 592 ⟶ 1,506:
Now we can do the task:
 
<langsyntaxhighlight lang="coco">ie-npc = ei-npc = ie-pc = ei-pc = 0
for word of dict.toLowerCase!.match /\S+/g
++ie-npc if /(^|[^c])ie/.test word
Line 604 ⟶ 1,518:
console.log '(1) is%s plausible.', if p1 then '' else ' not'
console.log '(2) is%s plausible.', if p2 then '' else ' not'
console.log 'The whole phrase is%s plausible.', if p1 and p2 then '' else ' not'</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">
(defun test-rule (rule-name examples counter-examples)
(let ((plausible (if (> examples (* 2 counter-examples)) 'plausible 'not-plausible)))
Line 643 ⟶ 1,557:
(plausibility "Dictionary" #p"unixdict.txt" #'parse-dict)
(plausibility "Word frequencies (stretch goal)" #p"1_2_all_freq.txt" #'parse-freq)
</syntaxhighlight>
</lang>
 
{{out}}
Line 661 ⟶ 1,575:
=={{header|D}}==
The extra work has not been attempted
<langsyntaxhighlight Dlang="d">import std.file;
import std.stdio;
 
Line 784 ⟶ 1,698:
}
return cnt;
}</langsyntaxhighlight>
 
{{out}}
Line 791 ⟶ 1,705:
'I before E when not preceded by C' is plausible with evidence 2.147465
'E before I when preceded by C' is not plausible with evidence 0.541667</pre>
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IOUtils}}
{{Trans|C sharp}}
<syntaxhighlight lang="delphi">
program I_before_E_except_after_C;
 
uses
System.SysUtils, System.IOUtils;
 
function IsOppPlausibleWord(w: string): Boolean;
begin
if ((not w.Contains('c')) and (w.Contains('ei'))) then
exit(True);
 
if (w.Contains('cie')) then
exit(True);
 
exit(false);
end;
 
function IsPlausibleWord(w: string): Boolean;
begin
if ((not w.Contains('c')) and (w.Contains('ie'))) then
exit(True);
 
if (w.Contains('cie')) then
exit(True);
 
exit(false);
end;
 
function IsPlausibleRule(filename: TFileName): Boolean;
var
words: TArray<string>;
trueCount, falseCount: Cardinal;
w: string;
begin
words := TFile.ReadAllLines(filename, TEncoding.UTF8);
trueCount := 0;
falseCount := 0;
 
for w in words do
begin
if (IsPlausibleWord(w)) then
inc(trueCount)
else if (IsOppPlausibleWord(w)) then
inc(falseCount);
 
end;
 
Writeln('Plausible count: ', trueCount);
Writeln('Implausible count: ', falseCount);
 
Result := trueCount > 2 * falseCount;;
 
end;
 
begin
if (IsPlausibleRule('unixdict.txt')) then
Writeln('Rule is plausible.')
else
Writeln('Rule is not plausible.');
 
end.</syntaxhighlight>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">\util.g
 
/* variables to hold totals for each possibility */
word cie, xie, cei, xei;
 
/* classify a word and add it to the proper total */
proc nonrec classify(*char w) void:
if CharsIndex(w, "ie") /= -1 then
if CharsIndex(w, "cie") /= -1
then cie := cie + 1
else xie := xie + 1
fi
elif CharsIndex(w, "ei") /= -1 then
if CharsIndex(w, "cei") /= -1
then cei := cei + 1
else xei := xei + 1
fi
fi
corp
 
/* see if a clause is plausible */
proc nonrec plausible(*char clause; word match, nomatch) bool:
bool p;
p := 2*match > nomatch;
writeln(clause, ": ", if p then "" else "not " fi, "plausible.");
p
corp
 
proc nonrec main() void:
file() dict_file;
channel input text dict_ch;
[256] char line;
bool p;
cie := 0;
xie := 0;
cei := 0;
xei := 0;
/* read every word */
open(dict_ch, dict_file, "unixdict.txt");
while readln(dict_ch; &line[0]) do
classify(&line[0])
od;
close(dict_ch);
/* print statistics */
writeln("CIE: ", cie:5);
writeln("xIE: ", xie:5);
writeln("CEI: ", cei:5);
writeln("xEI: ", xei:5);
/* see if the propositions are plausible */
p := plausible("I before E when not preceded by C", xie, cie);
p := plausible("E before I when preceded by C", cei, xei) and p;
writeln("I before E except after C: ",
if p then "" else "not " fi,
"plausible.")
corp</syntaxhighlight>
{{out}}
<pre>CIE: 24
xIE: 465
CEI: 13
xEI: 209
I before E when not preceded by C: plausible.
E before I when preceded by C: not plausible.
I before E except after C: not plausible.</pre>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def task(path) do
plausibility_ratio = 2
Line 822 ⟶ 1,871:
 
path = hd(System.argv)
IO.inspect RC.task(path)</langsyntaxhighlight>
 
{{out}}
Line 835 ⟶ 1,884:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(cei).
-export([plaus/0,count/3]).
Line 860 ⟶ 1,909:
nomatch -> count(T,Pattern, Acc)
end.
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 870 ⟶ 1,919:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators formatting generalizations io.encodings.utf8
io.files kernel literals math prettyprint regexp sequences ;
IN: rosetta-code.i-before-e
Line 892 ⟶ 1,941:
 
"I before E when not preceded by C"
"E before I when preceded by C" [ output ] bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 904 ⟶ 1,953:
=={{header|Fortran}}==
Please find the linux build instructions along with example run in the comments at the beginning of the f90 source. Thank you.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sat May 18 22:19:19
Line 976 ⟶ 2,025:
end function plausibility
end program cia
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight FreeBASIClang="freebasic">Function getfile(file As String) As String
Dim As Integer F = Freefile
Dim As String text,intext
Line 1,028 ⟶ 2,077:
print "So, the idea is not plausible."
 
Sleep</langsyntaxhighlight>
{{out}}
<pre>The number of words in unixdict.txt 25104
Line 1,042 ⟶ 2,091:
ei is not plausible when preceeded by c, the ratio is 0.5416666666666666
So, the idea is not plausible.</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">include "NSLog.incl"
 
#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
 
void local fn CheckWord( wrd as CFStringRef, txt as CFStringRef, c as ^long, x as ^long )
CFRange range = fn StringRangeOfString( wrd, txt )
while ( range.location != NSNotFound )
if ( range.location > 0 )
select ( fn StringCharacterAtIndex( wrd, range.location-1 ) )
case _"c"
*c += 1
case else
*x += 1
end select
else
*x += 1
end if
range.location++
range.length = len(wrd) - range.location
range = fn StringRangeOfStringWithOptionsInRange( wrd, txt, 0, range )
wend
end fn
 
void local fn Doit
CFURLRef url = fn URLWithString( @"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" )
CFStringRef string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
CFArrayRef words = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet )
long cei = 0, cie = 0, xei = 0, xie = 0
CFStringRef wrd, result
for wrd in words
fn CheckWord( wrd, @"ei", @cei, @xei )
fn CheckWord( wrd, @"ie", @cie, @xie )
next
NSLog(@"cei: %ld",cei)
NSLog(@"cie: %ld",cie)
NSLog(@"xei: %ld",xei)
NSLog(@"xie: %ld",xie)
if 2 * xie <= cie then result = @"not plausible" else result = @"plausible"
NSLog( @"\nI before E when not preceded by C: %@.\n¬
There are %ld examples and %ld counter-examples for a ratio of %f.\n", ¬
result, xie, xei, ( ( (float)xie - (float)cie ) / ( (float)xei - (float)cei ) ) )
if 2 * cei <= xei then result = @"not plausible" else result = @"plausible"
NSLog( @"E before I when preceded by C: %@.\n¬
There are %ld examples and %ld counter-examples for a ratio of %f.\n", ¬
result, cei, cie, ( (float)cei / (float)cie ) )
end fn
 
fn DoIt
 
HandleEvents</syntaxhighlight>
 
{{output}}
<pre>cei: 13
cie: 24
xei: 217
xie: 466
 
I before E when not preceded by C: plausible.
There are 466 examples and 217 counter-examples for a ratio of 2.166667.
 
E before I when preceded by C: not plausible.
There are 13 examples and 24 counter-examples for a ratio of 0.541667.</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,111 ⟶ 2,228:
}
return false
}</langsyntaxhighlight>
 
{{out}}
Line 1,125 ⟶ 2,242:
This solution does not attempt the stretch goal.
 
<langsyntaxhighlight Haskelllang="haskell">import Network.HTTP
import Text.Regex.TDFA
import Text.Printf
Line 1,149 ⟶ 2,266:
rule2Plausible = numTrueRule2 > (2*numFalseRule2)
printf "Rule 2 is correct for %d\n incorrect for %d\n" numTrueRule2 numFalseRule2
printf "*** Rule 2 is %splausible.\n" (if rule2Plausible then "" else "im")</langsyntaxhighlight>
 
{{out}}
Line 1,170 ⟶ 2,287:
same input line should all be tested.
 
<langsyntaxhighlight Uniconlang="unicon">import Utils # To get the FindFirst class
 
procedure main(a)
Line 1,188 ⟶ 2,305:
 
if \showCounts then every write(phrase := !phrases,": ",totals[phrase])
end</langsyntaxhighlight>
 
{{out}} of running with <tt>--showcounts</tt> flag:
Line 1,205 ⟶ 2,322:
=== stretch goal ===
 
<langsyntaxhighlight Uniconlang="unicon">import Utils # To get the FindFirst class
 
procedure main(a)
Line 1,229 ⟶ 2,346:
 
if \showCounts then every write(phrase := !phrases,": ",totals[phrase])
end</langsyntaxhighlight>
 
{{out}}
Line 1,248 ⟶ 2,365:
After downloading unixdict to /tmp:
 
<langsyntaxhighlight Jlang="j"> dict=:tolower fread '/tmp/unixdict.txt'</langsyntaxhighlight>
 
Investigating the rules:
 
<langsyntaxhighlight Jlang="j"> +/'cie' E. dict
24
+/'cei' E. dict
Line 1,259 ⟶ 2,376:
490
+/'ei' E. dict
230</langsyntaxhighlight>
 
So, based on unixdict.txt, the "I before E" rule seems plausible (490 > 230 by more than a factor of 2), but the exception does not make much sense (we see almost twice as many i before e after a c as we see e before i after a c).
Line 1,269 ⟶ 2,386:
After downloading 1_2_all_freq to /tmp, we can read it into J, and break out the first column (as words) and the third column as numbers:
 
<langsyntaxhighlight Jlang="j">allfreq=: |:}.<;._1;._2]1!:1<'/tmp/1_2_all_freq.txt'
 
words=: >0 { allfreq
freqs=: 0 {.@".&>2 { allfreq</langsyntaxhighlight>
 
With these definitions, we can define a prevalence verb which will tell us how often a particular substring is appears in use:
 
<langsyntaxhighlight Jlang="j">prevalence=:verb define
(y +./@E."1 words) +/ .* freqs
)</langsyntaxhighlight>
 
Investigating our original proposed rules:
 
<langsyntaxhighlight Jlang="j"> 'ie' %&prevalence 'ei'
1.76868</langsyntaxhighlight>
 
A generic "i before e" rule is not looking quite as good now - words that have i before e are used less than twice as much as words which use e before i.
 
<langsyntaxhighlight Jlang="j"> 'cei' %&prevalence 'cie'
0.328974</langsyntaxhighlight>
 
An "except after c" variant is looking awful now - words that use the cie sequence are three times as likely as words that use the cei sequence. So, of course, if we modified our original rule with this exception it would weaken the original rule:
 
<langsyntaxhighlight Jlang="j"> ('ie' -&prevalence 'cie') % ('ei' -&prevalence 'cei')
1.68255</langsyntaxhighlight>
 
Note that we might also want to consider non-adjacent matches (the regular expression 'i.*e' instead of 'ie' or perhaps 'c.*ie' or 'c.*i.*e' instead of 'cie') - this would be straightforward to check, but this would bulk up the page. (And, to be meaningful, we'd want a more constrained wildcard than <code>.*</code> -- at the very least we would not want to span words.)
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
</syntaxhighlight>
<syntaxhighlight lang="java">
public static void main(String[] args) throws URISyntaxException, IOException {
count();
System.out.printf("%-10s %,d%n", "total", total);
System.out.printf("%-10s %,d%n", "'cei'", cei);
System.out.printf("%-10s %,d%n", "'cie'", cie);
System.out.printf("%,d > (%,d * 2) = %b%n", cei, cie, cei > (cie * 2));
System.out.printf("%,d > (%,d * 2) = %b", cie, cei, cie > (cei * 2));
}
 
static int total = 0;
static int cei = 0;
static int cie = 0;
 
static void count() throws URISyntaxException, IOException {
URL url = new URI("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").toURL();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.matches(".*?(?:[^c]ie|cei).*")) {
cei++;
} else if (line.matches(".*?(?:[^c]ei|cie).*")) {
cie++;
}
total++;
}
}
}
</syntaxhighlight>
<pre>
total 25,104
'cei' 477
'cie' 215
477 > (215 * 2) = true
215 > (477 * 2) = false
</pre>
<br />
An alternate demonstration<br>
Download and save wordlist to unixdict.txt.
 
<langsyntaxhighlight lang="java">
import java.io.BufferedReader;
import java.io.FileReader;
Line 1,359 ⟶ 2,522:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,370 ⟶ 2,533:
 
WARNING: The problem statement is misleading as the rule only applies to syllables that rhyme with "see".
<langsyntaxhighlight lang="jq">def plausibility_ratio: 2;
 
# scan/2 produces a stream of matches but the first match of a segment (e.g. cie)
Line 1,404 ⟶ 2,567:
as ratio = \($x)/\($y) ~ \($ratio * 100 |round)%" ;
 
"Using the problematic criterion specified in the task requirements:", assess</langsyntaxhighlight>
{{out}}
Using http://www.puzzlers.org/pub/wordlists/unixdict.txt as of June 2015:
<langsyntaxhighlight lang="sh">$ jq -s -R -r -f I_before_E_except_after_C.jq unixdict.txt
Using the problematic criterion specified in the task requirements:
-- the rule "E before I when preceded by C" is implausible
as ratio = 13/24 ~ 54%
-- the rule "I before E when not preceded by C" is plausible
as ratio = 464/217 ~ 214%</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.0.6
 
open("unixdict.txt") do txtfile
Line 1,442 ⟶ 2,605:
print("Plausibility of \"E before I when preceded by C\":")
println(rule2 > 2 * notrule2 ? "PLAUSIBLE" : "UNPLAUSIBLE")
end</langsyntaxhighlight>
 
{{out}}
Line 1,449 ⟶ 2,612:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.net.URL
Line 1,509 ⟶ 2,672:
println()
printResults("British National Corpus", counts2)
}</langsyntaxhighlight>
 
{{out}}
Line 1,541 ⟶ 2,704:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">
local(cie,cei,ie,ei) = (:0,0,0,0)
 
Line 1,575 ⟶ 2,738:
)
stdoutnl(`Overall the rule is ` + (#ie_plausible and #cei_plausible ? `` | `NOT-`) + `PLAUSIBLE`)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,584 ⟶ 2,747:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Needed to get dictionary file from web server
local http = require("socket.http")
 
Line 1,615 ⟶ 2,778:
io.write("Overall the phrase is ")
if not (sub1 and sub2) then io.write("not ") end
print("plausible.")</langsyntaxhighlight>
{{out}}
<pre>I before E when not preceded by C: PLAUSIBLE
Line 1,622 ⟶ 2,785:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">words:= HTTP:-Get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"):
lst := StringTools:-Split(words[2],"\n"):
xie, cie, cei, xei := 0, 0, 0, 0:
Line 1,644 ⟶ 2,807:
printf("The first phrase is %s with supporting features %d, anti features %d\n", piecewise(p1, "plausible", "not plausible"), xie, xei);
printf("The seond phrase is %s with supporting features %d, anti features %d\n", piecewise(p2, "plausible", "not plausible"), cei, cie);
printf("The overall phrase is %s\n", piecewise(p1 and p2, "plausible", "not plausible")):</langsyntaxhighlight>
{{Out|Output}}
<pre>The first phrase is plausible with supporting features 465 and anti features 213
Line 1,651 ⟶ 2,814:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">wordlist =
Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt",
"Words"];
Line 1,677 ⟶ 2,840:
ToString[N[cei/cie]]]
Print["Overall the rule is " <>
If[test1 && test2, "PLAUSIBLE", "NOT PLAUSIBLE" ]]</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="mathematica">The number of words in unixdict.txt = 25104
The rule "I before E when not preceded by C" is PLAUSIBLE
There were 465 examples and 213 counter examples, for a ratio of 2.1831
Line 1,686 ⟶ 2,849:
There were 13 examples and 24 counter examples, for a ratio of 0.541667
Overall the rule is NOT PLAUSIBLE
</syntaxhighlight>
</lang>
 
=={{header|MATLAB}} / {{header|Octave}}==
{{incomplete|MATLAB|Is the original phrase plausible?}}
 
<syntaxhighlight lang="matlab">
<lang MATLAB>function i_before_e_except_after_c(f)
function iBeforeE()
check('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt');
fprintf('\n');
check('http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt');
end
 
function check(URL)
fid = fopen(f,'r');
fprintf('For %s:\n', URL)
nei = 0;
[~, name, ext] = fileparts(URL);
fn = [name ext];
if exist(fn,'file')
lines = readlines(fn, 'EmptyLineRule', 'skip');
else
fprintf('Reading data from %s\n', URL)
lines = readlines(URL, 'EmptyLineRule', 'skip');
% Save the file for later
writelines(lines,fn);
end
includesFrequencyData = length(split(lines(1))) > 1;
ie = 0;
cie = 0;
ei = 0;
cei = 0;
for i = 1:size(lines,1)
nie = 0;
if includesFrequencyData
cie = 0;
fields = split(strtrim(lines(i)));
while ~feof(fid)
if length(fields) ~= 3 || i == 1
c = strsplit(strtrim(fgetl(fid)),char([9,32]));
continue;
if length(c) > 2,
end
n = str2num(c{3});
word = fields(1);
else
frequency = str2double(fields(3));
n = 1;
else
end;
word = lines(i);
if strfind(c{1},'ei')>1, nei=nei+n; end;
frequency = 1;
if strfind(c{1},'cei'), cei=cei+n; end;
end
if strfind(c{1},'ie')>1, nie=nie+n; end;
if ie = ie + length(strfind(c{1}word,'cieie'), ) cie=cie+n;* endfrequency;
ei = ei + length(strfind(word,'ei')) * frequency;
end;
cie = cie + length(strfind(word,'cie')) * frequency;
fclose(fid);
cei = cei + length(strfind(word,'cei')) * frequency;
end
rule1 = "I before E when not preceded by C";
p1 = reportPlausibility(rule1, ie-cie, ei-cei );
rule2 = "E before I when preceded by C";
p2 = reportPlausibility(rule2, cei, cie );
combinedRule = "I before E, except after C";
fprintf('Hence the combined rule \"%s\" is ', combinedRule);
if ~(p1 && p2)
fprintf('NOT ');
end
fprintf('PLAUSIBLE.\n');
end
 
function plausible = reportPlausibility(claim, positive, negative)
printf('cie: %i\nnie: %i\ncei: %i\nnei: %i\n',cie,nie-cie,cei,nei-cei);
vplausible = ''true;
fprintf('\"%s\" is ', claim);
if (nie < 3 * cie)
if positive <= 2*negative
v=' not';
plausible = false;
fprintf('NOT ')
end
fprintf('PLAUSIBLE,\n since the ratio of positive to negative examples is %d/%d = %0.2f.\n', positive, negative, positive/negative )
printf('I before E when not preceded by C: is%s plausible\n',v);
v = '';
if (nei > 3 * cei)
v=' not';
end
</syntaxhighlight>
printf('E before I when preceded by C: is%s plausible\n',v);
</lang>
 
<pre>
<pre>octave:23> i_before_e_except_after_c 1_2_all_freq.txt
>> iBeforeE
cie: 994
For http://wiki.puzzlers.org/pub/wordlists/unixdict.txt:
nie: 8133
"I before E when not preceded by C" is PLAUSIBLE,
cei: 327
since the ratio of positive to negative examples is 466/217 = 2.15.
nei: 4274
I"E before EI when not preceded by C:" is plausibleNOT PLAUSIBLE,
since the ratio of positive to negative examples is 13/24 = 0.54.
E before I when preceded by C: is not plausible
Hence the combined rule "I before E, except after C" is NOT PLAUSIBLE.
octave:24> i_before_e_except_after_c unixdict.txt
 
cie: 24
For http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt:
nie: 464
"I before E when not preceded by C" is NOT PLAUSIBLE,
cei: 13
since the ratio of positive to negative examples is 8207/4826 = 1.70.
nei: 191
I"E before EI when not preceded by C:" is plausibleNOT PLAUSIBLE,
since the ratio of positive to negative examples is 327/994 = 0.33.
E before I when preceded by C: is not plausible</pre>
Hence the combined rule "I before E, except after C" is NOT PLAUSIBLE.
</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE IEC;
IMPORT SeqIO;
IMPORT Texts;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Pos;
 
VAR words, cie, cei, xie, xei: CARDINAL;
xie_plausible, cei_plausible: BOOLEAN;
PROCEDURE Classify(word: ARRAY OF CHAR);
VAR end: CARDINAL;
BEGIN
INC(words);
end := Pos("", word);
IF Pos("ie", word) # end THEN
IF Pos("cie", word) # end
THEN INC(cie);
ELSE INC(xie);
END;
ELSIF Pos("ei", word) # end THEN
IF Pos("cei", word) # end
THEN INC(cei);
ELSE INC(xei);
END;
END;
END Classify;
 
PROCEDURE ProcessFile(filename: ARRAY OF CHAR);
VAR file: SeqIO.FILE;
dict: Texts.TEXT;
word: ARRAY [0..63] OF CHAR;
fs: SeqIO.FileState;
ts: Texts.TextState;
BEGIN
fs := SeqIO.Open(file, filename);
ts := Texts.Connect(dict, file);
WHILE NOT Texts.EOT(dict) DO
Texts.ReadLn(dict, word);
Classify(word);
END;
ts := Texts.Disconnect(dict);
fs := SeqIO.Close(file);
END ProcessFile;
 
PROCEDURE WriteStat(name: ARRAY OF CHAR; num: CARDINAL);
BEGIN
WriteString(name);
WriteString(": ");
WriteCard(num, 0);
WriteLn;
END WriteStat;
 
PROCEDURE Plausible(feature: ARRAY OF CHAR; match, nomatch: CARDINAL): BOOLEAN;
VAR plausible: BOOLEAN;
BEGIN
WriteString(feature);
WriteString(": ");
plausible := 2 * match > nomatch;
IF NOT plausible THEN
WriteString("not ");
END;
WriteString("plausible.");
WriteLn;
RETURN plausible;
END Plausible;
 
BEGIN
words := 0;
cie := 0;
cei := 0;
xie := 0;
xei := 0;
ProcessFile("unixdict.txt");
WriteStat("Amount of words", words);
WriteStat("CIE", cie);
WriteStat("xIE", xie);
WriteStat("CEI", cei);
WriteStat("xEI", xei);
WriteLn;
xie_plausible :=
Plausible("I before E when not preceded by C", xie, cie);
cei_plausible :=
Plausible("E before I when preceded by C", cei, xei);
WriteString("I before E, except after C: ");
IF NOT (xie_plausible AND cei_plausible) THEN
WriteString("not ");
END;
WriteString("plausible.");
WriteLn;
END IEC.</syntaxhighlight>
{{out}}
<pre>Amount of words: 50209
CIE: 24
xIE: 465
CEI: 13
xEI: 209
 
I before E when not preceded by C: plausible.
E before I when preceded by C: not plausible.
I before E, except after C: not plausible.</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import httpclient, strutils, strformat
 
const
Rule1 = "\"I before E when not preceded by C\""
Rule2 = "\"E before I when preceded by C\""
Phrase = "\"I before E except after C\""
PlausibilityText: array[bool, string] = ["not plausible", "plausible"]
 
 
proc plausibility(rule: string; count1, count2: int): bool =
## Compute, display and return plausibility.
result = count1 > 2 * count2
stdout.write &"The rule {rule} is {PlausibilityText[result]}: "
echo &"there were {count1} examples and {count2} counter-examples."
 
 
let client = newHttpClient()
 
var nie, cie, nei, cei = 0
for word in client.getContent("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").split():
if word.contains("ie"):
if word.contains("cie"):
inc cie
else:
inc nie
if word.contains("ei"):
if word.contains("cei"):
inc cei
else:
inc nei
 
let p1 = plausibility(Rule1, nie, nei)
let p2 = plausibility(Rule2, cei, cie)
echo &"So the phrase {Phrase} is {PlausibilityText[p1 and p2]}."</syntaxhighlight>
 
{{out}}
<pre>The rule "I before E when not preceded by C" is plausible: there were 465 examples and 213 counter-examples.
The rule "E before I when preceded by C" is not plausible: there were 13 examples and 24 counter-examples.
So the phrase "I before E except after C" is not plausible.</pre>
 
=={{header|Objeck}}==
{{trans|Seed7}}
<langsyntaxhighlight lang="objeck">
use HTTP;
use Collection;
Line 1,804 ⟶ 3,147:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,816 ⟶ 3,159:
(To be plausible, one word count must exceed another by 2 times)
</pre>
 
=={{header|Octave}}==
{{incomplete|MATLAB|Is the original phrase plausible?}}
 
<syntaxhighlight lang="matlab">function i_before_e_except_after_c(f)
 
fid = fopen(f,'r');
nei = 0;
cei = 0;
nie = 0;
cie = 0;
while ~feof(fid)
c = strsplit(strtrim(fgetl(fid)),char([9,32]));
if length(c) > 2,
n = str2num(c{3});
else
n = 1;
end;
if strfind(c{1},'ei')>1, nei=nei+n; end;
if strfind(c{1},'cei'), cei=cei+n; end;
if strfind(c{1},'ie')>1, nie=nie+n; end;
if strfind(c{1},'cie'), cie=cie+n; end;
end;
fclose(fid);
 
printf('cie: %i\nnie: %i\ncei: %i\nnei: %i\n',cie,nie-cie,cei,nei-cei);
v = '';
if (nie < 3 * cie)
v=' not';
end
printf('I before E when not preceded by C: is%s plausible\n',v);
v = '';
if (nei > 3 * cei)
v=' not';
end
printf('E before I when preceded by C: is%s plausible\n',v);
</syntaxhighlight>
 
<pre>octave:23> i_before_e_except_after_c 1_2_all_freq.txt
cie: 994
nie: 8133
cei: 327
nei: 4274
I before E when not preceded by C: is plausible
E before I when preceded by C: is not plausible
octave:24> i_before_e_except_after_c unixdict.txt
cie: 24
nie: 464
cei: 13
nei: 191
I before E when not preceded by C: is plausible
E before I when preceded by C: is not plausible</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 1,851 ⟶ 3,246:
$result += result($support, $against);
 
print 'Overall: ', 'NOT ' x ($result < 2), "PLAUSIBLE.\n";</langsyntaxhighlight>
 
{{out}}
Line 1,860 ⟶ 3,255:
===Perl: Stretch Goal===
Just replace the while loop with the following one:
<langsyntaxhighlight lang="perl">while (<>) {
my @columns = split;
next if 3 < @columns;
Line 1,867 ⟶ 3,262:
$count{$k} += $freq if -1 != index $word, $k;
}
}</langsyntaxhighlight>
{{out}}
<pre>I before E when not preceded by C: 8148 / 4826 = 1.69. NOT PLAUSIBLE
Line 1,874 ⟶ 3,269:
 
=={{header|Phix}}==
Kept dirt simple, difficult to imagine anythingany beingother muchapproach being faster than this.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>-- demo\rosetta\IbeforeE.exw
<span style="color: #000080;font-style:italic;">-- demo\rosetta\IbeforeE.exw</span>
procedure show_plausibility(string msg, integer w, wo)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
string no = iff(w<2*wo?" not":"")
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show_plausibility</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">wo</span><span style="color: #0000FF;">)</span>
printf(1, "%s (pro: %3d, anti: %3d) is%s plausible\n",{msg,w,wo,no})
<span style="color: #004080;">string</span> <span style="color: #000000;">no</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">w</span><span style="color: #0000FF;"><</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">wo</span><span style="color: #0000FF;">?</span><span style="color: #008000;">" not"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"%s (pro: %3d, anti: %3d) is%s plausible\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">,</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wo</span><span style="color: #0000FF;">,</span><span style="color: #000000;">no</span><span style="color: #0000FF;">})</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
object text = get_text(join_path({"..","unixdict.txt"}))
if not string(text) then
<span style="color: #004080;">string</span> <span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">unix_dict</span><span style="color: #0000FF;">())</span>
crash("unixdict.txt error, download from http://www.puzzlers.org/pub/wordlists/unixdict.txt")
<span style="color: #000080;font-style:italic;">-- Note: my unixdict.txt begins with "10th" and ends with "zygote", so
end if
-- boundary checks such as "i&gt;=2 and i+1&lt;=length(text)" can be skipped.</span>
-- Note: my unixdict.txt begins with "10th" and ends with "zygote", so
<span style="color: #004080;">integer</span> <span style="color: #000000;">cei</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xei</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cie</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xie</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
-- boundary checks (such as "i+1<=length(text) and ") can be skipped.
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer {cei,xei,cie,xie} @= 0
<span style="color: #008080;">if</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">'i'</span> <span style="color: #008080;">then</span>
for i=1 to length(text) do
<span style="color: #008080;">if</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">'e'</span> <span style="color: #008080;">then</span>
if text[i]='i' then
<span style="color: #008080;">if</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">'c'</span> <span style="color: #008080;">then</span>
if text[i-1]='e' then
<span style="color: #000000;">cei</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if text[i-2]='c' then
<span cei +style="color: 1#008080;">else</span>
<span style="color: #000000;">xei</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
else
<span style="color: #008080;">end</span> xei<span +style="color: 1#008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000080;font-style:italic;">-- (nb not elsif here; "eie" occurs twice)</span>
end if
<span style="color: #008080;">if</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">'e'</span> <span style="color: #008080;">then</span>
-- (not elsif here; "eie" occurs twice)
<span style="color: #008080;">if</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">'c'</span> <span style="color: #008080;">then</span>
if text[i+1]='e' then
<span style="color: #000000;">cie</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if text[i-1]='c' then
<span cie +style="color: 1#008080;">else</span>
<span style="color: #000000;">xie</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
else
<span style="color: #008080;">end</span> xie<span +style="color: 1#008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"occurances: cie:%d, xie:%d, cei:%d, xei:%d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">cie</span><span style="color: #0000FF;">,</span><span style="color: #000000;">xie</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cei</span><span style="color: #0000FF;">,</span><span style="color: #000000;">xei</span><span style="color: #0000FF;">})</span>
end for
<span style="color: #000000;">show_plausibility</span><span style="color: #0000FF;">(</span> <span style="color: #008000;">"i before e except after c"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xie</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cie</span> <span style="color: #0000FF;">);</span>
printf(1,"occurances: cie:%d, xie:%d, cei:%d, xei:%d\n", {cie,xie,cei,xei})
<span style="color: #000000;">show_plausibility</span><span style="color: #0000FF;">(</span> <span style="color: #008000;">"e before i except after c"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xei</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cei</span> <span style="color: #0000FF;">);</span>
show_plausibility("i before e except after c", xie, cie)
<span style="color: #000000;">show_plausibility</span><span style="color: #0000FF;">(</span> <span style="color: #008000;">"i before e when after c"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cie</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cei</span> <span style="color: #0000FF;">);</span>
show_plausibility("e before i except after c", xei, cei)
<span style="color: #000000;">show_plausibility</span><span style="color: #0000FF;">(</span> <span style="color: #008000;">"e before i when after c"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cei</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cie</span> <span style="color: #0000FF;">);</span>
show_plausibility("i before e when after c", cie, cei)
<span style="color: #000000;">show_plausibility</span><span style="color: #0000FF;">(</span> <span style="color: #008000;">"i before e in general"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xie</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">cie</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xei</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">cei</span> <span style="color: #0000FF;">);</span>
show_plausibility("e before i when after c", cei, cie)
<span style="color: #000000;">show_plausibility</span><span style="color: #0000FF;">(</span> <span style="color: #008000;">"e before i in general"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xei</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">cei</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xie</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">cie</span> <span style="color: #0000FF;">)</span>
show_plausibility("i before e in general", xie + cie, xei + cei)
<!--</syntaxhighlight>-->
show_plausibility("e before i in general", xei + cei, xie + cie)</lang>
{{out}}
Although the output matches, I decided to use different metrics from ALGOL 68 for the middle two conclusions.<br>
Line 1,927 ⟶ 3,322:
e before i in general (pro: 230, anti: 490) is not plausible
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
Words = read_file_lines("unixdict.txt"),
IEWords = [Word : Word in Words, find(Word,"ie",_,_)],
EIWords = [Word : Word in Words, find(Word,"ei",_,_)],
 
% cie vs not cie
[CIE_len, CIE_not_len] = partition_len(IEWords,"cie"),
println([cie=CIE_len,cie_not=CIE_not_len]),
 
% cei vs not cei
[CEI_len, CEI_not_len] = partition_len(EIWords,"cei"),
println([cei=CEI_len,cei_not=CEI_not_len]),
 
nl,
printf("I before E when not preceeded by C (%d vs %d): %w\n",
CIE_not_len,CEI_not_len,plausible(CIE_not_len,CEI_not_len)),
printf("E before I when preceeded by C (%d cs %d): %w\n",
CEI_len,CIE_len,plausible(CEI_len,CIE_len)).
 
plausible(Len1,Len2) = cond(Len1 / Len2 > 2,"plausible","not plausible").
 
partition_len(Words,Sub) = [True.len, False.len] =>
True = [],
False = [],
foreach(Word in Words)
if find(Word,Sub,_,_) then
True := [Word|True]
else
False := [Word|False]
end
end.</syntaxhighlight>
 
{{out}}
<pre>[cie = 24,cie_not = 465]
[cei = 13,cei_not = 213]
 
I before E when not preceeded by C (465 vs 213): plausible
E before I when preceeded by C (13 cs 24): not plausible</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de ibEeaC (File . Prg)
(let
(Cie (let N 0 (in File (while (from "cie") (run Prg))))
Line 1,959 ⟶ 3,394:
 
(ibEeaC "1_2_all_freq.txt"
(inc 'N (format (stem (line) "\t"))) )</langsyntaxhighlight>
Output:
<pre>cie: 24
Line 1,976 ⟶ 3,411:
E before I when after C: is not plausible
Overall rule is not plausible</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">iBeforeE: procedure options(main);
declare dict file;
open file(dict) title('unixdict.txt');
on endfile(dict) go to report;
declare (cie, xie, cei, xei) fixed;
declare word char(32) varying;
cie = 0;
xie = 0;
cei = 0;
xei = 0;
do while('1'b);
get file(dict) list(word);
if index(word, 'ie') ^= 0 then
if index(word, 'cie') ^= 0 then
cie = cie + 1;
else
xie = xie + 1;
if index(word, 'ei') ^= 0 then
if index(word, 'cei') ^= 0 then
cei = cei + 1;
else
xei = xei + 1;
end;
report:
close file(dict);
put skip list('CIE:', cie);
put skip list('xIE:', xie);
put skip list('CEI:', cei);
put skip list('xEI:', xei);
declare (ieNotC, eiC) bit;
ieNotC = xie * 2 > cie;
eiC = cei * 2 > xei;
 
put skip list('I before E when not preceded by C:');
if ^ieNotC then put list('not');
put list('plausible.');
 
put skip list('E before I when preceded by C:');
if ^eiC then put list('not');
put list('plausible.');
 
put skip list('I before E, except after C:');
if ^(ieNotC & eiC) then put list('not');
put list('plausible.');
end iBeforeE;</syntaxhighlight>
{{out}}
<pre>CIE: 24
xIE: 465
CEI: 13
xEI: 213
I before E when not preceded by C: plausible.
E before I when preceded by C: not plausible.
I before E, except after C: not plausible.</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight Powershelllang="powershell">$Web = New-Object -TypeName Net.Webclient
$Words = $web.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt')
Line 2,006 ⟶ 3,500:
if ($Clause1 -and $Clause2)
{$MainClause = $True}
"The plausibility of the phrase 'I before E except after C' is $MainClause"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,015 ⟶ 3,509:
 
==={{header|Alternative Implementation}}===
<langsyntaxhighlight Powershelllang="powershell">$Web = New-Object -TypeName Net.Webclient
$Words = $web.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt')
Line 2,043 ⟶ 3,537:
if ($Clause1 -and $Clause2)
{$MainClause = $True}
"The plausibility of the phrase 'I before E except after C' is $MainClause"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,049 ⟶ 3,543:
The plausibility of 'E before I when preceded by C' is False
The plausibility of the phrase 'I before E except after C' is False
</pre>
==={{header|Alternative Implementation 2}}===
A single pass through the wordlist using the regex engine.
<syntaxhighlight lang="powershell">$webResult = Invoke-WebRequest -Uri http://wiki.puzzlers.org/pub/wordlists/unixdict.txt -UseBasicParsing
 
$cie, $cei, $_ie, $_ei = 0, 0, 0, 0
 
[regex]::Matches($webResult.Content, '.(ie|ei)').foreach{
if ($_.Value -eq 'cie') { $cie+=2 }
elseif ($_.Value -eq 'cei') { $cei++ }
elseif ($_.Value[1] -eq 'i' ) { $_ie++ }
else { $_ei+=2 }
}
 
"I before E when not preceded by C is plausible: $($_ie -gt $_ei)"
"E before I when preceded by C is plausible: $($cei -gt $cie)"
"I before E, except after C is plausible: $(($_ie -gt $_ei) -and ($cei -gt $cie))"</syntaxhighlight>
{{out}}
<pre>
I before E when not preceded by C is plausible: True
E before I when preceded by C is plausible: False
I before E, except after C is plausible: False
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">If ReadFile(1,GetPathPart(ProgramFilename())+"wordlist(en).txt")
While Not Eof(1)
wl$+ReadString(1)+";"
Line 2,074 ⟶ 3,590:
Print("Overall the rule is : ")
If cei>cie And ie>ei : PrintN("PLAUSIBLE") : Else : PrintN("NOT PLAUSIBLE") : EndIf
Input()</langsyntaxhighlight>
{{out}}
<pre>
Line 2,090 ⟶ 3,606:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import urllib.request
import re
 
Line 2,126 ⟶ 3,642:
 
print('Checking plausibility of "I before E except after C":')
print_result(*simple_stats())</langsyntaxhighlight>
 
{{out}}
Line 2,142 ⟶ 3,658:
===Python: Stretch Goal===
Add the following to the bottom of the previous program:
<langsyntaxhighlight lang="python">def stretch_stats(url='http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt'):
freq = [line.strip().lower().split()
for line in urllib.request.urlopen(url)
Line 2,157 ⟶ 3,673:
print('\n\nChecking plausibility of "I before E except after C"')
print('And taking account of word frequencies in British English:')
print_result(*stretch_stats())</langsyntaxhighlight>
 
{{out|Produces this extra output}}
Line 2,171 ⟶ 3,687:
OVERALL IT IS IMPLAUSIBLE!
(To be plausible, one count must exceed another by 2 times)</pre>
 
 
=={{header|QBasic}}==
{{trans|BASIC}}
<syntaxhighlight lang="qbasic">DEFINT A-Z
DIM W AS STRING
CLS
OPEN "I", 1, "UNIXDICT.TXT"
DO
LINE INPUT #1, W
IF INSTR(W, "ie") THEN IF INSTR(W, "cie") THEN CI = CI + 1 ELSE XI = XI + 1
IF INSTR(W, "ei") THEN IF INSTR(W, "cei") THEN CE = CE + 1 ELSE XE = XE + 1
LOOP WHILE NOT EOF(1)
CLOSE #1
 
PRINT "CIE:"; CI
PRINT "xIE:"; XI
PRINT "CEI:"; CE
PRINT "xEI:"; XE
PRINT
PRINT "I before E when not preceded by C: ";
IF 2 * XI <= CI THEN PRINT "not ";
PRINT "plausible."
PRINT "E before I when preceded by C: ";
IF 2 * CE <= XE THEN PRINT "not ";
PRINT "plausible."</syntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">words = tolower(readLines("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"))
ie.npc = sum(grepl("(?<!c)ie", words, perl = T))
ei.npc = sum(grepl("(?<!c)ei", words, perl = T))
Line 2,184 ⟶ 3,726:
message("(1) is ", (if (p1) "" else "not "), "plausible.")
message("(2) is ", (if (p2) "" else "not "), "plausible.")
message("The whole phrase is ", (if (p1 && p2) "" else "not "), "plausible.")</langsyntaxhighlight>
 
{{out}}
Line 2,192 ⟶ 3,734:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
(define (get-tallies filename line-parser . patterns)
Line 2,223 ⟶ 3,765:
 
(plausibility "Dictionary" "unixdict.txt" (λ (line) (list line 1))) (newline)
(plausibility "Word frequencies (stretch goal)" "1_2_all_freq.txt" parse-frequency-data)</langsyntaxhighlight>
 
{{out}}
Line 2,243 ⟶ 3,785:
(formerly Perl 6)
This solution uses grammars and actions to parse the given file, the <tt>Bag</tt> for tallying up occurrences of each possible thing we're looking for ("ie", "ei", "cie", and "cei"), and junctions to determine the plausibility of a phrase from the subphrases. Note that a version of rakudo newer than the January 2014 compiler or Star releases is needed, as this code relies on a recent bugfix to the <tt>make</tt> function.
<syntaxhighlight lang="raku" perl6line>grammar CollectWords {
token TOP {
[^^ <word> $$ \n?]+
Line 2,310 ⟶ 3,852:
plausible($results<cei>, $results<cie>, "E before I when preceded by C");
 
say "I before E except after C: ", $phrasetest ?? "PLAUSIBLE" !! "NOT PLAUSIBLE";</langsyntaxhighlight>
 
{{out}}
Line 2,333 ⟶ 3,875:
 
This solution requires just a few modifications to the grammar and actions from the non-stretch goal.
<syntaxhighlight lang="raku" perl6line>grammar CollectWords {
token TOP {
^^ \t Word \t PoS \t Freq $$ \n
Line 2,366 ⟶ 3,908:
method word($/) {
if $<with_c> + $<no_c> {
make flat $<with_c>».ast xx +$<freq>, $<no_c>».ast xx +$<freq>;
} else {
make ();
Line 2,398 ⟶ 3,940:
plausible($results<cei>, $results<cie>, "E before I when preceded by C");
 
say "I before E except after C: ", $phrasetest ?? "PLAUSIBLE" !! "NOT PLAUSIBLE";</langsyntaxhighlight>
 
{{out}}
Line 2,404 ⟶ 3,946:
E before I when preceded by C: NOT PLAUSIBLE (327 vs. 994 ✘)
I before E except after C: NOT PLAUSIBLE</pre>
 
=={{header|Red}}==
The script processes both the task and the stretch goal.
In the stretch goal, "rows with three space or tab separated words only" (7574 out of 7726) are processed, excluding all expressions like "out of".
<syntaxhighlight lang="red">Red ["i before e except after c"]
 
testlist: function [wordlist /wfreq] [
cie: cei: ie: ei: 0
if not wfreq [forall wordlist [insert wordlist: next wordlist 1]]
foreach [word freq] wordlist [
parse word [ some [
"cie" (cie: cie + freq) |
"cei" (cei: cei + freq) |
"ie" (ie: ie + freq) |
"ei" (ei: ei + freq) |
skip
]]
]
print rejoin [
"i is before e " ie " times, and also " cie " times following c.^/"
"i is after e " ei " times, and also " cei " times following c.^/"
"Hence ^"i before e^" is " either a: 2 * ei < ie [""] ["not "] "plausible,^/"
"while ^"except after c^" is " either b: 2 * cie < cei [""] ["not "] "plausible.^/"
"Overall the rule is " either a and b [""] ["not "] "plausible."]
]
 
print "Results for unixdict.txt:"
testlist read/lines http://wiki.puzzlers.org/pub/wordlists/unixdict.txt
 
print "^/Results for British National Corpus:"
bnc: next read/lines %1_2_all_freq.txt
spaces: charset "^- "
bnclist: collect [ foreach w bnc [
if 3 = length? seq: split trim w spaces [
keep seq/1 keep to-integer seq/3
]]]
testlist/wfreq bnclist</syntaxhighlight>
 
{{out}}
<pre>Results for unixdict.txt:
i is before e 464 times, and also 24 times following c.
i is after e 217 times, and also 13 times following c.
Hence "i before e" is plausible,
while "except after c" is not plausible.
Overall the rule is not plausible.
 
Results for British National Corpus:
i is before e 8207 times, and also 994 times following c.
i is after e 4826 times, and also 327 times following c.
Hence "i before e" is not plausible,
while "except after c" is not plausible.
Overall the rule is not plausible.</pre>
 
=={{header|REXX}}==
Line 2,413 ⟶ 4,007:
 
===unweighted version===
<langsyntaxhighlight lang="rexx">/*REXX program shows plausibility of "I before E" when not preceded by C, and */
/*───────────────────────────────────── "E before I" when preceded by C. */
parse arg iFID . /*obtain optional argument from the CL.*/
Line 2,448 ⟶ 4,042:
else #.x.z=#.x.z + 1
s=_ + 1 /*handle the cases of multiple finds. */
end /*forever*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default dictionary:}}
<pre>
Line 2,484 ⟶ 4,078:
 
A cursory look at the file seems to indicate that the use of the tilde and/or asterisk doesn't affect the rules for the mantra phrases.
<langsyntaxhighlight lang="rexx">/*REXX program shows plausibility of "I before E" when not preceded by C, and */
/*───────────────────────────────────── "E before I" when preceded by C, using a */
/*───────────────────────────────────── weighted frequency for each word. */
Line 2,544 ⟶ 4,138:
if substr(u, _ - 1 + (_==1)*999, 1)=='C' then #.x.c=#.x.c + one
else #.x.z=#.x.z + one
s=_ + 1 /*handle the cases of multiple finds. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default dictionary and default word frequency list:}}
<pre>
Line 2,565 ⟶ 4,159:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : I before E except after C
 
Line 2,605 ⟶ 4,199:
end
return sum
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,619 ⟶ 4,213:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'open-uri'
 
plausibility_ratio = 2
Line 2,638 ⟶ 4,232:
 
puts "Overall: #{overall_plausible ? 'Plausible' : 'Implausible'}."
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,649 ⟶ 4,243:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::default::Default;
use std::ops::AddAssign;
 
Line 2,728 ⟶ 4,322:
);
}
</syntaxhighlight>
</lang>
<pre>
Counting Feature {
Line 2,742 ⟶ 4,336:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object I_before_E_except_after_C extends App {
val testIE1 = "(^|[^c])ie".r // i before e when not preceded by c
val testIE2 = "cie".r // i before e when preceded by c
Line 2,764 ⟶ 4,358:
println("E before I when preceded by C: "+plausibility(countsCEI))
println("Overall: "+plausibility(plausible(countsIE) && plausible(countsCEI)))
}</langsyntaxhighlight>
{{out}}
<pre>I before E when not preceded by C: plausible
Line 2,771 ⟶ 4,365:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "gethttp.s7i";
include "float.s7i";
Line 2,829 ⟶ 4,423:
writeln("(To be plausible, one word count must exceed another by " <& PLAUSIBILITY_RATIO <& " times)");
end if;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,841 ⟶ 4,435:
(To be plausible, one word count must exceed another by 2 times)
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program i_before_e_except_after_c;
init cie := 0, xie := 0, cei := 0, xei := 0;
 
dict := open("unixdict.txt", "r");
loop doing word := getline(dict); while word /= om do
classify(word);
end loop;
close(dict);
 
p :=
plausible("I before E when not preceded by C", xie, cie) and
plausible("E before I when preceded by C", cei, xei);
print;
print("I before E, except after C:" + (if p then "" else " not" end)
+ " plausible.");
 
proc classify(word);
if "ie" in word then
if "cie" in word then cie +:= 1;
else xie +:= 1;
end if;
elseif "ei" in word then
if "cei" in word then cei +:= 1;
else xei +:= 1;
end if;
end if;
end proc;
 
proc plausible(clause, feature, opposite);
p := 2 * feature > opposite;
print(clause + ":" + (if p then "" else " not" end) + " plausible.");
return p;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>I before E when not preceded by C: plausible.
E before I when preceded by C: not plausible.
 
I before E, except after C: not plausible.</pre>
 
=={{header|Swift}}==
Using [https://github.com/johnno1962/SwiftRegex/blob/master/SwiftRegex.swift SwiftRegex] for easy regex in strings.
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
let request = NSURLRequest(URL: NSURL(string: "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")!)
Line 2,898 ⟶ 4,533:
}
 
CFRunLoopRun()</langsyntaxhighlight>
{{out}}
<pre>
Line 2,904 ⟶ 4,539:
E before I when preceded by C is not plausable
I before E except after C is not plausible</pre>
 
=={{header|True BASIC}}==
{{trans|BASIC}}
<syntaxhighlight lang="qbasic">DEF EOF(f)
IF END #f THEN LET EOF = -1 ELSE LET EOF = 0
END DEF
 
CLEAR
OPEN #1: NAME "UNIXDICT.TXT", org text, ACCESS INPUT, create old
DO
LINE INPUT #1: w$
IF POS(w$,"ie")<>0 THEN
IF POS(w$,"cie")<>0 THEN LET ci = ci+1 ELSE LET xi = xi+1
END IF
IF POS(w$,"ei")<>0 THEN
IF POS(w$,"cei")<>0 THEN LET ce = ce+1 ELSE LET xe = xe+1
END IF
LOOP WHILE (NOT EOF(1)<>0)
CLOSE #1
 
PRINT "CIE:"; ci
PRINT "xIE:"; xi
PRINT "CEI:"; ce
PRINT "xEI:"; xe
PRINT
PRINT "I before E when not preceded by C: ";
IF 2*xi <= ci THEN PRINT "not ";
PRINT "plausible."
PRINT "E before I when preceded by C: ";
IF 2*ce <= xe THEN PRINT "not ";
PRINT "plausible."
END</syntaxhighlight>
 
=={{header|Tcl}}==
{{trans|Python}}<!-- very approximately, mainly for the messages -->
<langsyntaxhighlight lang="tcl">package require http
 
variable PLAUSIBILITY_RATIO 2.0
Line 2,948 ⟶ 4,615:
}
puts "\n(To be plausible, one word count must exceed another by\
$PLAUSIBILITY_RATIO times)"</langsyntaxhighlight>
{{out}}
<!-- note that checking the pronunciation of the words indicates a key guard on the real rule that isn't normally stated -->
Line 2,966 ⟶ 4,633:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
words=REQUEST("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
Line 3,029 ⟶ 4,696:
 
TRAcE *check1,check2,checkall
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,042 ⟶ 4,709:
checkall = not plausible
</pre>
 
=={{header|uBasic/4tH}}==
{{trans|PowerShell}}
<syntaxhighlight lang="text">If Set(a, Open ("unixdict.txt", "r")) < 0 Then Print "Cannot open \qunixdict.txt\q" : End
 
x = Set (y, Set (p, Set (q, 0)))
 
Do While Read (a)
w = Tok(0)
If FUNC(_Search(w, "cei")) > -1 Then x = x + 1
If FUNC(_Search(w, "cie")) > -1 Then y = y + 1
If FUNC(_Search(w, "ie")) > -1 Then p = p + 1
If FUNC(_Search(w, "ei")) > -1 Then q = q + 1
Loop
 
Print "The plausibility of 'I before E when not preceded by C' is ";
Print Show (Iif (p>(q+q), "True", "False"))
 
Print "The plausibility of 'E before I when preceded by C' is ";
Print Show (Iif (x>(y+y), "True", "False"))
 
Print "The plausibility of the phrase 'I before E except after C' is ";
Print Show (Iif ((x>(y+y))*(p>(q+q)), "True", "False"))
 
Close a
End
 
_Search
Param (2)
Local (1)
For c@ = 0 to Len (a@) - Len (b@)
If Comp(Clip(Chop(a@,c@),Len(a@)-c@-Len(b@)),b@)=0 Then Unloop : Return (c@)
Next
Return (-1)</syntaxhighlight>
{{Out}}
<pre>The plausibility of 'I before E when not preceded by C' is True
The plausibility of 'E before I when preceded by C' is False
The plausibility of the phrase 'I before E except after C' is False
 
0 OK, 0:800 </pre>
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang="bash">#!/bin/sh
 
matched() {
Line 3,071 ⟶ 4,778:
echo "Overall, the rule is not plausible"
fi
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,081 ⟶ 4,788:
=={{header|VBScript}}==
The sample text was downloaded and saved in the same folder as the script.
<syntaxhighlight lang="vb">
<lang vb>
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
Line 3,130 ⟶ 4,837:
srcFile.Close
Set objFSO = Nothing
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,147 ⟶ 4,854:
Regex implementation does not technically conform to specification because it counts the number of occurrences of "ie" and "ei" instead of the number of words.
 
<langsyntaxhighlight lang="vbnet">Option Compare Binary
Option Explicit On
Option Infer On
Line 3,282 ⟶ 4,989:
End Sub
End Module
</syntaxhighlight>
</lang>
 
{{out|case=Loop implementation}}
Line 3,326 ⟶ 5,033:
 
Rule thus overall IS NOT plausible.</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import os
import strconv
 
fn main() {
mut cei, mut cie, mut ie, mut ei := f32(0), f32(0), f32(0), f32(0)
unixdict := os.read_file('./unixdict.txt') or {println('Error: file not found') exit(1)}
words := unixdict.split_into_lines()
println("The number of words in unixdict: ${words.len}")
for word in words {
cei += word.count('cei')
cie += word.count('cie')
ei += word.count('ei')
ie += word.count('ie')
}
print("Rule: 'e' before 'i' when preceded by 'c' at the ratio of ")
print("${strconv.f64_to_str_lnd1((cei / cie), 2)} is ")
if cei > cie {println("plausible.")} else {println("implausible.")}
println("$cei cases for and $cie cases against.")
 
print("Rule: 'i' before 'e' except after 'c' at the ratio of ")
print("${strconv.f64_to_str_lnd1(((ie - cie) / (ei - cei)), 2)} is ")
if ie > ei {println("plausible.")} else {println("implausible.")}
println("${(ie - cie)} cases for and ${(ei - cei)} cases against.")
 
print("Overall the rules are ")
if cei > cie && ie > ei {println("plausible.")} else {println("implausible.")}
}
</syntaxhighlight>
 
{{out}}
<pre>
The number of words in unixdict: 25104
Rule: 'e' before 'i' when preceded by 'c' at the ratio of 0.54 is implausible.
13 cases for and 24 cases against.
Rule: 'i' before 'e' except after 'c' at the ratio of 2.15 is plausible.
466 cases for and 217 cases against.
Overall the rules are implausible.
</pre>
 
=={{header|Wren}}==
Line 3,333 ⟶ 5,080:
 
Also there are seven words which fall into two categories and which have therefore been double-counted.
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
import "./pattern" for Pattern
import "./fmt" for Fmt
 
var yesNo = Fn.new { |b| (b) ? "yes" : "no" }
Line 3,384 ⟶ 5,131:
Fmt.print(" Plausible : $s", yesNo.call(plaus2))
 
Fmt.print("\nPlausible overall: $s", yesNo.call(plaus && plaus2))</langsyntaxhighlight>
 
{{out}}
Line 3,415 ⟶ 5,162:
And the code and results for the 'stretch goal' which has just the one double-counted word:
 
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
import "./pattern" for Pattern
import "./fmt" for Fmt
 
var yesNo = Fn.new { |b| (b) ? "yes" : "no" }
Line 3,472 ⟶ 5,219:
Fmt.print(" Plausible : $s", yesNo.call(plaus2))
 
Fmt.print("\nPlausible overall: $s", yesNo.call(plaus && plaus2))</langsyntaxhighlight>
 
{{out}}
Line 3,494 ⟶ 5,241:
Plausible overall: no
</pre>
 
=={{header|Yabasic}}==
{{trans|BASIC}}
<syntaxhighlight lang="freebasic">open "unixdict.txt" for reading as #1
 
repeat
line input #1 pal$
if instr(pal$, "ie") then
if instr(pal$, "cie") then CI = CI + 1 else XI = XI + 1 : fi
endif
if instr(pal$, "ei") then
if instr(pal$, "cei") then CE = CE + 1 else XE = XE + 1 : fi
endif
until eof(1)
close #1
 
print "CIE: ", CI
print "xIE: ", XI
print "CEI: ", CE
print "xEI: ", XE
print "\nI before E when not preceded by C: ";
if 2 * XI <= CI then print "not "; : fi
print "plausible."
print "E before I when preceded by C: ";
if 2 * CE <= XE then print "not "; : fi
print "plausible."
end</syntaxhighlight>
 
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn wcnt(wordList,altrs,aAdjust,bltrs,bAdjust,text){
a:=wordList.reduce('wrap(cnt,word){ cnt+word.holds(altrs) },0) - aAdjust;
b:=wordList.reduce('wrap(cnt,word){ cnt+word.holds(bltrs) },0) - bAdjust;
Line 3,504 ⟶ 5,279:
return(a,b,ratio);
}
wordList:=File("unixdict.txt").read();</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">a,b,r1:=wcnt(wordList,"cei",0,"cie",0,"E before I when preceded by C");
_,_,r2:=wcnt(wordList,"ie",b,"ei",a, "I before E when not preceded by C");
"Overall the rule is %splausible".fmt((r1<2 or r2<2) and "im" or "").println();</langsyntaxhighlight>
{{out}}
<pre>
Line 3,517 ⟶ 5,292:
</pre>
Stretch
<langsyntaxhighlight lang="zkl">fcn wc2(wordList,altrs,aAdjust,bltrs,bAdjust,text){
a,b:=wordList.reduce('wrap(cnts,line){
// don't care if line is "Word PoS Freq" or "as yet Adv 14"
Line 3,531 ⟶ 5,306:
return(a,b,ratio);
}
wordList:=File("1_2_all_freq.txt").read();</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits