Find words whose first and last three letters are equal: Difference between revisions

From Rosetta Code
Content added Content deleted
m (syntax highlighting fixup automation)
Line 12: Line 12:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>L(word) File(‘unixdict.txt’).read().split("\n")
<syntaxhighlight lang="11l">L(word) File(‘unixdict.txt’).read().split("\n")
I word.len > 5 & word[0.<3] == word[(len)-3..]
I word.len > 5 & word[0.<3] == word[(len)-3..]
print(word)</lang>
print(word)</syntaxhighlight>


{{out}}
{{out}}
Line 30: Line 30:
=={{header|Action!}}==
=={{header|Action!}}==
In the following solution the input file [https://gitlab.com/amarok8bit/action-rosetta-code/-/blob/master/source/unixdict.txt unixdict.txt] is loaded from H6 drive. Altirra emulator automatically converts CR/LF character from ASCII into 155 character in ATASCII charset used by Atari 8-bit computer when one from H6-H10 hard drive under DOS 2.5 is used.
In the following solution the input file [https://gitlab.com/amarok8bit/action-rosetta-code/-/blob/master/source/unixdict.txt unixdict.txt] is loaded from H6 drive. Altirra emulator automatically converts CR/LF character from ASCII into 155 character in ATASCII charset used by Atari 8-bit computer when one from H6-H10 hard drive under DOS 2.5 is used.
<lang Action!>BYTE FUNC IsValidWord(CHAR ARRAY word)
<syntaxhighlight lang="action!">BYTE FUNC IsValidWord(CHAR ARRAY word)
BYTE len
BYTE len


Line 61: Line 61:


FindWords(fname)
FindWords(fname)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Find_words_whose_first_and_last_three_letters_are_equal.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Find_words_whose_first_and_last_three_letters_are_equal.png Screenshot from Atari 8-bit computer]
Line 69: Line 69:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Strings.Fixed;
with Ada.Strings.Fixed;


Line 92: Line 92:
end loop;
end loop;
Close (File);
Close (File);
end Find_Three_Equals;</lang>
end Find_Three_Equals;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68># find 6 (or more) character words with the same first and last 3 letters #
<syntaxhighlight lang="algol68"># find 6 (or more) character words with the same first and last 3 letters #
IF FILE input file;
IF FILE input file;
STRING file name = "unixdict.txt";
STRING file name = "unixdict.txt";
Line 136: Line 136:
print( ( newline, "found ", whole( count, 0 ), " words with the same first and last 3 characters", newline ) );
print( ( newline, "found ", whole( count, 0 ), " words with the same first and last 3 characters", newline ) );
close( input file )
close( input file )
FI</lang>
FI</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 146: Line 146:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>words: read.lines relative "unixdict.txt"
<syntaxhighlight lang="rebol">words: read.lines relative "unixdict.txt"
equalHeadTail?: function [w][
equalHeadTail?: function [w][
equal? first.n: 3 w last.n: 3 w
equal? first.n: 3 w last.n: 3 w
Line 156: Line 156:
print word
print word
]
]
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 170: Line 170:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>FileRead, db, % A_Desktop "\unixdict.txt"
<syntaxhighlight lang="autohotkey">FileRead, db, % A_Desktop "\unixdict.txt"
for i, word in StrSplit(db, "`n", "`r")
for i, word in StrSplit(db, "`n", "`r")
if StrLen(word) < 6
if StrLen(word) < 6
Line 177: Line 177:
result .= word "`n"
result .= word "`n"
MsgBox, 262144, , % result
MsgBox, 262144, , % result
return</lang>
return</syntaxhighlight>
{{out}}
{{out}}
<pre>antiperspirant
<pre>antiperspirant
Line 189: Line 189:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f FIND_WORDS_WHICH_FIRST_AND_LAST_THREE_LETTERS_ARE_EQUALS.AWK unixdict.txt
# syntax: GAWK -f FIND_WORDS_WHICH_FIRST_AND_LAST_THREE_LETTERS_ARE_EQUALS.AWK unixdict.txt
(length($0) >= 6 && substr($0,1,3) == substr($0,length($0)-2,3))
(length($0) >= 6 && substr($0,1,3) == substr($0,length($0)-2,3))
Line 195: Line 195:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 209: Line 209:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <cstdlib>
<syntaxhighlight lang="cpp">#include <cstdlib>
#include <fstream>
#include <fstream>
#include <iostream>
#include <iostream>
Line 228: Line 228:
}
}
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 243: Line 243:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
// First and last three letters are equal. Nigel Galloway: February 18th., 2021
// First and last three letters are equal. Nigel Galloway: February 18th., 2021
let fN g=if String.length g<6 then false else g.[..2]=g.[g.Length-3..]
let fN g=if String.length g<6 then false else g.[..2]=g.[g.Length-3..]
seq{use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter fN|>Seq.iter(printfn "%s")
seq{use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter fN|>Seq.iter(printfn "%s")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 262: Line 262:
===Read entire file===
===Read entire file===
This version reads the entire dictionary file into memory and filters it. This is the fastest version by far. Factor is optimized for making multiple passes over data; it actually takes longer if we combine the two filters into one, either with short-circuiting or non-short-circuiting <code>and</code>.
This version reads the entire dictionary file into memory and filters it. This is the fastest version by far. Factor is optimized for making multiple passes over data; it actually takes longer if we combine the two filters into one, either with short-circuiting or non-short-circuiting <code>and</code>.
<lang factor>USING: io io.encodings.ascii io.files kernel math sequences ;
<syntaxhighlight lang="factor">USING: io io.encodings.ascii io.files kernel math sequences ;


"unixdict.txt" ascii file-lines
"unixdict.txt" ascii file-lines
[ length 5 > ] filter
[ length 5 > ] filter
[ [ 3 head-slice ] [ 3 tail-slice* ] bi = ] filter
[ [ 3 head-slice ] [ 3 tail-slice* ] bi = ] filter
[ print ] each</lang>
[ print ] each</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 282: Line 282:
===Read file line by line===
===Read file line by line===
This version reads the dictionary file line by line and prints out words that fit the criteria. This ends up being a bit more imperative and deeply nested, but unlike the version above, we only load one word at a time, saving quite a bit of memory.
This version reads the dictionary file line by line and prints out words that fit the criteria. This ends up being a bit more imperative and deeply nested, but unlike the version above, we only load one word at a time, saving quite a bit of memory.
<lang factor>USING: combinators.short-circuit io io.encodings.ascii io.files
<syntaxhighlight lang="factor">USING: combinators.short-circuit io io.encodings.ascii io.files
kernel math sequences ;
kernel math sequences ;


Line 297: Line 297:
] when*
] when*
] loop
] loop
] with-file-reader</lang>
] with-file-reader</syntaxhighlight>
{{out}}
{{out}}
As above.
As above.
Line 303: Line 303:
===Lazy file I/O===
===Lazy file I/O===
This version lazily reads the input file by treating a stream like a lazy list with the <code>llines</code> word. This allows us the nice style of the first example with the memory benefits of the second example. Unlike in the first example, combining the filters would buy us some time here, as lazy lists aren't as efficient as sequences.
This version lazily reads the input file by treating a stream like a lazy list with the <code>llines</code> word. This allows us the nice style of the first example with the memory benefits of the second example. Unlike in the first example, combining the filters would buy us some time here, as lazy lists aren't as efficient as sequences.
<lang factor>USING: io io.encodings.ascii io.files kernel lists lists.lazy
<syntaxhighlight lang="factor">USING: io io.encodings.ascii io.files kernel lists lists.lazy
math sequences ;
math sequences ;


