Change e letters to i in words: Difference between revisions

add SETL
m (→‎{{header|Python}}: Simplified an expression.)
(add SETL)
 
(42 intermediate revisions by 16 users not shown)
Line 1:
{{Draft task}}
 
;Task:
Use the dictionary   [https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt]
Line 13 ⟶ 12:
{{Template:Strings}}
<br><br>
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">V words = File(‘unixdict.txt’).read().split("\n")
V words_set = Set(words)
 
L(word) words
I word.len > 5
V new_word = word.replace(‘e’, ‘i’)
I new_word != word & new_word C words_set
print(word‘ -> ’new_word)</syntaxhighlight>
 
{{out}}
<pre>
analyses -> analysis
atlantes -> atlantis
bellow -> billow
breton -> briton
clench -> clinch
convect -> convict
crises -> crisis
diagnoses -> diagnosis
enfant -> infant
enquiry -> inquiry
frances -> francis
galatea -> galatia
harden -> hardin
heckman -> hickman
inequity -> iniquity
inflect -> inflict
jacobean -> jacobian
marten -> martin
module -> moduli
pegging -> pigging
psychoses -> psychosis
rabbet -> rabbit
sterling -> stirling
synopses -> synopsis
vector -> victor
welles -> willis
</pre>
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_Io;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
Line 55 ⟶ 94:
end;
end loop;
end Change_E_To_I;</langsyntaxhighlight>
{{out}}
<pre>analyses -> analysis
Line 83 ⟶ 122:
vector -> victor
welles -> willis</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># find words where replacing "e" with "i" results in another word #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
Line 142 ⟶ 180:
e := NEXT words
OD
FI</langsyntaxhighlight>
{{out}}
Note, the associative array is not traversed in lexicographical order, the output here has been sorted for ease of comparison with other samples.
Line 173 ⟶ 211:
welles -> willis
</pre>
 
=={{header|AppleScript}}==
===Core language only===
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later.
Because of the huge size of the original word list and the number of changed words to check, it's nearly 100 times as fast to ensure the list is sorted and to use a binary search handler as it is to use the language's built-in '''is in''' command! (1.17 seconds instead of 110 on my current machine.) A further, lesser but interesting optimisation is to work through the sorted list in reverse, storing possible "i" word candidates encountered before getting to any "e" words from which they can be derived. Changed "e" words then only need to be checked against this smaller collection.
use sorter : script "Insertion sort" -- <https://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#AppleScript>
 
<lang applescript>use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later.
use sorter : script "Custom Iterative Ternary Merge Sort" -- <https://macscripter.net/viewtopic.php?pid=194430#p194430>
use scripting additions
 
Line 189 ⟶ 224:
repeat until (l = r)
set m to (l + r) div 2
if (item m of o's lst's item m < v) then
set l to m + 1
else
Line 196 ⟶ 231:
end repeat
if (item l of o's lst's item l is= v) then return l
return 0
end binarySearch
 
on replace(a, b, txt)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to a
set txt to txt's text items
set AppleScript's text item delimiters to b
set txt to txt as text
set AppleScript's text item delimiters to astid
return txt
end replace
 
