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

From Rosetta Code
Content added Content deleted
(Realize in F#)
Line 31: Line 31:
</pre>
</pre>


=={{header|F_Sharp|F#}}==
<lang fsharp>
// 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")
</lang>
{{out}}
<pre>
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes
</pre>
=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: io io.encodings.ascii io.files kernel math sequences ;
<lang factor>USING: io io.encodings.ascii io.files kernel math sequences ;

Revision as of 15:17, 18 February 2021

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

Use the dictionary  unixdict.txt

Find the words which first and last three letters are equals.

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



AWK

<lang AWK>

  1. 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)

} </lang>

Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

F#

<lang fsharp> // 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") </lang>

Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Factor

<lang factor>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</lang>

Output:
antiperspirant
calendrical
einstein
hotshot
murmur
oshkosh
tartar
testes

Go

<lang 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)
       }
   }

}</lang>

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

Julia

See Alternade_words#Julia for the foreachword function. <lang julia>matchfirstlast3(word, _) = length(word) > 5 && word[1:3] == word[end-2:end] ? word : ""

foreachword("unixdict.txt", matchfirstlast3, numcols=4)</lang>

Output:
Word source: unixdict.txt

antiperspirant calendrical    einstein       hotshot
murmur         oshkosh        tartar         testes

Perl

as one-liner .. <lang perl>// 20210212 Perl programming solution

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

  1. minor variation

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

Phix

<lang Phix>function flaste(string word)

   return length(word)>5 and word[1..3]=word[-3..-1]

end function

sequence flastes = filter(get_text("demo/unixdict.txt",GT_LF_STRIPPED),flaste)

printf(1,"%d words: %s\n",{length(flastes),join(shorten(flastes,"",3))})</lang>

Output:
8 words: antiperspirant calendrical einstein hotshot murmur oshkosh tartar testes

Raku

<lang perl6># 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,*) } </lang>

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. <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*/ 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. = # - 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</lang>
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

<lang 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 </lang> Output:

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

Swift

<lang 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)

}</lang>

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

Wren

Library: Wren-fmt

<lang ecmascript>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)
   }</lang>
Output:
1: antiperspirant
2: calendrical
3: einstein
4: hotshot
5: murmur
6: oshkosh
7: tartar
8: testes