Line 309: Line 309:
[ length 5 > ] lfilter
[ length 5 > ] lfilter
[ [ 3 head-slice ] [ 3 tail-slice* ] bi = ] lfilter
[ [ 3 head-slice ] [ 3 tail-slice* ] bi = ] lfilter
[ print ] leach</lang>
[ print ] leach</syntaxhighlight>
{{out}}
{{out}}
As above.
As above.
Line 315: Line 315:
=={{header|Forth}}==
=={{header|Forth}}==
{{works with|Gforth}}
{{works with|Gforth}}
<lang forth>: first-last-three-equal { addr len -- ? }
<syntaxhighlight lang="forth">: first-last-three-equal { addr len -- ? }
len 5 <= if false exit then
len 5 <= if false exit then
addr 3 addr len 3 - + 3 compare 0= ;
addr 3 addr len 3 - + 3 compare 0= ;
Line 338: Line 338:


main
main
bye</lang>
bye</syntaxhighlight>


{{out}}
{{out}}
Line 353: Line 353:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>#define NULL 0
<syntaxhighlight lang="freebasic">#define NULL 0


type node
type node
Line 403: Line 403:
nextword:
nextword:
curr = curr->nxt
curr = curr->nxt
wend</lang>
wend</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 416: Line 416:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 441: Line 441:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 456: Line 456:


