I before E except after C: Difference between revisions
m
→{{header|Wren}}: Minor tidy
No edit summary |
m (→{{header|Wren}}: Minor tidy) |
||
(16 intermediate revisions by 12 users not shown) | |||
Line 36:
{{trans|Python}}
<
F plausibility_check(comment, x, y)
Line 66:
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)</
{{out}}
Line 88:
(Indeed, <code>unixdict.txt</code> is 206k.)
<
fcb1: equ 5Ch ; FCB 1 (populated by file on command line)
dma: equ 80h ; Standard DMA location
Line 294:
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</
{{out}}
Line 308:
=={{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.
<
# implements the plausibility test specified by the task #
Line 387:
show plausibility( "i before e in general", xie + cie, xei + cei );
show plausibility( "e before i in general", xei + cei, xie + cie )
FI</
{{out}}
<pre>
Line 407:
===Vanilla===
<
script o
property wordList : words of (read file ((path to desktop as text) & "www.rosettacode.org:unixdict.txt") as «class utf8»)
Line 447:
end ibeeac
ibeeac()</
{{output}}
<
===AppleScriptObjC===
<
use framework "Foundation"
use scripting additions
Line 483:
end ibeeac
ibeeac()</
{{output}}
<
===Functional===
<
use framework "Foundation"
use scripting additions
Line 736:
end tell
end if
end zipWith</
{{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}}==
<
WordList := RegExReplace(WordList, "i)cie", "", cieN)
WordList := RegExReplace(WordList, "i)cei", "", ceiN)
Line 763 ⟶ 805:
WebRequest.Send()
return, WebRequest.ResponseText
}</
{{out}}
<pre>"I before E when not preceded by C" is plausible.
Line 774 ⟶ 816:
=={{header|AWK}}==
<
/.ei/ {nei+=cnt($3)}
Line 799 ⟶ 841:
print "E before I when preceded by C: is"v2" plausible";
print "Overall rule is"v" plausible";
}</
Usage:
Line 821 ⟶ 863:
=={{header|Batch File}}==
Download first the text file, then put it on the same directory with this sample code:
<
::Batch File Implementation
Line 857 ⟶ 899:
pause
exit /b 0</
{{Out}}
<pre>Plausibility of "I before E when not preceded by C": TRUE (465 VS 213)
Line 867 ⟶ 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.
<
setlocal enableDelayedExpansion
for /f %%A in ('findstr /i "^ie [^c]ie" unixdict.txt ^| find /c /v ""') do set Atrue=%%A
Line 877 ⟶ 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%!</
{{Out}}
<pre>I before E when not preceded by C: True=465 False=213 : Plausible
Line 886 ⟶ 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.
<
setlocal enableDelayedExpansion
set /a Atrue=Afalse=Btrue=Bfalse=0
Line 897 ⟶ 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%!</
{{Out}}
<pre>I before E when not preceded by C: True=8192 False=4826 : Implausible
Line 904 ⟶ 946:
=={{header|BASIC}}==
<
20 OPEN "I",1,"UNIXDICT.TXT": GOTO 60
30 LINE INPUT #1,W$
Line 920 ⟶ 962:
150 PRINT "E before I when preceded by C: ";
160 IF 2*CE <= XE THEN PRINT "not ";
170 PRINT "plausible."</
{{out}}
<pre>CIE: 24
Line 933 ⟶ 975:
=={{header|BASIC256}}==
{{trans|BASIC}}
<
open 1, "unixdict.txt"
Line 958 ⟶ 1,000:
if 2 * CE <= XE then print "not ";
print "plausible."
end</
=={{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}}==
<
// Read word from selected input
Line 1,014 ⟶ 1,108:
writef("E before I when preceded by C: %Splausible.*N",
2*ncei > nxei -> "", "not ")
$)</
{{out}}
<pre>CIE: 24
Line 1,028 ⟶ 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">
%{
/*
Line 1,061 ⟶ 1,155:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
{{trans|Java}}
<
using System.Collections.Generic;
using System.IO;
Line 1,119 ⟶ 1,213:
}
}
}</
{{out}}
<pre>Plausible count: 384
Line 1,132 ⟶ 1,226:
:* (Test used 4.4, so only a limited number of C++11 features were used.)
<
#include <fstream>
#include <string>
Line 1,233 ⟶ 1,327:
return 0;
}
</syntaxhighlight>
{{out}}
Line 1,248 ⟶ 1,342:
The output here was generated with the files as of 21st June 2016.
<
(ns i-before-e.core
(:require [clojure.string :as s])
Line 1,302 ⟶ 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>
{{out}}
Line 1,322 ⟶ 1,416:
=={{header|CLU}}==
<
rep = record[cie, xie, cei, xei, words: int]
Line 1,394 ⟶ 1,488:
stream$close(fstream)
stream$puts(po, report$results(r))
end start_up </
{{out}}
<pre>Amount of words: 25104
Line 1,412 ⟶ 1,506:
Now we can do the task:
<
for word of dict.toLowerCase!.match /\S+/g
++ie-npc if /(^|[^c])ie/.test word
Line 1,424 ⟶ 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'</
=={{header|Common Lisp}}==
<
(defun test-rule (rule-name examples counter-examples)
(let ((plausible (if (> examples (* 2 counter-examples)) 'plausible 'not-plausible)))
Line 1,463 ⟶ 1,557:
(plausibility "Dictionary" #p"unixdict.txt" #'parse-dict)
(plausibility "Word frequencies (stretch goal)" #p"1_2_all_freq.txt" #'parse-freq)
</syntaxhighlight>
{{out}}
Line 1,481 ⟶ 1,575:
=={{header|D}}==
The extra work has not been attempted
<
import std.stdio;
Line 1,604 ⟶ 1,698:
}
return cnt;
}</
{{out}}
Line 1,616 ⟶ 1,710:
{{libheader| System.IOUtils}}
{{Trans|C sharp}}
<syntaxhighlight lang="delphi">
program I_before_E_except_after_C;
Line 1,676 ⟶ 1,770:
Writeln('Rule is not plausible.');
end.</
=={{header|Draco}}==
<
/* variables to hold totals for each possibility */
Line 1,737 ⟶ 1,831:
if p then "" else "not " fi,
"plausible.")
corp</
{{out}}
<pre>CIE: 24
Line 1,749 ⟶ 1,843:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def task(path) do
plausibility_ratio = 2
Line 1,777 ⟶ 1,871:
path = hd(System.argv)
IO.inspect RC.task(path)</
{{out}}
Line 1,790 ⟶ 1,884:
=={{header|Erlang}}==
<
-module(cei).
-export([plaus/0,count/3]).
Line 1,815 ⟶ 1,909:
nomatch -> count(T,Pattern, Acc)
end.
</syntaxhighlight>
{{output}}
<pre>
Line 1,825 ⟶ 1,919:
=={{header|Factor}}==
<
io.files kernel literals math prettyprint regexp sequences ;
IN: rosetta-code.i-before-e
Line 1,847 ⟶ 1,941:
"I before E when not preceded by C"
"E before I when preceded by C" [ output ] bi@</
{{out}}
<pre>
Line 1,859 ⟶ 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">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sat May 18 22:19:19
Line 1,931 ⟶ 2,025:
end function plausibility
end program cia
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Dim As Integer F = Freefile
Dim As String text,intext
Line 1,983 ⟶ 2,077:
print "So, the idea is not plausible."
Sleep</
{{out}}
<pre>The number of words in unixdict.txt 25104
Line 1,999 ⟶ 2,093:
=={{header|FutureBasic}}==
<
#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
void local fn CheckWord( wrd as CFStringRef, txt as CFStringRef, c as ^long, x as ^long )
end fn
void local fn Doit
end fn
fn DoIt
HandleEvents</
{{output}}
Line 2,065 ⟶ 2,159:
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}}==
<
import (
Line 2,135 ⟶ 2,228:
}
return false
}</
{{out}}
Line 2,149 ⟶ 2,242:
This solution does not attempt the stretch goal.
<
import Text.Regex.TDFA
import Text.Printf
Line 2,173 ⟶ 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")</
{{out}}
Line 2,194 ⟶ 2,287:
same input line should all be tested.
<
procedure main(a)
Line 2,212 ⟶ 2,305:
if \showCounts then every write(phrase := !phrases,": ",totals[phrase])
end</
{{out}} of running with <tt>--showcounts</tt> flag:
Line 2,229 ⟶ 2,322:
=== stretch goal ===
<
procedure main(a)
Line 2,253 ⟶ 2,346:
if \showCounts then every write(phrase := !phrases,": ",totals[phrase])
end</
{{out}}
Line 2,272 ⟶ 2,365:
After downloading unixdict to /tmp:
<
Investigating the rules:
<
24
+/'cei' E. dict
Line 2,283 ⟶ 2,376:
490
+/'ei' E. dict
230</
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 2,293 ⟶ 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:
<
words=: >0 { allfreq
freqs=: 0 {.@".&>2 { allfreq</
With these definitions, we can define a prevalence verb which will tell us how often a particular substring is appears in use:
<
(y +./@E."1 words) +/ .* freqs
)</
Investigating our original proposed rules:
<
1.76868</
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.
<
0.328974</
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:
<
1.68255</
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.
<
import java.io.BufferedReader;
import java.io.FileReader;
Line 2,383 ⟶ 2,522:
}
}
</syntaxhighlight>
{{out}}
Line 2,394 ⟶ 2,533:
WARNING: The problem statement is misleading as the rule only applies to syllables that rhyme with "see".
<
# scan/2 produces a stream of matches but the first match of a segment (e.g. cie)
Line 2,428 ⟶ 2,567:
as ratio = \($x)/\($y) ~ \($ratio * 100 |round)%" ;
"Using the problematic criterion specified in the task requirements:", assess</
{{out}}
Using http://www.puzzlers.org/pub/wordlists/unixdict.txt as of June 2015:
<
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%</
=={{header|Julia}}==
<
open("unixdict.txt") do txtfile
Line 2,466 ⟶ 2,605:
print("Plausibility of \"E before I when preceded by C\":")
println(rule2 > 2 * notrule2 ? "PLAUSIBLE" : "UNPLAUSIBLE")
end</
{{out}}
Line 2,473 ⟶ 2,612:
=={{header|Kotlin}}==
<
import java.net.URL
Line 2,533 ⟶ 2,672:
println()
printResults("British National Corpus", counts2)
}</
{{out}}
Line 2,565 ⟶ 2,704:
=={{header|Lasso}}==
<
local(cie,cei,ie,ei) = (:0,0,0,0)
Line 2,599 ⟶ 2,738:
)
stdoutnl(`Overall the rule is ` + (#ie_plausible and #cei_plausible ? `` | `NOT-`) + `PLAUSIBLE`)
</syntaxhighlight>
{{out}}
<pre>
Line 2,608 ⟶ 2,747:
=={{header|Lua}}==
<
local http = require("socket.http")
Line 2,639 ⟶ 2,778:
io.write("Overall the phrase is ")
if not (sub1 and sub2) then io.write("not ") end
print("plausible.")</
{{out}}
<pre>I before E when not preceded by C: PLAUSIBLE
Line 2,646 ⟶ 2,785:
=={{header|Maple}}==
<
lst := StringTools:-Split(words[2],"\n"):
xie, cie, cei, xei := 0, 0, 0, 0:
Line 2,668 ⟶ 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")):</
{{Out|Output}}
<pre>The first phrase is plausible with supporting features 465 and anti features 213
Line 2,675 ⟶ 2,814:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt",
"Words"];
Line 2,701 ⟶ 2,840:
ToString[N[cei/cie]]]
Print["Overall the rule is " <>
If[test1 && test2, "PLAUSIBLE", "NOT PLAUSIBLE" ]]</
{{out}}
<
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 2,710 ⟶ 2,849:
There were 13 examples and 24 counter examples, for a ratio of 0.541667
Overall the rule is NOT PLAUSIBLE
</syntaxhighlight>
=={{header|MATLAB
<syntaxhighlight lang="matlab">
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)
fprintf('For %s:\n', URL)
[~, 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)
if includesFrequencyData
fields = split(strtrim(lines(i)));
if length(fields) ~= 3 || i == 1
continue;
end
word = fields(1);
frequency = str2double(fields(3));
else
word = lines(i);
frequency = 1;
end
ei = ei + length(strfind(word,'ei')) * frequency;
cie = cie + length(strfind(word,'cie')) * frequency;
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)
fprintf('\"%s\" is ', claim);
if positive <= 2*negative
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 )
end
</syntaxhighlight>
<pre>
>> iBeforeE
For http://wiki.puzzlers.org/pub/wordlists/unixdict.txt:
"I before E when not preceded by C" is PLAUSIBLE,
since the ratio of positive to negative examples is 466/217 = 2.15.
since the ratio of positive to negative examples is 13/24 = 0.54.
Hence the combined rule "I before E, except after C" is NOT PLAUSIBLE.
For http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt:
"I before E when not preceded by C" is NOT PLAUSIBLE,
since the ratio of positive to negative examples is 8207/4826 = 1.70.
since the ratio of positive to negative examples is 327/994 = 0.33.
Hence the combined rule "I before E, except after C" is NOT PLAUSIBLE.
</pre>
=={{header|Modula-2}}==
<
IMPORT SeqIO;
IMPORT Texts;
Line 2,860 ⟶ 3,030:
WriteString("plausible.");
WriteLn;
END IEC.</
{{out}}
<pre>Amount of words: 50209
Line 2,873 ⟶ 3,043:
=={{header|Nim}}==
<
const
Line 2,906 ⟶ 3,076:
let p1 = plausibility(Rule1, nie, nei)
let p2 = plausibility(Rule2, cei, cie)
echo &"So the phrase {Phrase} is {PlausibilityText[p1 and p2]}."</
{{out}}
Line 2,915 ⟶ 3,085:
=={{header|Objeck}}==
{{trans|Seed7}}
<
use HTTP;
use Collection;
Line 2,977 ⟶ 3,147:
}
}
</syntaxhighlight>
{{out}}
Line 2,989 ⟶ 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}}==
<
use warnings;
use strict;
Line 3,024 ⟶ 3,246:
$result += result($support, $against);
print 'Overall: ', 'NOT ' x ($result < 2), "PLAUSIBLE.\n";</
{{out}}
Line 3,033 ⟶ 3,255:
===Perl: Stretch Goal===
Just replace the while loop with the following one:
<
my @columns = split;
next if 3 < @columns;
Line 3,040 ⟶ 3,262:
$count{$k} += $freq if -1 != index $word, $k;
}
}</
{{out}}
<pre>I before E when not preceded by C: 8148 / 4826 = 1.69. NOT PLAUSIBLE
Line 3,048 ⟶ 3,270:
=={{header|Phix}}==
Kept dirt simple, difficult to imagine any other approach being faster than this.
<!--<
<span style="color: #000080;font-style:italic;">-- demo\rosetta\IbeforeE.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 3,086 ⟶ 3,308:
<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>
<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>
<!--</
{{out}}
Although the output matches, I decided to use different metrics from ALGOL 68 for the middle two conclusions.<br>
Line 3,102 ⟶ 3,324:
=={{header|Picat}}==
<
Words = read_file_lines("unixdict.txt"),
IEWords = [Word : Word in Words, find(Word,"ie",_,_)],
Line 3,132 ⟶ 3,354:
False := [Word|False]
end
end.</
{{out}}
Line 3,142 ⟶ 3,364:
=={{header|PicoLisp}}==
<
(let
(Cie (let N 0 (in File (while (from "cie") (run Prg))))
Line 3,172 ⟶ 3,394:
(ibEeaC "1_2_all_freq.txt"
(inc 'N (format (stem (line) "\t"))) )</
Output:
<pre>cie: 24
Line 3,191 ⟶ 3,413:
=={{header|PL/I}}==
<
declare dict file;
open file(dict) title('unixdict.txt');
Line 3,239 ⟶ 3,461:
if ^(ieNotC & eiC) then put list('not');
put list('plausible.');
end iBeforeE;</
{{out}}
<pre>CIE: 24
Line 3,250 ⟶ 3,472:
=={{header|PowerShell}}==
<
$Words = $web.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt')
Line 3,278 ⟶ 3,500:
if ($Clause1 -and $Clause2)
{$MainClause = $True}
"The plausibility of the phrase 'I before E except after C' is $MainClause"</
{{out}}
<pre>
Line 3,287 ⟶ 3,509:
==={{header|Alternative Implementation}}===
<
$Words = $web.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt')
Line 3,315 ⟶ 3,537:
if ($Clause1 -and $Clause2)
{$MainClause = $True}
"The plausibility of the phrase 'I before E except after C' is $MainClause"</
{{out}}
<pre>
Line 3,324 ⟶ 3,546:
==={{header|Alternative Implementation 2}}===
A single pass through the wordlist using the regex engine.
<
$cie, $cei, $_ie, $_ei = 0, 0, 0, 0
Line 3,337 ⟶ 3,559:
"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))"</
{{out}}
<pre>
Line 3,346 ⟶ 3,568:
=={{header|PureBasic}}==
<
While Not Eof(1)
wl$+ReadString(1)+";"
Line 3,368 ⟶ 3,590:
Print("Overall the rule is : ")
If cei>cie And ie>ei : PrintN("PLAUSIBLE") : Else : PrintN("NOT PLAUSIBLE") : EndIf
Input()</
{{out}}
<pre>
Line 3,384 ⟶ 3,606:
=={{header|Python}}==
<
import re
Line 3,420 ⟶ 3,642:
print('Checking plausibility of "I before E except after C":')
print_result(*simple_stats())</
{{out}}
Line 3,436 ⟶ 3,658:
===Python: Stretch Goal===
Add the following to the bottom of the previous program:
<
freq = [line.strip().lower().split()
for line in urllib.request.urlopen(url)
Line 3,451 ⟶ 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())</
{{out|Produces this extra output}}
Line 3,469 ⟶ 3,691:
=={{header|QBasic}}==
{{trans|BASIC}}
<
DIM W AS STRING
CLS
Line 3,490 ⟶ 3,712:
PRINT "E before I when preceded by C: ";
IF 2 * CE <= XE THEN PRINT "not ";
PRINT "plausible."</
=={{header|R}}==
<
ie.npc = sum(grepl("(?<!c)ie", words, perl = T))
ei.npc = sum(grepl("(?<!c)ei", words, perl = T))
Line 3,504 ⟶ 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.")</
{{out}}
Line 3,512 ⟶ 3,734:
=={{header|Racket}}==
<
(define (get-tallies filename line-parser . patterns)
Line 3,543 ⟶ 3,765:
(plausibility "Dictionary" "unixdict.txt" (λ (line) (list line 1))) (newline)
(plausibility "Word frequencies (stretch goal)" "1_2_all_freq.txt" parse-frequency-data)</
{{out}}
Line 3,563 ⟶ 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"
token TOP {
[^^ <word> $$ \n?]+
Line 3,630 ⟶ 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";</
{{out}}
Line 3,653 ⟶ 3,875:
This solution requires just a few modifications to the grammar and actions from the non-stretch goal.
<syntaxhighlight lang="raku"
token TOP {
^^ \t Word \t PoS \t Freq $$ \n
Line 3,718 ⟶ 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";</
{{out}}
Line 3,728 ⟶ 3,950:
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".
<
testlist: function [wordlist /wfreq] [
Line 3,760 ⟶ 3,982:
keep seq/1 keep to-integer seq/3
]]]
testlist/wfreq bnclist</
{{out}}
Line 3,785 ⟶ 4,007:
===unweighted version===
<
/*───────────────────────────────────── "E before I" when preceded by C. */
parse arg iFID . /*obtain optional argument from the CL.*/
Line 3,820 ⟶ 4,042:
else #.x.z=#.x.z + 1
s=_ + 1 /*handle the cases of multiple finds. */
end /*forever*/</
{{out|output|text= when using the default dictionary:}}
<pre>
Line 3,856 ⟶ 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.
<
/*───────────────────────────────────── "E before I" when preceded by C, using a */
/*───────────────────────────────────── weighted frequency for each word. */
Line 3,916 ⟶ 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. */</
{{out|output|text= when using the default dictionary and default word frequency list:}}
<pre>
Line 3,937 ⟶ 4,159:
=={{header|Ring}}==
<
# Project : I before E except after C
Line 3,977 ⟶ 4,199:
end
return sum
</syntaxhighlight>
Output:
<pre>
Line 3,991 ⟶ 4,213:
=={{header|Ruby}}==
<
plausibility_ratio = 2
Line 4,010 ⟶ 4,232:
puts "Overall: #{overall_plausible ? 'Plausible' : 'Implausible'}."
</syntaxhighlight>
{{out}}
<pre>
Line 4,021 ⟶ 4,243:
=={{header|Rust}}==
<
use std::ops::AddAssign;
Line 4,100 ⟶ 4,322:
);
}
</syntaxhighlight>
<pre>
Counting Feature {
Line 4,114 ⟶ 4,336:
=={{header|Scala}}==
<
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 4,136 ⟶ 4,358:
println("E before I when preceded by C: "+plausibility(countsCEI))
println("Overall: "+plausibility(plausible(countsIE) && plausible(countsCEI)))
}</
{{out}}
<pre>I before E when not preceded by C: plausible
Line 4,143 ⟶ 4,365:
=={{header|Seed7}}==
<
include "gethttp.s7i";
include "float.s7i";
Line 4,201 ⟶ 4,423:
writeln("(To be plausible, one word count must exceed another by " <& PLAUSIBILITY_RATIO <& " times)");
end if;
end func;</
{{out}}
Line 4,213 ⟶ 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.
<
let request = NSURLRequest(URL: NSURL(string: "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")!)
Line 4,270 ⟶ 4,533:
}
CFRunLoopRun()</
{{out}}
<pre>
Line 4,276 ⟶ 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}}
<
IF END #f THEN LET EOF = -1 ELSE LET EOF = 0
END DEF
Line 4,308 ⟶ 4,570:
IF 2*ce <= xe THEN PRINT "not ";
PRINT "plausible."
END</
=={{header|Tcl}}==
{{trans|Python}}<!-- very approximately, mainly for the messages -->
<
variable PLAUSIBILITY_RATIO 2.0
Line 4,353 ⟶ 4,615:
}
puts "\n(To be plausible, one word count must exceed another by\
$PLAUSIBILITY_RATIO times)"</
{{out}}
<!-- note that checking the pronunciation of the words indicates a key guard on the real rule that isn't normally stated -->
Line 4,371 ⟶ 4,633:
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT,{}
words=REQUEST("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
Line 4,434 ⟶ 4,696:
TRAcE *check1,check2,checkall
</syntaxhighlight>
Output:
<pre>
Line 4,447 ⟶ 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}}==
<
matched() {
Line 4,476 ⟶ 4,778:
echo "Overall, the rule is not plausible"
fi
</syntaxhighlight>
{{out}}
<pre>
Line 4,486 ⟶ 4,788:
=={{header|VBScript}}==
The sample text was downloaded and saved in the same folder as the script.
<syntaxhighlight lang="vb">
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
Line 4,535 ⟶ 4,837:
srcFile.Close
Set objFSO = Nothing
</syntaxhighlight>
{{Out}}
Line 4,552 ⟶ 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.
<
Option Explicit On
Option Infer On
Line 4,687 ⟶ 4,989:
End Sub
End Module
</syntaxhighlight>
{{out|case=Loop implementation}}
Line 4,731 ⟶ 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 4,738 ⟶ 5,080:
Also there are seven words which fall into two categories and which have therefore been double-counted.
<
import "./pattern" for Pattern
import "./fmt" for Fmt
var yesNo = Fn.new { |b| (b) ? "yes" : "no" }
Line 4,789 ⟶ 5,131:
Fmt.print(" Plausible : $s", yesNo.call(plaus2))
Fmt.print("\nPlausible overall: $s", yesNo.call(plaus && plaus2))</
{{out}}
Line 4,820 ⟶ 5,162:
And the code and results for the 'stretch goal' which has just the one double-counted word:
<
import "./pattern" for Pattern
import "./fmt" for Fmt
var yesNo = Fn.new { |b| (b) ? "yes" : "no" }
Line 4,877 ⟶ 5,219:
Fmt.print(" Plausible : $s", yesNo.call(plaus2))
Fmt.print("\nPlausible overall: $s", yesNo.call(plaus && plaus2))</
{{out}}
Line 4,899 ⟶ 5,241:
Plausible overall: no
</pre>
=={{header|Yabasic}}==
{{trans|BASIC}}
<
repeat
Line 4,926 ⟶ 5,267:
if 2 * CE <= XE then print "not "; : fi
print "plausible."
end</
=={{header|zkl}}==
<
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 4,938 ⟶ 5,279:
return(a,b,ratio);
}
wordList:=File("unixdict.txt").read();</
<
_,_,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();</
{{out}}
<pre>
Line 4,951 ⟶ 5,292:
</pre>
Stretch
<
a,b:=wordList.reduce('wrap(cnts,line){
// don't care if line is "Word PoS Freq" or "as yet Adv 14"
Line 4,965 ⟶ 5,306:
return(a,b,ratio);
}
wordList:=File("1_2_all_freq.txt").read();</
{{out}}
<pre>
|