on task(minWordLength)
Line 209 ⟶ 254:
set wordCount to (count o's wordList)
ignoring case
tell sorter to sort(o's wordList, 1, wordCount, {}) -- Not actually needed with unixdict.txt.
tell sorter to sort(o's wordList, 1, wordCount) -- Not actually needed with unixdict.txt.
set iWordCount to 0
set iWordCount to 0
set astid to AppleScript's text item delimiters
repeat with i from wordCount to 1 by -1
set thisWord to item iset ofthisWord to o's wordList's item i
if ((count thisWord) < minWordLength) then
else if ((thisWord contains "e") and (iWordCount > 0)) then
set AppleScript's text item delimitersset changedWord to replace("e", "i", thisWord)
set tis to thisWord if (binarySearch(changedWord, o's textiWords, 1, iWordCount) > 0) itemsthen
set AppleScriptbeginning of o's text item delimitersoutput to "i"{thisWord, changedWord}
set changedWord to tis asend textif
else if (binarySearch(changedWord, o's iWords, 1, iWordCount)thisWord >contains 0"i") then
set beginning of o's outputiWords to {thisWord, changedWord}
set iWordCount to iWordCount + 1
end if
elseend if (thisWord contains "i") thenrepeat
end ignoring
set beginning of o's iWords to thisWord
set iWordCount to iWordCount + 1
end if
end repeat
set AppleScript's text item delimiters to astid
return o's output
end task
 
task(6)</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{{"analyses", "analysis"}, {"atlantes", "atlantis"}, {"bellow", "billow"}, {"breton", "briton"}, {"clench", "clinch"}, {"convect", "convict"}, {"crises", "crisis"}, {"diagnoses", "diagnosis"}, {"enfant", "infant"}, {"enquiry", "inquiry"}, {"frances", "francis"}, {"galatea", "galatia"}, {"harden", "hardin"}, {"heckman", "hickman"}, {"inequity", "iniquity"}, {"inflect", "inflict"}, {"jacobean", "jacobian"}, {"marten", "martin"}, {"module", "moduli"}, {"pegging", "pigging"}, {"psychoses", "psychosis"}, {"rabbet", "rabbit"}, {"sterling", "stirling"}, {"synopses", "synopsis"}, {"vector", "victor"}, {"welles", "willis"}}</langsyntaxhighlight>
 
===AppleScriptObjC===
The Foundation framework has very fast array filters, but reducing the checklist size and checking with the same binary search handler as above are also effective. This version takes about 0.37 seconds. As above, the case-sensitivity and sorting arrangements are superfluous with unixdict.txt, but are included for interest. Same result.
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
Line 304 ⟶ 346:
end task
 
task(6)</langsyntaxhighlight>
 
===Functional===
Assuming a local copy of unixdict.txt (on the macOS Desktop),
 
using the Foundation libraries,
 
and defining the list of twins as an intersection of sets.
 
<syntaxhighlight lang="applescript">use framework "Foundation"
 
 
----- DICTIONARY WORDS TWINNED BY (E -> I) REPLACEMENT ---
 
-- ieTwins :: String -> [(String, String)]
on ieTwins(s)
-- Pairs of dictionary words in s which
-- are twinned by (e -> i) replacement
set ca to current application
set longWords to filteredLines("5 < length", s)
set eWords to longWords's ¬
filteredArrayUsingPredicate:(containsString("e"))
set lexicon to ca's NSSet's ¬
setWithArray:(longWords's ¬
filteredArrayUsingPredicate:(containsString("i")))
set possibles to (allReplaced("e", "i", ¬
(eWords's componentsJoinedByString:(linefeed))))'s ¬
componentsSeparatedByString:(linefeed)
set possibleSet to ca's NSMutableSet's setWithArray:(possibles)
possibleSet's intersectSet:(lexicon)
-- Dictionary of possible words and their sources
set dict to dictFromZip(possibles, eWords)
-- Listing of candidate words which are found in the dictionary
-- (twinned with their sources)
script pair
on |λ|(k)
{(dict's objectForKey:(k)) as string, k}
end |λ|
end script
map(pair, ((possibleSet's allObjects())'s ¬
sortedArrayUsingSelector:"compare:") as list)
end ieTwins
 
 
--------------------------- TEST -------------------------
on run
script go
on |λ|(ei)
set {e, i} to ei
i & " <- " & e
end |λ|
end script
unlines(map(go, ¬
ieTwins(readFile("~/Desktop/unixdict.txt"))))
end run
 
 
------------------------- GENERIC ------------------------
 
-- allRplaced :: String -> String -> NSString -> NSString
on allReplaced(needle, replacement, haystack)
haystack's stringByReplacingOccurrencesOfString:(needle) ¬
withString:(replacement)
end allReplaced
 
 
-- containsString :: String -> NSPredicate
on containsString(s)
tell current application
its (NSPredicate's ¬
predicateWithFormat:("self contains '" & s & "'"))
end tell
end containsString
 
 
-- dictFromZip :: NSArray -> NSArray -> NSDictionary
on dictFromZip(ks, vs)
tell current application
its (NSDictionary's ¬
dictionaryWithObjects:vs forKeys:ks)
end tell
end dictFromZip
 
 
-- filteredLines :: String -> NSString -> [a]
on filteredLines(predicateString, s)
-- A list of lines filtered by an NSPredicate string
tell current application
set predicate to its (NSPredicate's ¬
predicateWithFormat:predicateString)
set array to its (NSArray's ¬
arrayWithArray:(s's componentsSeparatedByString:(linefeed)))
end tell
(array's filteredArrayUsingPredicate:(predicate))
end filteredLines
 
 
-- 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
 
 
-- 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
 
 
-- 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</syntaxhighlight>
{{Out}}
<pre>analysis <- analyses
atlantis <- atlantes
billow <- bellow
briton <- breton
clinch <- clench
convict <- convect
crisis <- crises
diagnosis <- diagnoses
francis <- frances
galatia <- galatea
hardin <- harden
hickman <- heckman
infant <- enfant
inflict <- inflect
iniquity <- inequity
inquiry <- enquiry
jacobian <- jacobean
martin <- marten
moduli <- module
pigging <- pegging
psychosis <- psychoses
rabbit <- rabbet
stirling <- sterling
synopsis <- synopses
victor <- vector
willis <- welles</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">words: map read.lines relative "unixdict.txt" => strip
 
loop words 'word [
sw: new size word
if 6 > size word ->
continue
 
iw: replace word "e" "i"
if and? [contains? word "e"][contains? words iw] ->
print [word "=>" iw]
]</syntaxhighlight>
 
{{out}}
 
<pre>analyses => analysis
atlantes => atlantis
bellow => billow
breton => briton
clench => clinch
convect => convict
crises => crisis
diagnoses => diagnosis
enfant => infant
enquiry => inquiry
frances => francis
galatea => galatia
harden => hardin
heckman => hickman
inequity => iniquity
inflect => inflict
jacobean => jacobian
marten => martin
module => moduli
pegging => pigging
psychoses => psychosis
rabbet => rabbit
sterling => stirling
synopses => synopsis
vector => victor
welles => willis</pre>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">FileRead, db, % A_Desktop "\unixdict.txt"
oWord := []
for i, word in StrSplit(db, "`n", "`r")
if (StrLen(word) > 5)
oWord[word] := true
 
for word in oWord
if InStr(word, "e") && oWord[StrReplace(word, "e", "i")]
result .= word . (StrLen(word) > 8 ? "`t" : "`t`t") . ": " StrReplace(word, "e", "i") "`n"
 
MsgBox, 262144, , % result</syntaxhighlight>
{{out}}
<pre>analyses : analysis
atlantes : atlantis
bellow : billow
breton : briton
clench : clinch
convect : convict
crises : crisis
diagnoses : diagnosis
enfant : infant
enquiry : inquiry
frances : francis
galatea : galatia
harden : hardin
heckman : hickman
inequity : iniquity
inflect : inflict
jacobean : jacobian
marten : martin
module : moduli
pegging : pigging
psychoses : psychosis
rabbet : rabbit
sterling : stirling
synopses : synopsis
vector : victor
welles : willis</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f CHANGE_E_LETTERS_TO_I_IN_WORDS.AWK unixdict.txt
#
Line 334 ⟶ 645:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 364 ⟶ 675:
welles willis
</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
Line 466 ⟶ 776:
free_dictionary(dictionary, size);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 497 ⟶ 807:
26. welles -> willis
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <cstdlib>
#include <fstream>
Line 535 ⟶ 844:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 566 ⟶ 875:
26. welles -> willis
</pre>
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Classes}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Change_e_letters_to_i_in_words;
 
Line 610 ⟶ 918:
 
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>analyses ──► analysis
Line 638 ⟶ 946:
vector ──► victor
welles ──► willis</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Change 'e' to 'i' in words. Nigel Galloway: February 18th., 2021
let g=[|use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()|]|>Array.filter(fun n->n.Length>5)
let fN g=(g,(Seq.map(fun n->if n='e' then 'i' else n)>>Array.ofSeq>>System.String)g)
g|>Array.filter(Seq.contains 'e')|>Array.map fN|>Array.filter(fun(_,n)-> Array.contains n g)|>Array.iter(fun(n,g)->printfn "%s -> %s" n g)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 676 ⟶ 983:
</pre>
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs binary-search formatting io.encodings.ascii
io.files kernel literals math sequences splitting ;
 
Line 686 ⟶ 993:
[ dup "e" "i" replace ] map>alist
[ nip words sorted-member? ] assoc-filter ! binary search
[ "%-9s -> %s\n" printf ] assoc-each</langsyntaxhighlight>
{{out}}
<pre>
Line 716 ⟶ 1,023:
welles -> willis
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#define NULL 0
 
type node
Line 778 ⟶ 1,084:
end if
curr = curr->nxt
wend</langsyntaxhighlight>
{{out}}<pre>
analyses analysis
Line 806 ⟶ 1,112:
vector victor
welles willis</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
 
void local fn DoIt
CFURLRef url
CFStringRef string, wd
ErrorRef err = NULL
CFArrayRef array
CFMutableArrayRef mutArray
url = fn URLWithString( @"https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt" )
string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, @err )
if ( string )
array = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet )
mutArray = fn MutableArrayWithCapacity(0)
for wd in array
if ( len(wd) > 5 and fn StringContainsString( wd, @"e" ) )
wd = fn StringByReplacingOccurrencesOfString( wd, @"e", @"i" )
if ( fn ArrayContainsObject( array, wd ) )
MutableArrayAddObject( mutArray, wd )
end if
end if
next
string = fn ArrayComponentsJoinedByString( mutArray, @"\n" )
NSLog(@"%@",string)
else
NSLog(@"%@",err)
end if
end fn
 
fn DoIt
 
HandleEvents</syntaxhighlight>
 
{{out}}
<pre>
analysis
atlantis
billow
briton
clinch
convict
crisis
diagnosis
infant
inquiry
francis
galatia
hardin
hickman
iniquity
inflict
jacobian
martin
moduli
pigging
psychosis
rabbit
stirling
synopsis
victor
willis
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 846 ⟶ 1,221:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 877 ⟶ 1,252:
26: welles -> willis
</pre>
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import qualified Data.Set as S
 
------ DICTIONARY WORDS TWINNED BY e -> i REPLACEMENT ----
 
ieTwins :: String -> [(String, String)]
ieTwins s =
[ (w, twin)
| w <- filter ('e' `elem`) longWords,
let twin = iForE w,
S.member twin lexicon
]
where
longWords = filter ((5 <) . length) (lines s)
lexicon = S.fromList $ filter ('i' `elem`) longWords
 
iForE :: String -> String
iForE [] = []
iForE ('e' : cs) = 'i' : iForE cs
iForE (c : cs) = c : iForE cs
 
--------------------------- TEST -------------------------
main :: IO ()
main =
readFile "unixdict.txt"
>>= (mapM_ print . ieTwins)</syntaxhighlight>
{{Out}}
<pre>("analyses","analysis")
("atlantes","atlantis")
("bellow","billow")
("breton","briton")
("clench","clinch")
("convect","convict")
("crises","crisis")
("diagnoses","diagnosis")
("enfant","infant")
("enquiry","inquiry")
("frances","francis")
("galatea","galatia")
("harden","hardin")
("heckman","hickman")
("inequity","iniquity")
("inflect","inflict")
("jacobean","jacobian")
("marten","martin")
("module","moduli")
("pegging","pigging")
("psychoses","psychosis")
("rabbet","rabbit")
("sterling","stirling")
("synopses","synopsis")
("vector","victor")
("welles","willis")</pre>
=={{header|J}}==
<syntaxhighlight lang="j"> >(([-.-.)rplc&'ei'&.>@(#~ ('e'&e. * 5<#)@>)) cutLF fread 'unixdict.txt'
analysis
atlantis
billow
briton
clinch
convict
crisis
diagnosis
francis
galatia
hardin
hickman
infant
inflict
iniquity
inquiry
jacobian
martin
moduli
pigging
psychosis
rabbit
stirling
synopsis
victor
willis</syntaxhighlight>
=={{header|JavaScript}}==
{{Works with| macOS}}
 
ECMAScript defines no file access interface.
 
Here we use the ObjC interface of macOS ''JavaScript for Automation'' to define a '''readFile''' function.
 
<syntaxhighlight lang="javascript">(() => {
"use strict";
// ieTwins :: String -> [(String, String)]
const ieTwins = s => {
const
longWords = s.split("\n")
.filter(x => 5 < x.length),
lexicon = new Set(
longWords.filter(w => w.includes("i"))
),
rgx = /e/gu;
return longWords.flatMap(
w => w.includes("e") ? (() => {
const x = w.replace(rgx, "i");
return lexicon.has(x) ? [
[w, x]
] : [];
})() : []
);
};
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
const s = readFile("unixdict.txt");
return ieTwins(s)
.map(JSON.stringify)
.join("\n");
};
// --------------------- GENERIC ---------------------
// readFile :: FilePath -> IO String
const readFile = fp => {
// The contents of a text file at the
// filepath fp.
const
e = $(),
ns = $.NSString
.stringWithContentsOfFileEncodingError(
$(fp).stringByStandardizingPath,
$.NSUTF8StringEncoding,
e
);
return ObjC.unwrap(
ns.isNil() ? (
e.localizedDescription
) : ns
);
};
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre>["analyses","analysis"]
["atlantes","atlantis"]
["bellow","billow"]
["breton","briton"]
["clench","clinch"]
["convect","convict"]
["crises","crisis"]
["diagnoses","diagnosis"]
["enfant","infant"]
["enquiry","inquiry"]
["frances","francis"]
["galatea","galatia"]
["harden","hardin"]
["heckman","hickman"]
["inequity","iniquity"]
["inflect","inflict"]
["jacobean","jacobian"]
["marten","martin"]
["module","moduli"]
["pegging","pigging"]
["psychoses","psychosis"]
["rabbet","rabbit"]
["sterling","stirling"]
["synopses","synopsis"]
["vector","victor"]
["welles","willis"]</pre>
=={{header|jq}}==
{{works with|jq}}
Line 884 ⟶ 1,432:
For the sake of brevity, we confine attention to words longer than 6 characters.
 
<syntaxhighlight lang="jq">
<lang jq>
def e2i($dict):
select(index("e"))
Line 897 ⟶ 1,445:
| e2i($dict)
| "\($w) → \(.)"
</syntaxhighlight>
</lang>
Invocation: jq -n -rR -f e2i.jq unixdict.txt
{{out}}
Line 917 ⟶ 1,465:
synopses → synopsis
</pre>
 
=={{header|Julia}}==
See [[Alternade_words]] for the foreachword function.
<langsyntaxhighlight lang="julia">e2i(w, d) = (if 'e' in w s = replace(w, "e" => "i"); haskey(d, s) && return "$w => $s" end; "")
foreachword("unixdict.txt", e2i, minlen=6, colwidth=23, numcols=4)
</langsyntaxhighlight>{{out}}
<pre>
Word source: unixdict.txt
Line 934 ⟶ 1,481:
vector => victor welles => willis
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
<syntaxhighlight lang="mathematica">dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]];
dict //= StringSplit[#, "\n"] &;
dict //= Select[StringLength /* GreaterThan[5]];
sel = Select[dict, StringContainsQ["e"]];
sel = Select[sel, MemberQ[dict, StringReplace[#, "e" -> "i"]] &];
{#, StringReplace[#, "e" -> "i"]} & /@ sel</syntaxhighlight>
{{out}}
<pre>{{analyses,analysis},{atlantes,atlantis},{bellow,billow},{breton,briton},{clench,clinch},{convect,convict},{crises,crisis},{diagnoses,diagnosis},{enfant,infant},{enquiry,inquiry},{frances,francis},{galatea,galatia},{harden,hardin},{heckman,hickman},{inequity,iniquity},{inflect,inflict},{jacobean,jacobian},{marten,martin},{module,moduli},{pegging,pigging},{psychoses,psychosis},{rabbet,rabbit},{sterling,stirling},{synopses,synopsis},{vector,victor},{welles,willis}}</pre>
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import sets, strutils, sugar
 
# Build a set of words to speed up membership check.
Line 944 ⟶ 1,499:
let newWord = word.replace('e', 'i')
if newWord.len > 5 and newWord != word and newWord in wordSet:
echo word, " → ", newWord</langsyntaxhighlight>
 
{{out}}
Line 973 ⟶ 1,528:
vector → victor
welles → willis</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Change_e_letters_to_i_in_words
Line 984 ⟶ 1,538:
my %i = map { tr/i/e/r => sprintf "%30s %s\n", tr/i/e/r, $_ }
grep !/e/, grep 5 <= length, $file =~ /^.*i.*$/gm;
print @i{ split ' ', $file };</langsyntaxhighlight>
{{out}}
<pre>
Line 1,032 ⟶ 1,586:
wrest wrist
</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">unix_dict</span><span style="color: #0000FF;">()</span>
Line 1,041 ⟶ 1,594:
<span style="color: #004080;">sequence</span> <span style="color: #000000;">chetie</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cheti</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">chetei</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({</span><span style="color: #000000;">chetie</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">chetie</span><span style="color: #0000FF;">,</span><span style="color: #000000;">chei</span><span style="color: #0000FF;">)})</span>
<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;">"%d words: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">chetei</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">chetei</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
26 words: {{"analyses","analysis"},{"atlantes","atlantis"},"...",{"vector","victor"},{"welles","willis"}}
</pre>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">:- dynamic dictionary_word/1.
 
main:-
Line 1,081 ⟶ 1,633:
replace(Ch1, Ch2, Chars1, Chars2).
replace(Ch1, Ch2, [Ch|Chars1], [Ch|Chars2]):-
replace(Ch1, Ch2, Chars1, Chars2).</langsyntaxhighlight>
 
{{out}}
Line 1,112 ⟶ 1,664:
welles -> willis
</pre>
 
 
=={{header|Python}}==
Needs Python 3.8 or above for the assignment operator in the list comprehension.
{{Works with|Python|3.8}}
<langsyntaxhighlight lang="python">'''Dictionary words twinned by (e -> i) replacement'''
 
 
Line 1,126 ⟶ 1,676:
'e' by 'i'.
'''
allWordslongWords = s.splitlines()[
w for w in s.splitlines()
lexicon = set(allWords)
if 5 < len(w)
]
lexicon = {
w for w in longWords
if 'i' in w
}
 
return [
(w, twin) for w in allWordslongWords
if 5 < len(w) and 'e' in w and (
twin := w.replace('e', 'i')
) in lexicon
Line 1,143 ⟶ 1,699:
in unixdict.txt
'''
for pair in ieTwins(
ieTwinsreadFile("unixdict.txt")
readFile("unixdict.txt")
)
):
print(pair)
Line 1,155 ⟶ 1,709:
# readFile :: FilePath -> IO String
def readFile(fp):
'''The contents of any file at the path fp.
derived by expanding any ~ in fp.
'''
with open(fp, 'r', encoding='utf-8') as f:
Line 1,164 ⟶ 1,717:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>('analyses', 'analysis')
Line 1,192 ⟶ 1,745:
('vector', 'victor')
('welles', 'willis')</pre>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] swap ]'[ swap
witheach [
dup nested
Line 1,222 ⟶ 1,774:
[ swap echo$ cr ]
else nip ]
drop</langsyntaxhighlight>
 
{{out}}
Line 1,252 ⟶ 1,804:
victor
willis</pre>
=={{header|R}}==
 
<syntaxhighlight lang="rsplus">dict <- scan("https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt", what = character())
changed <- chartr("e", "i", dict)
cbind(Before = dict, After = changed)[changed != dict & changed %in% dict & nchar(changed) > 5, ]</syntaxhighlight>
{{out}}
<pre> Before After
[1,] "analyses" "analysis"
[2,] "atlantes" "atlantis"
[3,] "bellow" "billow"
[4,] "breton" "briton"
[5,] "clench" "clinch"
[6,] "convect" "convict"
[7,] "crises" "crisis"
[8,] "diagnoses" "diagnosis"
[9,] "enfant" "infant"
[10,] "enquiry" "inquiry"
[11,] "frances" "francis"
[12,] "galatea" "galatia"
[13,] "harden" "hardin"
[14,] "heckman" "hickman"
[15,] "inequity" "iniquity"
[16,] "inflect" "inflict"
[17,] "jacobean" "jacobian"
[18,] "marten" "martin"
[19,] "module" "moduli"
[20,] "pegging" "pigging"
[21,] "psychoses" "psychosis"
[22,] "rabbet" "rabbit"
[23,] "sterling" "stirling"
[24,] "synopses" "synopsis"
[25,] "vector" "victor"
[26,] "welles" "willis"</pre>
=={{header|Raku}}==
<syntaxhighlight lang="raku" perl6line>my %ei = 'unixdict.txt'.IO.words.grep({ .chars > 5 and /<[ie]>/ }).map: { $_ => .subst('e', 'i', :g) };
put %ei.grep( *.key.contains: 'e' ).grep({ %ei{.value}:exists }).sort.batch(4)».gist».fmt('%-22s').join: "\n";</langsyntaxhighlight>
 
{{out}}
Line 1,265 ⟶ 1,848:
psychoses => psychosis rabbet => rabbit sterling => stirling synopses => synopsis
vector => victor welles => willis</pre>
 
=={{header|REXX}}==
This REXX version doesn't care what order the words in the dictionary are in, &nbsp; nor does it care what
Line 1,272 ⟶ 1,854:
It also allows the minimum length to be specified on the command line (CL), &nbsp; as well as the old character &nbsp; (that is
<br>to be changed), &nbsp; the new character &nbsp; (that is to be changed into), &nbsp; and as well as the dictionary file identifier.
<langsyntaxhighlight lang="rexx">/*REXX pgm finds words with changed letter E──►I and is a word (in a specified dict).*/
parse arg minL oldC newC iFID . /*obtain optional arguments from the CL*/
if minL=='' | minL=="," then minL= 6 /*Not specified? Then use the default.*/
Line 1,299 ⟶ 1,881:
say /*stick a fork in it, we're all done. */
say copies('─',30) finds " words found that were changed with " oldC '──►' ,
newC", and with a minimum length of " minL</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,333 ⟶ 1,915:
────────────────────────────── 26 words found that were changed with E ──► I, and with a minimum length of 6
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 1,365 ⟶ 1,946:
 
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,397 ⟶ 1,978:
26. welles => willis
done...
</pre>
=={{header|RPL}}==
The only way to use <code>unixdict.txt</code> as input is to convert it into a list of 25104 strings. Fortunately, emulators can handle such a big data structure in RAM.
{{works with|Halcyon Calc|4.2.7}}
≪ → words
≪ { }
<span style="color:red">1</span> words EVAL SIZE '''FOR''' j
words j GET
'''IF''' DUP SIZE <span style="color:red">5</span> ≤ OVER <span style="color:red">"e"</span> POS NOT OR '''THEN''' DROP '''ELSE'''
<span style="color:red">""</span>
<span style="color:red">1 3</span> PICK SIZE '''FOR''' j
OVER j DUP SUB
NUM R→B <span style="color:red">#20h</span> OR B→R CHR <span style="color:grey">@turn into lowercase</span>
DUP <span style="color:red">"e"</span> == <span style="color:red">"i"</span> ROT IFTE +
'''NEXT'''
'''IF''' words EVAL OVER POS '''THEN''' <span style="color:red">" → "</span> SWAP + + + '''ELSE''' DROP2 '''END'''
'''END NEXT'''
≫ ≫ ‘<span style="color:blue">E→I</span>’ STO
{{out}}
<pre>
1: { "analyses → analysis" "atlantes → atlantis" "bellow → billow" "breton → briton" "clench → clinch" "convect → convict" "crises → crisis" "diagnoses → diagnosis" "enfant → infant" "enquiry → inquiry" "frances → francis" "galatea → galatia" "harden → hardin" "heckman → hickman" "inequity → iniquity" "inflect → inflict" "jacobean → jacobian" "marten → martin" "module → moduli" "pegging → pigging" "psychoses → psychosis" "rabbet → rabbit" "sterling → stirling" "synopses → synopsis" "vector → victor" "welles → willis" }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">words = File.readlines("unixdict.txt").map(&:chomp)
words.each do |word|
next if word.size < 6
Line 1,408 ⟶ 2,010:
puts "#{word.ljust(10)} -> #{e2i}"
end
</syntaxhighlight>
</lang>
{{out}}
<pre style="height: 30ex">analyses -> analysis
Line 1,439 ⟶ 2,041:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::collections::BTreeSet;
use std::fs::File;
use std::io::{self, BufRead};
Line 1,469 ⟶ 2,071:
Err(error) => eprintln!("{}", error),
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,500 ⟶ 2,102:
26. welles -> willis
</pre>
=={{header|SETL}}==
<syntaxhighlight lang="setl">program change_e_letters_to_i_in_words;
dictfile := open("unixdict.txt", "r");
dict := {getline(dictfile) : until eof(dictfile)};
close(dictfile);
 
loop for word in dict | #word > 5 do
if "e" notin word then continue; end if;
iword := replaceall(word, "e", "i");
if iword notin dict then continue; end if;
print([word, iword]);
end loop;
 
proc replaceall(word, x, y);
loop while x in word do
word(x) := y;
end loop;
return word;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>[analyses analysis]
[atlantes atlantis]
[bellow billow]
[breton briton]
[clench clinch]
[convect convict]
[crises crisis]
[diagnoses diagnosis]
[enfant infant]
[enquiry inquiry]
[frances francis]
[galatea galatia]
[harden hardin]
[heckman hickman]
[inequity iniquity]
[inflect inflict]
[jacobean jacobian]
[marten martin]
[module moduli]
[pegging pigging]
[psychoses psychosis]
[rabbet rabbit]
[sterling stirling]
[synopses synopsis]
[vector victor]
[welles willis]</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var file = File("unixdict.txt")
 
if (!file.exists) {
Line 1,527 ⟶ 2,176:
printf("%2d: %20s <-> %s\n", ++count, word, changed)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,559 ⟶ 2,208:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
 
func loadDictionary(path: String, minLength: Int) throws -> Set<String> {
Line 1,586 ⟶ 2,235:
} catch {
print(error.localizedDescription)
}</langsyntaxhighlight>
 
{{out}}
Line 1,617 ⟶ 2,266:
26. welles -> willis
</pre>
=={{header|VBScript}}==
Run it in CScript.
<syntaxhighlight lang="vb">
with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
set d=createobject("scripting.dictionary")
redim b(ubound(a))
i=0
for each x in a
s=trim(x)
if len(s)>5 then
if instr(s,"i") then d.add s,""
if instr(s,"e") then b(i)=s: i=i+1
end if
next
redim preserve b(i-1)
 
for i=0 to ubound(b)
s=trim(b(i))
s2=replace(s,"e","i")
if d.exists(s2) then
wscript.echo left(s& space(10),10) & "-> " & s2
end if
next
 
</syntaxhighlight>
{{out}}
<pre>
analyses -> analysis
atlantes -> atlantis
bellow -> billow
breton -> briton
clench -> clinch
convect -> convict
crises -> crisis
diagnoses -> diagnosis
enfant -> infant
enquiry -> inquiry
frances -> francis
galatea -> galatia
harden -> hardin
heckman -> hickman
inequity -> iniquity
inflect -> inflict
jacobean -> jacobian
marten -> martin
module -> moduli
pegging -> pigging
psychoses -> psychosis
rabbet -> rabbit
sterling -> stirling
synopses -> synopsis
vector -> victor
welles -> willis
</pre>
=={{header|Wren}}==
{{libheader|Wren-sort}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
import "./sort" for Find
import "./fmt" for Fmt
 
var wordList = "unixdict.txt" // local copy
Line 1,637 ⟶ 2,345:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,668 ⟶ 2,376:
26: welles -> willis
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">string 0; \use zero-terminated strings
int Dict(26000); \pointers to words (enough for unixdict.txt)
int DictSize; \actual number of pointers in Dict
 
func StrCmp(A, B); \Compare string A to B
char A, B; \Returns: >0 if A>B, =0 if A=B, and <0 if A<B
int I;
[for I:= 0 to -1>>1 do
[if A(I) # B(I) then return A(I) - B(I);
if A(I) = 0 then return 0;
];
]; \StrCmp
 
func LookUp(Word); \Return 'true' if Word is in Dict
char Word;
int Lo, Hi, I, Cmp;
[Lo:= 0; Hi:= DictSize-1;
loop [I:= (Lo+Hi) / 2; \binary search
Cmp:= StrCmp(Word, Dict(I));
if Cmp < 0 then Hi:= I-1 else Lo:= I+1;
if Cmp = 0 then return true;
if Lo > Hi then return false;
];
]; \LookUp
 
int I, DI, Ch, HasE;
char Word, AltWord(25); \(longest word in unixdict is 22 chars)
def LF=$0A, CR=$0D, EOF=$1A;
 
[FSet(FOpen("unixdict.txt", 0), ^I); \load dictionary into Dict
OpenI(3); \assume alphabetical order and all lowercase
DI:= 0; \ignore non-alpha characters: 0..9, ' and &
repeat Dict(DI):= Reserve(0); \get pointer to memory used to store Word
Word:= Dict(DI);
I:= 0;
loop [repeat Ch:= ChIn(3) until Ch # CR; \remove possible CR
if Ch=LF or Ch=EOF then quit;
Word(I):= Ch;
I:= I+1;
];
Word(I):= 0; \terminate Word string
I:= Reserve(I+1); \reserve memory used for Word
DI:= DI+1; \next dictionary entry
until Ch = EOF;
DictSize:= DI;
 
DI:= 0;
repeat Word:= Dict(DI);
I:= 0; HasE:= false;
loop [Ch:= Word(I);
AltWord(I):= Ch;
if Ch = 0 then quit;
if Ch = ^e then
[HasE:= true;
AltWord(I):= ^i;
];
I:= I+1;
];
if HasE & I>5 then \Word must be greater than 5 chars
[if LookUp(AltWord) then
[Text(0, Word);
Text(0, " -> ");
Text(0, AltWord);
CrLf(0);
];
];
DI:= DI+1;
until DI >= DictSize;
]</syntaxhighlight>
 
{{out}}
<pre>
analyses -> analysis
atlantes -> atlantis
bellow -> billow
breton -> briton
clench -> clinch
convect -> convict
crises -> crisis
diagnoses -> diagnosis
enfant -> infant
enquiry -> inquiry
frances -> francis
galatea -> galatia
harden -> hardin
heckman -> hickman
inequity -> iniquity
inflect -> inflict
jacobean -> jacobian
marten -> martin
module -> moduli
pegging -> pigging
psychoses -> psychosis
rabbet -> rabbit
sterling -> stirling
synopses -> synopsis
vector -> victor
welles -> willis
</pre>
{{omit from|6502 Assembly|unixdict.txt is much larger than the CPU's address space.}}
{{omit from|8080 Assembly|See 6502 Assembly.}}
{{omit from|Z80 Assembly|See 6502 Assembly.}}
2,093

edits