=={{header|J}}==
=={{header|J}}==
<lang J> >(#~ ((3&{. -: _3&{.)*5<#)@>) cutLF fread 'unixdict.txt'
<syntaxhighlight lang="j"> >(#~ ((3&{. -: _3&{.)*5<#)@>) cutLF fread 'unixdict.txt'
antiperspirant
antiperspirant
calendrical
calendrical
Line 464: Line 464:
oshkosh
oshkosh
tartar
tartar
testes</lang>
testes</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
{{works with|jq}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
'''Works with gojq, the Go implementation of jq'''
<lang jq>select(length > 5 and .[:3] == .[-3:])</lang>
<syntaxhighlight lang="jq">select(length > 5 and .[:3] == .[-3:])</syntaxhighlight>
{{out}}
{{out}}
Invocation example: jq -rRM -f program.jq unixdict.txt
Invocation example: jq -rRM -f program.jq unixdict.txt
Line 485: Line 485:
=={{header|Julia}}==
=={{header|Julia}}==
See Alternade_words#Julia for the foreachword function.
See Alternade_words#Julia for the foreachword function.
<lang julia>matchfirstlast3(word, _) = length(word) > 5 && word[1:3] == word[end-2:end] ? word : ""
<syntaxhighlight lang="julia">matchfirstlast3(word, _) = length(word) > 5 && word[1:3] == word[end-2:end] ? word : ""
foreachword("unixdict.txt", matchfirstlast3, numcols=4)</lang>{{out}}
foreachword("unixdict.txt", matchfirstlast3, numcols=4)</syntaxhighlight>{{out}}
<pre>
<pre>
Word source: unixdict.txt
Word source: unixdict.txt
Line 495: Line 495:


=={{header|Ksh}}==
=={{header|Ksh}}==
<lang ksh>#!/bin/ksh
<syntaxhighlight lang="ksh">#!/bin/ksh


# Find list of words (> 5 chars) where 1st 3 and last 3 letters are the same
# Find list of words (> 5 chars) where 1st 3 and last 3 letters are the same
Line 517: Line 517:
[[ ${first} == ${last} ]] && print ${word}
[[ ${first} == ${last} ]] && print ${word}


done < ${dict}</lang>
done < ${dict}</syntaxhighlight>


{{out}}
{{out}}
Line 530: Line 530:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]];
<syntaxhighlight lang="mathematica">dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]];
dict //= StringSplit[#, "\n"] &;
dict //= StringSplit[#, "\n"] &;
dict //= Select[StringLength /* GreaterThan[5]];
dict //= Select[StringLength /* GreaterThan[5]];
Select[dict, StringTake[#, 3] === StringTake[#, -3] &]</lang>
Select[dict, StringTake[#, 3] === StringTake[#, -3] &]</syntaxhighlight>
{{out}}
{{out}}
<pre>{"antiperspirant", "calendrical", "einstein", "hotshot", "murmur", "oshkosh", "tartar", "testes"}</pre>
<pre>{"antiperspirant", "calendrical", "einstein", "hotshot", "murmur", "oshkosh", "tartar", "testes"}</pre>


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>for word in "unixdict.txt".lines:
<syntaxhighlight lang="nim">for word in "unixdict.txt".lines:
if word.len > 5:
if word.len > 5:
if word[0..2] == word[^3..^1]:
if word[0..2] == word[^3..^1]:
echo word</lang>
echo word</syntaxhighlight>


{{out}}
{{out}}
Line 555: Line 555:
=={{header|Perl}}==
=={{header|Perl}}==
as one-liner ..
as one-liner ..
<lang perl>// 20210212 Perl programming solution
<syntaxhighlight lang="perl">// 20210212 Perl programming solution


perl -ne '/(?=^(.{3}).*\1$)^.{6,}$/&&print' unixdict.txt
perl -ne '/(?=^(.{3}).*\1$)^.{6,}$/&&print' unixdict.txt
Line 561: Line 561:
# minor variation
# minor variation


perl -ne 's/(?=^(.{3}).*\1$)^.{6,}$/print/e' unixdict.txt</lang>
perl -ne 's/(?=^(.{3}).*\1$)^.{6,}$/print/e' unixdict.txt</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">flaste</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)></span><span style="color: #000000;">5</span> <span style="color: #008080;">and</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">word</span><span style="color: #0000FF;">[-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">flaste</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)></span><span style="color: #000000;">5</span> <span style="color: #008080;">and</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">word</span><span style="color: #0000FF;">[-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">flastes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">unix_dict</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">flaste</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">flastes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">unix_dict</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">flaste</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: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">flastes</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">flastes</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</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: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">flastes</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">flastes</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">))})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 576: Line 576:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>firstAndLast3Equal: procedure options(main);
<syntaxhighlight lang="pli">firstAndLast3Equal: procedure options(main);
declare dict file;
declare dict file;
open file(dict) title('unixdict.txt');
open file(dict) title('unixdict.txt');
Line 589: Line 589:
put skip list(word);
put skip list(word);
end;
end;
end firstAndLast3Equal;</lang>
end firstAndLast3Equal;</syntaxhighlight>
{{out}}
{{out}}
<pre>antiperspirant
<pre>antiperspirant
Line 602: Line 602:
=={{header|Python}}==
=={{header|Python}}==
Tested on Python 3+, the file download will work only if the link is still active. It is possible that you may be able to fetch the file in your browser but download via code may still fail. Check whether you are connected to a VPN, it works on open networks
Tested on Python 3+, the file download will work only if the link is still active. It is possible that you may be able to fetch the file in your browser but download via code may still fail. Check whether you are connected to a VPN, it works on open networks
<syntaxhighlight lang="python">
<lang Python>
import urllib.request
import urllib.request
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
Line 615: Line 615:
if len(word)>5 and word[:3].lower()==word[-3:].lower():
if len(word)>5 and word[:3].lower()==word[-3:].lower():
print(word)
print(word)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 630: Line 630:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ [] swap ]'[ swap
<syntaxhighlight lang="quackery"> [ [] swap ]'[ swap
witheach [
witheach [
dup nested
dup nested
Line 641: Line 641:
filter [ size 5 > ]
filter [ size 5 > ]
filter [ 3 split -3 split nip = ]
filter [ 3 split -3 split nip = ]
witheach [ echo$ cr ]</lang>
witheach [ echo$ cr ]</syntaxhighlight>


{{out}}
{{out}}
Line 656: Line 656:


=={{header|R}}==
=={{header|R}}==
<lang rsplus>dict <- scan("https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt", what = character())
<syntaxhighlight lang="rsplus">dict <- scan("https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt", what = character())
dict[nchar(dict) > 5 & substr(dict, 1, 3) == substr(dict, nchar(dict) - 2, nchar(dict))]</lang>
dict[nchar(dict) > 5 & substr(dict, 1, 3) == substr(dict, nchar(dict) - 2, nchar(dict))]</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define ((prefix-and-suffix-match? len) str)
(define ((prefix-and-suffix-match? len) str)
Line 670: Line 670:


(module+ main
(module+ main
(filter (prefix-and-suffix-match? 3) (file->lines "../../data/unixdict.txt")))</lang>
(filter (prefix-and-suffix-match? 3) (file->lines "../../data/unixdict.txt")))</syntaxhighlight>


{{out}}
{{out}}
Line 677: Line 677:


=={{header|Raku}}==
=={{header|Raku}}==
<lang perl6># 20210210 Raku programming solution
<syntaxhighlight lang="raku" line># 20210210 Raku programming solution


my ( \L, \N, \IN ) = 5, 3, 'unixdict.txt';
my ( \L, \N, \IN ) = 5, 3, 'unixdict.txt';


for IN.IO.lines { .say if .chars > L and .substr(0,N) eq .substr(*-N,*) }
for IN.IO.lines { .say if .chars > L and .substr(0,N) eq .substr(*-N,*) }
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 696: Line 696:


=={{header|Red}}==
=={{header|Red}}==
<lang rebol>Red[]
<syntaxhighlight lang="rebol">Red[]


foreach word read/lines %unixdict.txt [
foreach word read/lines %unixdict.txt [
Line 705: Line 705:
print word
print word
]
]
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 726: Line 726:
It also allows the length ('''3''') of the first and last number of letters to be specified, &nbsp; and also the minimum length of the
It also allows the length ('''3''') of the first and last number of letters to be specified, &nbsp; and also the minimum length of the
<br>words to be searched on the command line (CL) as well as specifying the dictionary file identifier.
<br>words to be searched on the command line (CL) as well as specifying the dictionary file identifier.
<lang rexx>/*REXX pgm finds words in an specified dict. which have the same 1st and last 3 letters.*/
<syntaxhighlight lang="rexx">/*REXX pgm finds words in an specified dict. which have the same 1st and last 3 letters.*/
parse arg minL many iFID . /*obtain optional arguments from the CL*/
parse arg minL many iFID . /*obtain optional arguments from the CL*/
if minL=='' | minL=="," then minL= 6 /* " " " " " " */
if minL=='' | minL=="," then minL= 6 /* " " " " " " */
Line 750: Line 750:
/*stick a fork in it, we're all done. */
/*stick a fork in it, we're all done. */
say copies('─', 30) finds " words found that the left " many ' letters match the' ,
say copies('─', 30) finds " words found that the left " many ' letters match the' ,
"right letters which a word has a minimal length of " minL</lang>
"right letters which a word has a minimal length of " minL</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre style="font-size:89%">
<pre style="font-size:89%">
Line 766: Line 766:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
load "stdlib.ring"
load "stdlib.ring"


Line 791: Line 791:


see "done..." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 808: Line 808:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>words = File.readlines("unixdict.txt").map(&:chomp)
<syntaxhighlight lang="ruby">words = File.readlines("unixdict.txt").map(&:chomp)
puts words.select{|w| w.end_with?(w[0,3]) && w.size > 5}
puts words.select{|w| w.end_with?(w[0,3]) && w.size > 5}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>antiperspirant
<pre>antiperspirant
Line 822: Line 822:
</pre>
</pre>
=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>File("unixdict.txt").open_r.each {|word|
<syntaxhighlight lang="ruby">File("unixdict.txt").open_r.each {|word|
word.len > 5 || next
word.len > 5 || next
if (word.ends_with(word.first(3))) {
if (word.ends_with(word.first(3))) {
say word
say word
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 841: Line 841:


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


do {
do {
Line 851: Line 851:
} catch {
} catch {
print(error.localizedDescription)
print(error.localizedDescription)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 867: Line 867:
=={{header|VBScript}}==
=={{header|VBScript}}==
After building a program checking for the 3 letters in any order, I found people just checked the same trigraph at start and end. I modified my program so it puts an asterisk after the words in the "standard" answer. Run the ssript with CScript.
After building a program checking for the 3 letters in any order, I found people just checked the same trigraph at start and end. I modified my program so it puts an asterisk after the words in the "standard" answer. Run the ssript with CScript.
<syntaxhighlight lang="vb">
<lang vb>
with createobject("ADODB.Stream")
with createobject("ADODB.Stream")
.charset ="UTF-8"
.charset ="UTF-8"
Line 902: Line 902:
end if
end if
next
next
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 927: Line 927:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "io" for File
<syntaxhighlight lang="ecmascript">import "io" for File
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 939: Line 939:
count = count + 1
count = count + 1
Fmt.print("$d: $s", count, w)
Fmt.print("$d: $s", count, w)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 954: Line 954:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0; \Use zero-terminated strings
<syntaxhighlight lang="xpl0">string 0; \Use zero-terminated strings
int I, Ch, Len;
int I, Ch, Len;
char Word(100); \(longest word in unixdict.txt is 22 chars)
char Word(100); \(longest word in unixdict.txt is 22 chars)
Line 974: Line 974:
[Text(0, Word); CrLf(0)];
[Text(0, Word); CrLf(0)];
until Ch = EOF;
until Ch = EOF;
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}

Revision as of 13:06, 27 August 2022

Find words whose first and last three letters are equal is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task

Using the dictionary  unixdict.txt

find the words whose first and last three letters are equal.

The length of any word shown should have a length   >  5.


Other tasks related to string operations:
Metrics
Counting
Remove/replace
Anagrams/Derangements/shuffling
Find/Search/Determine
Formatting
Song lyrics/poems/Mad Libs/phrases
Tokenize
Sequences



11l

L(word) File(‘unixdict.txt’).read().split("\n")
   I word.len > 5 & word[0.<3] == word[(len)-3..]
      print(word)
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Action!

In the following solution the input file unixdict.txt is loaded from H6 drive. Altirra emulator automatically converts CR/LF character from ASCII into 155 character in ATASCII charset used by Atari 8-bit computer when one from H6-H10 hard drive under DOS 2.5 is used.

BYTE FUNC IsValidWord(CHAR ARRAY word)
  BYTE len

  len=word(0)
  IF len<=5 THEN RETURN (0) FI
  IF word(1)#word(len-2) THEN RETURN(0) FI
  IF word(2)#word(len-1) THEN RETURN(0) FI
  IF word(3)#word(len) THEN RETURN(0) FI
RETURN (1)

PROC FindWords(CHAR ARRAY fname)
  CHAR ARRAY line(256)
  CHAR ARRAY tmp(256)
  BYTE dev=[1]

  Close(dev)
  Open(dev,fname,4)
  WHILE Eof(dev)=0
  DO
    InputSD(dev,line)
    IF IsValidWord(line) THEN
      PrintE(line)
    FI
  OD
  Close(dev)
RETURN

PROC Main()
  CHAR ARRAY fname="H6:UNIXDICT.TXT"

  FindWords(fname)
RETURN
Output:

Screenshot from Atari 8-bit computer

antiperspirant calendrical einstein hotshot murmur oshkosh tartar testes

Ada

with Ada.Text_Io;
with Ada.Strings.Fixed;

procedure Find_Three_Equals is
   use Ada.Text_Io;
   use Ada.Strings.Fixed;

   Filename : constant String := "unixdict.txt";
   File     : File_Type;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word  : constant String  := Get_Line (File);
         First : String renames Head (Word, 3);
         Last  : String renames Tail (Word, 3);
      begin
         if First = Last and Word'Length > 5 then
            Put_Line (Word);
         end if;
      end;
   end loop;
   Close (File);
end Find_Three_Equals;

ALGOL 68

# find 6 (or more) character words with the same first and last 3 letters #
IF  FILE input file;
    STRING file name = "unixdict.txt";
    open( input file, file name, stand in channel ) /= 0
THEN
    # failed to open the file #
    print( ( "Unable to open """ + file name + """", newline ) )
ELSE
    # file opened OK #
    BOOL at eof := FALSE;
    # set the EOF handler for the file #
    on logical file end( input file, ( REF FILE f )BOOL:
                                     BEGIN
                                         # note that we reached EOF on the #
                                         # latest read #
                                         at eof := TRUE;
                                         # return TRUE so processing can continue #
                                         TRUE
                                     END
                       );
    INT count := 0;
    WHILE STRING word;
          get( input file, ( word, newline ) );
          NOT at eof
    DO
        IF INT w len = ( UPB word + 1 ) - LWB word;
           w len > 5
        THEN
            IF word[ 1 : 3 ] = word[ w len - 2 : ]
            THEN
                count +:= 1;
                print( ( word, " " ) );
                IF count MOD 5 = 0
                THEN print( ( newline ) )
                ELSE FROM w len + 1 TO 14 DO print( ( " " ) ) OD
                FI
            FI
        FI
    OD;
    print( ( newline, "found ", whole( count, 0 ), " words with the same first and last 3 characters", newline ) );
    close( input file )
FI
Output:
antiperspirant calendrical    einstein       hotshot        murmur
oshkosh        tartar         testes
found 8 words with the same first and last 3 characters

Arturo

words: read.lines relative "unixdict.txt"
equalHeadTail?: function [w][
    equal? first.n: 3 w last.n: 3 w
]

loop words 'word [
    if 5 < size word [
        if equalHeadTail? word ->
            print word
    ]
]
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

AutoHotkey

FileRead, db, % A_Desktop "\unixdict.txt"
for i, word in StrSplit(db, "`n", "`r")
    if StrLen(word) < 6
        continue
    else if (SubStr(word, 1, 3) = SubStr(word, -2))
        result .= word "`n"
MsgBox, 262144, , % result
return
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

AWK

# syntax: GAWK -f FIND_WORDS_WHICH_FIRST_AND_LAST_THREE_LETTERS_ARE_EQUALS.AWK unixdict.txt
(length($0) >= 6 && substr($0,1,3) == substr($0,length($0)-2,3))
END {
    exit(0)
}
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

C++

#include <cstdlib>
#include <fstream>
#include <iostream>

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string word;
    int n = 0;
    while (getline(in, word)) {
        const size_t len = word.size();
        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)
            std::cout << ++n << ": " << word << '\n';
    }
    return EXIT_SUCCESS;
}
Output:
1. antiperspirant
2. calendrical
3. einstein
4. hotshot
5. murmur
6. oshkosh
7. tartar
8. testes

F#

// First and last three letters are equal. Nigel Galloway: February 18th., 2021
let fN g=if String.length g<6 then false else g.[..2]=g.[g.Length-3..]
seq{use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter fN|>Seq.iter(printfn "%s")
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Factor

Read entire file

This version reads the entire dictionary file into memory and filters it. This is the fastest version by far. Factor is optimized for making multiple passes over data; it actually takes longer if we combine the two filters into one, either with short-circuiting or non-short-circuiting and.

USING: io io.encodings.ascii io.files kernel math sequences ;

"unixdict.txt" ascii file-lines
[ length 5 > ] filter
[ [ 3 head-slice ] [ 3 tail-slice* ] bi = ] filter
[ print ] each
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Read file line by line

This version reads the dictionary file line by line and prints out words that fit the criteria. This ends up being a bit more imperative and deeply nested, but unlike the version above, we only load one word at a time, saving quite a bit of memory.

USING: combinators.short-circuit io io.encodings.ascii io.files
kernel math sequences ;

"unixdict.txt" ascii [
    [
        readln dup
        [
            dup
            {
                [ length 5 > ]
                [ [ 3 head-slice ] [ 3 tail-slice* ] bi = ]
            } 1&&
            [ print ] [ drop ] if
        ] when*
    ] loop
] with-file-reader
Output:

As above.

Lazy file I/O

This version lazily reads the input file by treating a stream like a lazy list with the llines word. This allows us the nice style of the first example with the memory benefits of the second example. Unlike in the first example, combining the filters would buy us some time here, as lazy lists aren't as efficient as sequences.

USING: io io.encodings.ascii io.files kernel lists lists.lazy
math sequences ;

"unixdict.txt" ascii <file-reader> llines
[ length 5 > ] lfilter
[ [ 3 head-slice ] [ 3 tail-slice* ] bi = ] lfilter
[ print ] leach
Output:

As above.

Forth

Works with: Gforth
: first-last-three-equal { addr len -- ? }
  len 5 <= if false exit then
  addr 3 addr len 3 - + 3 compare 0= ;

256 constant max-line

: main
  0 0 { count fd-in }
  s" unixdict.txt" r/o open-file throw to fd-in
  begin
    here max-line fd-in read-line throw
  while
    here swap 2dup first-last-three-equal if
      count 1+ to count
      count 1 .r ." . " type cr
    else
      2drop
    then
  repeat
  drop
  fd-in close-file throw ;

main
bye
Output:
1. antiperspirant
2. calendrical
3. einstein
4. hotshot
5. murmur
6. oshkosh
7. tartar
8. testes

FreeBASIC

#define NULL 0

type node
    word as string*32   'enough space to store any word in the dictionary
    nxt as node ptr
end type

function addword( tail as node ptr, word as string ) as node ptr
    'allocates memory for a new node, links the previous tail to it,
    'and returns the address of the new node
    dim as node ptr newnode = allocate(sizeof(node))
    tail->nxt = newnode
    newnode->nxt = NULL
    newnode->word = word
    return newnode
end function

function length( word as string ) as uinteger
    'necessary replacement for the built-in len function, which in this
    'case would always return 32
    for i as uinteger = 1 to 32
        if asc(mid(word,i,1)) = 0 then return i-1
    next i
    return 999
end function

dim as string word
dim as node ptr tail = allocate( sizeof(node) )
dim as node ptr head = tail, curr = head, currj
dim as uinteger ln
tail->nxt = NULL
tail->word = "XXXXHEADER"

open "unixdict.txt" for input as #1
while true
    line input #1, word
    if word = "" then exit while
    if length(word)>5 then tail = addword( tail, word )
wend
close #1

while curr->nxt <> NULL
    word = curr->word
    ln = length(word)
    for i as uinteger = 1 to 3
        if mid(word,i,1) <> mid(word,ln-3+i,1) then goto nextword
    next i
    print word
    nextword:
    curr = curr->nxt
wend
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Go

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "unicode/utf8"
)

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    count := 0
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {
            count++
            fmt.Printf("%d: %s\n", count, s)
        }
    }
}
Output:
1: antiperspirant
2: calendrical
3: einstein
4: hotshot
5: murmur
6: oshkosh
7: tartar
8: testes

J

   >(#~ ((3&{. -: _3&{.)*5<#)@>) cutLF fread 'unixdict.txt'
antiperspirant
calendrical   
einstein      
hotshot       
murmur        
oshkosh       
tartar        
testes

jq

Works with: jq

Works with gojq, the Go implementation of jq

select(length > 5 and .[:3] == .[-3:])
Output:

Invocation example: jq -rRM -f program.jq unixdict.txt

antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Julia

See Alternade_words#Julia for the foreachword function.

matchfirstlast3(word, _) = length(word) > 5 && word[1:3] == word[end-2:end] ? word : ""
foreachword("unixdict.txt", matchfirstlast3, numcols=4)
Output:
Word source: unixdict.txt

antiperspirant calendrical    einstein       hotshot
murmur         oshkosh        tartar         testes

Ksh

#!/bin/ksh

# Find list of words (> 5 chars) where 1st 3 and last 3 letters are the same

#	# Variables:
#
dict='../unixdict.txt'
integer MIN_LEN=5
integer MATCH_NO=3

 ######
# main #
 ######

 while read word; do
	(( ${#word} <= MIN_LEN )) && continue

	first=${word:0:${MATCH_NO}}
	last=${word:$((${#word}-MATCH_NO)):${#word}}

	[[ ${first} == ${last} ]] && print ${word}

 done < ${dict}
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Mathematica/Wolfram Language

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]];
Select[dict, StringTake[#, 3] === StringTake[#, -3] &]
Output:
{"antiperspirant", "calendrical", "einstein", "hotshot", "murmur", "oshkosh", "tartar", "testes"}

Nim

for word in "unixdict.txt".lines:
  if word.len > 5:
    if word[0..2] == word[^3..^1]:
      echo word
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Perl

as one-liner ..

// 20210212 Perl programming solution

perl -ne '/(?=^(.{3}).*\1$)^.{6,}$/&&print' unixdict.txt

# minor variation

perl -ne 's/(?=^(.{3}).*\1$)^.{6,}$/print/e' unixdict.txt

Phix

with javascript_semantics
function flaste(string word) return length(word)>5 and word[1..3]=word[-3..-1] end function
sequence flastes = filter(unix_dict(),flaste)
printf(1,"%d words: %s\n",{length(flastes),join(shorten(flastes,"",3))})
Output:
8 words: antiperspirant calendrical einstein hotshot murmur oshkosh tartar testes

PL/I

firstAndLast3Equal: procedure options(main);
    declare dict file;
    open file(dict) title('unixdict.txt');
    on endfile(dict) stop;
    
    declare word char(32) varying, (first3, last3) char(3);
    do while('1'b);
        get file(dict) list(word);
        first3 = substr(word, 1, 3);
        last3 = substr(word, length(word)-2, 3);
        if length(word) > 5 & first3 = last3 then
            put skip list(word); 
    end;    
end firstAndLast3Equal;
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Python

Tested on Python 3+, the file download will work only if the link is still active. It is possible that you may be able to fetch the file in your browser but download via code may still fail. Check whether you are connected to a VPN, it works on open networks

import urllib.request
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")

dictionary = open("unixdict.txt","r")

wordList = dictionary.read().split('\n')

dictionary.close()

for word in wordList:
    if len(word)>5 and word[:3].lower()==word[-3:].lower():
        print(word)
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Quackery

  [ [] swap ]'[ swap
    witheach [
      dup nested
      unrot over do
      iff [ dip join ]
      else nip
    ] drop ]                   is filter ( [ --> [ )

  $ "unixdict.txt" sharefile drop nest$
  filter [ size 5 > ]
  filter [ 3 split -3 split nip = ]
  witheach [ echo$ cr ]
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

R

dict <- scan("https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt", what = character())
dict[nchar(dict) > 5 & substr(dict, 1, 3) == substr(dict, nchar(dict) - 2, nchar(dict))]

Racket

#lang racket

(define ((prefix-and-suffix-match? len) str)
  (let ((l (string-length str)))
    (and (>= l (* 2 len))
         (string=? (substring str 0 len)
                   (substring str (- l len))))))

(module+ main
  (filter (prefix-and-suffix-match? 3) (file->lines "../../data/unixdict.txt")))
Output:
'("antiperspirant" "calendrical" "einstein" "hotshot" "murmur" "oshkosh" "tartar" "testes")

Raku

# 20210210 Raku programming solution

my ( \L, \N, \IN ) = 5, 3, 'unixdict.txt';

for IN.IO.lines { .say if .chars > L and .substr(0,N) eq .substr(*-N,*) }
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Red

Red[]

foreach word read/lines %unixdict.txt [
    if all [
        greater? length? word 5
        equal? take/part copy word 3 take/part/last copy word 3
    ][
        print word
    ]
]
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

REXX

This REXX version doesn't care what order the words in the dictionary are in,   nor does it care what
case  (lower/upper/mixed)  the words are in,   the search for the words and vowels is   caseless.

The program verifies that the first and last three characters are, indeed, letters.

It also allows the length (3) of the first and last number of letters to be specified,   and also the minimum length of the
words to be searched on the command line (CL) as well as specifying the dictionary file identifier.

/*REXX pgm finds words in an specified dict. which have the same 1st and last 3 letters.*/
parse arg minL many iFID .                       /*obtain optional arguments from the CL*/
if minL=='' | minL=="," then minL=  6            /* "      "         "   "   "     "    */
if many=='' | many=="," then many=  3            /* "      "         "   "   "     "    */
if iFID=='' | iFID=="," then iFID='unixdict.txt' /* "      "         "   "   "     "    */

              do #=1  while lines(iFID)\==0      /*read each word in the file  (word=X).*/
              x= strip( linein( iFID) )          /*pick off a word from the input line. */
              @.#= x                             /*save:  the original case of the word.*/
              end   /*#*/
#= # - 1                                         /*adjust word count because of DO loop.*/
say copies('─', 30)     #     "words in the dictionary file: "       iFID
finds= 0                                         /*word count which have matching end.  */
                                                 /*process all the words that were found*/
     do j=1  for #;          $= @.j;    upper $  /*obtain dictionary word; uppercase it.*/
     if length($)<minL  then iterate             /*Word not long enough?   Then skip it.*/
     lhs= left($, many);     rhs= right($, many) /*obtain the left & right side of word.*/
     if \datatype(lhs || rhs, 'U')  then iterate /*are the left and right side letters? */
     if lhs \== rhs                 then iterate /*Left side match right side?  No, skip*/
     finds= finds + 1                            /*bump count of only "e" vowels found. */
     say right( left(@.j, 30),  40)              /*indent original word for readability.*/
     end        /*j*/
                                                 /*stick a fork in it,  we're all done. */
say copies('─', 30)  finds  " words found that the left "   many   ' letters match the' ,
                            "right letters which a word has a minimal length of "     minL
output   when using the default inputs:
────────────────────────────── 25104 words in the dictionary file:  unixdict.txt
          antiperspirant
          calendrical
          einstein
          hotshot
          murmur
          oshkosh
          tartar
          testes
────────────────────────────── 8  words found that the left  3  letters match the right letters which a word has a minimal length of  6

Ring

load "stdlib.ring"

cStr = read("unixdict.txt")
wordList = str2list(cStr)
num = 0

see "working..." + nl
see "Words are:" + nl

ln = len(wordList)
for n = ln to 1 step -1
    if len(wordList[n]) < 6
       del(wordList,n)
    ok
next

for n = 1 to len(wordList)
    if left(wordList[n],3) = right(wordList[n],3) 
       num = num + 1
       see "" + num + ". " + wordList[n] + nl
    ok
next

see "done..." + nl

Output:

working...
Words are:
1. antiperspirant
2. calendrical
3. einstein
4. hotshot
5. murmur
6. oshkosh
7. tartar
8. testes
done...

Ruby

words = File.readlines("unixdict.txt").map(&:chomp)
puts words.select{|w| w.end_with?(w[0,3]) && w.size > 5}
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Sidef

File("unixdict.txt").open_r.each {|word|
    word.len > 5 || next
    if (word.ends_with(word.first(3))) {
        say word
    }
}
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Swift

import Foundation

do {
    try String(contentsOfFile: "unixdict.txt", encoding: String.Encoding.ascii)
        .components(separatedBy: "\n")
        .filter{$0.count > 5 && $0.prefix(3) == $0.suffix(3)}
        .enumerated()
        .forEach{print("\($0.0 + 1). \($0.1)")}
} catch {
    print(error.localizedDescription)
}
Output:
1. antiperspirant
2. calendrical
3. einstein
4. hotshot
5. murmur
6. oshkosh
7. tartar
8. testes

VBScript

After building a program checking for the 3 letters in any order, I found people just checked the same trigraph at start and end. I modified my program so it puts an asterisk after the words in the "standard" answer. Run the ssript with CScript.

with createobject("ADODB.Stream")
  .charset ="UTF-8"
  .open
  .loadfromfile("unixdict.txt")
  s=.readtext
end with  
a=split (s,vblf)

set d= createobject("Scripting.Dictionary")
for each aa in a
  x=trim(aa)
  l=len(x)
  if l>5 then
   d.removeall
   for i=1 to 3
     m=mid(x,i,1)
     if not d.exists(m) then d.add m,null
   next
   res=true
   for i=l-2 to l
     m=mid(x,i,1)
     if not d.exists(m) then 
       res=false:exit for 
      else
        d.remove(m)
      end if        
   next 
   if res then 
     wscript.stdout.write left(x & space(15),15)
     if left(x,3)=right(x,3) then  wscript.stdout.write "*"
     wscript.stdout.writeline
    end if 
  end if
next
Output:
alfalfa
antiperspirant *
calendrical    *
cataract
deadhead
earthenware
einstein       *
encumbrance
greenberg
hannah
hotshot        *
marjoram
murmur         *
oshkosh        *
tartar         *
teammate
tenement
testes         *

Wren

Library: Wren-fmt
import "io" for File
import "/fmt" for Fmt

var wordList = "unixdict.txt" // local copy
var count = 0
File.read(wordList).trimEnd().split("\n").
    where { |w|
        return w.count > 5 && (w[0..2] == w[-3..-1])
    }.
    each { |w|
        count = count + 1
        Fmt.print("$d: $s", count, w)
    }
Output:
1: antiperspirant
2: calendrical
3: einstein
4: hotshot
5: murmur
6: oshkosh
7: tartar
8: testes

XPL0

string 0;               \Use zero-terminated strings
int  I, Ch, Len;
char Word(100); \(longest word in unixdict.txt is 22 chars)
def  LF=$0A, CR=$0D, EOF=$1A;
[FSet(FOpen("unixdict.txt", 0), ^I);    \open dictionary and set it to device 3
OpenI(3);
repeat  I:= 0;
        loop    [repeat Ch:= ChIn(3) until Ch # CR;     \remove possible CR
                if Ch=LF or Ch=EOF then quit;
                Word(I):= Ch;
                I:= I+1;
                ];
        Word(I):= 0;                    \terminate string
        Len:= I;
        if Len >= 6 then
            if Word(0) = Word(Len-3) &
               Word(1) = Word(Len-2) &
               Word(2) = Word(Len-1) then
                  [Text(0, Word);  CrLf(0)];
until   Ch = EOF;
]
Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes