Prime words
A word is a prime word if all its individual letters (expressed as an ASCII decimal code) are primes.
A ASCII decimal code is: 65 B ASCII decimal code is: 66 C ASCII decimal code is: 67 X ASCII decimal code is: 88 Y ASCII decimal code is: 89 Z ASCII decimal code is: 90 a ASCII decimal code is: 97 b ASCII decimal code is: 98 c ASCII decimal code is: 99 x ASCII decimal code is: 120 y ASCII decimal code is: 121 z ASCII decimal code is: 122
- Task
Show here on this page every prime word in unixdict.txt.
ALGOL 68
Does not distinguish between letters and non-letter ASCII codes (as with the REXX sample). <lang algol68># find words whose character codes are primes # 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 ); # construct a sieve of primes up to the maximum character # [ 0 : max abs char ]BOOL s; FOR i TO UPB s DO s[ i ] := TRUE OD; s[ 0 ] := s[ 1 ] := FALSE; FOR i FROM 2 TO ENTIER sqrt( UPB s ) DO IF s[ i ] THEN FOR p FROM i * i BY i TO UPB s DO s[ p ] := FALSE OD FI OD; # find the prime words # INT prime count := 0; WHILE STRING word; get( input file, ( word, newline ) ); NOT at eof DO BOOL is prime := FALSE; FOR w pos FROM LWB word TO UPB word WHILE ( is prime := s[ ABS word[ w pos ] ] ) DO SKIP OD; IF is prime THEN prime count +:= 1; print( ( whole( prime count, -5 ), ": ", word, newline ) ) FI OD; close( input file )
FI</lang>
- Output:
1: a 2: aaa 3: age 4: agee 5: ak 6: am 7: ama 8: e 9: egg 10: eke 11: em 12: emma 13: g 14: ga 15: gag 16: gage 17: gam 18: game 19: gamma 20: ge 21: gee 22: gem 23: gemma 24: gm 25: k 26: keg 27: m 28: ma 29: mae 30: magma 31: make 32: mamma 33: me 34: meek 35: meg 36: q
Factor
<lang factor>USING: io.encodings.ascii io.files math.primes prettyprint sequences ;
"unixdict.txt" ascii file-lines [ [ prime? ] all? ] filter .</lang>
- Output:
{ "a" "aaa" "age" "agee" "ak" "am" "ama" "e" "egg" "eke" "em" "emma" "g" "ga" "gag" "gage" "gam" "game" "gamma" "ge" "gee" "gem" "gemma" "gm" "k" "keg" "m" "ma" "mae" "magma" "make" "mamma" "me" "meek" "meg" "q" }
FreeBASIC
<lang freebasic> dim shared as boolean prime(0 to 29) =_
{false, true, false, true, true, false, false, true, false, true, false, false, true, false,_ false, false, true, false, true, true, false, true, true, false, true, false, false, false, false}
function isprimeletter( s as string ) as boolean
dim as ubyte n = asc(s) if n mod 2 = 0 then return false return prime( (n-65)/2 )
end function
function isprimeword( s as string ) as boolean
for i as uinteger = 1 to len(s) if not isprimeletter( mid(s,i,1) ) then return false next i return true
end function
dim as string word
open "unixdict.txt" for input as #1 while true
line input #1, word if word = "" then exit while if isprimeword( word ) then print word
wend close #1 end </lang>
- Output:
a aaa age agee ak am ama e egg eke em emma g ga gag gage gam game gamma ge gee gem gemma gm k keg m ma mae magma make mamma me meek meg q
Go
<lang go>package main
import (
"bytes" "fmt" "io/ioutil" "log" "strings"
)
func isPrime(n int) bool {
if n < 2 { return false } if n%2 == 0 { return n == 2 } if n%3 == 0 { return n == 3 } d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true
}
func main() {
// cache prime runes with codepoints between 33 and 255 say var primeRunes []rune for i := 33; i < 256; i += 2 { if isPrime(i) { primeRunes = append(primeRunes, rune(i)) } } primeString := string(primeRunes) wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) fmt.Println("Prime words in", wordList, "are:") for _, bword := range bwords { word := string(bword) ok := true for _, c := range word { if !strings.ContainsRune(primeString, c) { ok = false break } } if ok { fmt.Println(word) } }
}</lang>
- Output:
Prime words in unixdict.txt are: a aaa age agee ak am ama e egg eke em emma g ga gag gage gam game gamma ge gee gem gemma gm k keg m ma mae magma make mamma me meek meg q
Julia
<lang julia>const primelettervalues = [67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113] const words = split(read("unixdict.txt", String)) foreach(println, [w for w in words if all(c -> Int(c) in primelettervalues, collect(w))])
</lang>
- Output:
a aaa age agee ak am ama e egg eke em emma g ga gag gage gam game gamma ge gee gem gemma gm k keg m ma mae magma make mamma me meek meg q
Perl
<lang perl>#!/usr/bin/perl
use strict; use warnings;
my $pat = join , grep +(1 x ord) !~ /^(11+)\1+$/, 'a'..'z', 'A'..'Z'; @ARGV = 'unixdict.txt'; print join(, grep /^[$pat]+$/, <>) =~ tr/\n/ /r =~ s/.{1,71}\K /\n/gr;</lang>
- Output:
a aaa age agee ak am ama e egg eke em emma g ga gag gage gam game gamma ge gee gem gemma gm k keg m ma mae magma make mamma me meek meg q
Phix
<lang Phix>function sap(string word) return sum(apply(word,is_prime))==length(word) end function sequence words = filter(get_text("demo/unixdict.txt",GT_LF_STRIPPED),sap) printf(1,"%d prime words found: %s\n",{length(words),join(shorten(words,"",3),", ")})</lang>
- Output:
36 prime words found: a, aaa, age, ..., meek, meg, q
Raku
Another in a continuing series of tasks that are a minimal variation of previous ones. This is essentially Smarandache prime-digital sequence using ords instead of numerical digits. Sigh.
In an effort to anticipate / head-off a rash of tiny variant tasks, a series of one-liners:
<lang perl6>my @words = 'unixdict.txt'.IO.words».fc;
sub display ($n, @n, $s = "First 20: ") {"$n;\n{$s}{@n.join: ', '}"}
- The task
say 'Number of words whose ords are all prime: ',
@words.hyper.grep({ .ords.all.is-prime }).&{display +$_, $_, };
- Twelve other minor variants
say "\nNumber of words whose ordinal sum is prime: ",
@words.grep({ .ords.sum.is-prime }).&{display +$_, .head(20)};
say "\nNumber of words whose ords are all prime, and whose ordinal sum is prime: ",
@words.hyper.grep({ .ords.all.is-prime && .ords.sum.is-prime }).&{display +$_, $_, };
say "\n\nInterpreting the words as if they were base 36 numbers:";
say "\nNumber of words whose 'digits' are all prime in base 36: ",
@words.hyper.grep({ !.contains(/\W/) && all(.comb».parse-base(36)).is-prime }).&{display +$_, $_, };
say "\nNumber of words that are prime in base 36: ",
@words.grep({ !.contains(/\W/) && :36($_).is-prime }).&{display +$_, .head(20)};
say "\nNumber of words whose base 36 digital sum is prime: ",
@words.grep({ !.contains(/\W/) && .comb».parse-base(36).sum.is-prime }).&{display +$_, .head(20)};
say "\nNumber of words that are prime in base 36, and whose digital sum is prime: ",
@words.grep({ !.contains(/\W/) && :36($_).is-prime && .comb».parse-base(36).sum.is-prime }).&{display +$_, .head(20)};
say "\nNumber of words that are prime in base 36, whose digits are all prime, and whose digital sum is prime: ",
@words.hyper.grep({ !.contains(/\W/) && all(.comb».parse-base(36)).is-prime && :36($_).is-prime && .comb».parse-base(36).sum.is-prime }).&{display +$_, $_, };
use Base::Any:ver<0.1.2+>; set-digits('a'..'z');
say "\n\nTests using a custom base 26 where 'a' through 'z' is 0 through 25 and words are case folded:";
say "\nNumber of words whose 'digits' are all prime using a custom base 26: ",
@words.hyper.grep({ !.contains(/<-alpha>/) && all(.comb».&from-base(26)).is-prime }).&{display +$_, $_, };
say "\nNumber of words that are prime using a custom base 26: ",
@words.grep({ !.contains(/<-alpha>/) && .&from-base(26).is-prime }).&{display +$_, .head(20)};
say "\nNumber of words whose digital sum is prime using a custom base 26: ",
@words.grep({ !.contains(/<-alpha>/) && .comb».&from-base(26).sum.is-prime }).&{display +$_, .head(20)};
say "\nNumber of words that are prime in a custom base 26 and whose digital sum is prime in that base: ",
@words.grep({ !.contains(/<-alpha>/) && .&from-base(26).is-prime && .comb».&from-base(26).sum.is-prime }).&{display +$_, .head(20)};
say "\nNumber of words that are prime in custom base 26, whose digits are all prime, and whose digital sum is prime: ",
@words.hyper.grep({ !.contains(/<-alpha>/) && all(.comb».&from-base(26)).is-prime && .&from-base(26).is-prime && .comb».&from-base(26).sum.is-prime }).&{display +$_, $_, };</lang>
- Output:
Number of words whose ords are all prime: 36; a, aaa, age, agee, ak, am, ama, e, egg, eke, em, emma, g, ga, gag, gage, gam, game, gamma, ge, gee, gem, gemma, gm, k, keg, m, ma, mae, magma, make, mamma, me, meek, meg, q Number of words whose ordinal sum is prime: 3778; First 20: 10th, 9th, a, a's, aau, ababa, abate, abhorred, abject, ablate, aboard, abrade, abroad, absentee, absentia, absolute, absorptive, absurd, abusive, accelerate Number of words whose ords are all prime, and whose ordinal sum is prime: 12; a, e, egg, g, gem, k, keg, m, mae, mamma, meg, q Interpreting the words as if they were base 36 numbers: Number of words whose 'digits' are all prime in base 36: 18; 2nd, 5th, 7th, b, d, h, j, n, nd, nh, nj, nv, t, tn, tnt, tv, v, vt Number of words that are prime in base 36: 1106; First 20: 10th, 1st, 2nd, 5th, 6th, 7th, abandon, abbott, abdomen, ablution, abolish, abort, abrupt, absorb, abstention, abstract, abutted, accept, accident, acid Number of words whose base 36 digital sum is prime: 4740; First 20: 10th, 3rd, 7th, aba, abacus, abalone, abase, abater, abelian, abelson, aberrant, abeyant, ablaze, abort, aboveground, abraham, abrasion, abrasive, abreact, abridge Number of words that are prime in base 36, and whose digital sum is prime: 300; First 20: 10th, 7th, abort, accident, acid, ad, adorn, adulthood, afterthought, albeit, alvin, armload, around, arragon, arraign, assassin, asteroid, astound, augean, avocation Number of words that are prime in base 36, whose digits are all prime, and whose digital sum is prime: 8; 7th, b, d, h, j, n, t, v Tests using a custom base 26 where 'a' through 'z' is 0 through 25 and words are case folded: Number of words whose 'digits' are all prime using a custom base 26: 30; c, cdc, cf, crt, ct, d, dc, dr, f, fcc, fl, ft, ftc, h, l, ltd, n, nc, ncr, nd, nh, nrc, r, rd, t, tn, tnt, ttl, tx, x Number of words that are prime using a custom base 26: 987; First 20: abhorrent, abolish, abreact, absurd, ac, act, actual, actuarial, ad, adjutant, adult, advisor, aerosol, aft, agent, agricultural, ah, aid, ajar, al Number of words whose digital sum is prime using a custom base 26: 5473; First 20: ababa, aback, abacus, abalone, abase, abater, abc, abdicate, abdomen, abe, abelian, abelson, aberrant, abeyant, ablaze, abolish, abominate, aborigine, aboveground, abraham Number of words that are prime in a custom base 26 and whose digital sum is prime in that base: 292; First 20: abolish, abreact, absurd, ac, ad, adjutant, adult, agricultural, ah, aid, al, allah, allied, altar, an, annal, ar, arclength, argonaut, asocial Number of words that are prime in custom base 26, whose digits are all prime, and whose digital sum is prime: 9; c, d, f, h, l, n, r, t, x
REXX
No attempt was made to exclude any "word" if it contained any non-letter (Latin alphabet) characters. <lang rexx>/*REXX pg finds words whose ASCII code for its letters (within an identified dictionary)*/ parse arg iFID . /*obtain optional arguments from the CL*/ if iFID== | iFID=="," then iFID='unixdict.txt' /*Not specified? Then use the default.*/ call genPrimes /*generate all primes less than 256. */ say 'reading the dictionary file: ' iFID /*show which dictionary is being read. */ say
- = 0 /*count of prime words found (so far).*/
do recs=0 while lines(iFID)\==0 /*read each word in the file (word=X).*/ x= strip( linein( iFID) ) /*pick off a word from the input line. */
do j=1 for length(x) /*examine each letter (char) in word. */ _= c2d( substr(x, j, 1) ) /*convert each letter to a decimal num.*/ if \@._ then iterate recs /*is this ASCII code letter a prime ? */ end /*j*/ say x /*display a prime word to the terminal.*/ #= # + 1 /*bump the count of prime words. */ end /*recs*/ /* [↑] semaphore name is uppercased. */
say say copies('─', 30) recs "usable words in the dictionary file: " iFID say 'found ' # " prime words in the dictionary." exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ genPrimes: p= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 ,
67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 , 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 @.= 0; do j=1 for words(p); _= word(p, j); @._= 1; end /*j*/; return</lang>
- output when using the default input:
reading the dictionary file: unixdict.txt a aaa age agee ak am ama e egg eke em emma g ga gag gage gam game gamma ge gee gem gemma gm k keg m ma mae magma make mamma me meek meg q ────────────────────────────── 25104 usable words in the dictionary file: unixdict.txt found 36 prime words in the dictionary.
Ring
<lang ring> load "stdlib.ring"
cStr = read("unixdict.txt") wordList = str2list(cStr) Words = []
for n = 1 to len(wordList)
num = 0 len = len(wordList[n]) for m = 1 to len asc = ascii(wordList[n][m]) if isprime(asc) num = num + 1 else exit ok next if num = len add(Words,wordList[n]) ok
next
see "Prime words are:" + nl see Words </lang> Output:
Prime words are: a aaa age agee ak am ama e egg eke em emma g ga gag gage gam game gamma ge gee gem gemma gm k keg m ma mae magma make mamma me meek meg q
Wren
<lang ecmascript>import "io" for File import "/math" for Int import "/trait" for Stepped
// cache prime characters with codepoints between 33 and 255 say var primeChars = [] for (i in Stepped.new(33..255, 2)) {
if (Int.isPrime(i)) primeChars.add(String.fromCodePoint(i))
} var wordList = "unixdict.txt" // local copy var words = File.read(wordList).trimEnd().split("\n") System.print("Prime words in %(wordList) are:") for (word in words) {
if (word.all { |c| primeChars.contains(c) }) System.print(word)
}</lang>
- Output:
Prime words in unixdict.txt are: a aaa age agee ak am ama e egg eke em emma g ga gag gage gam game gamma ge gee gem gemma gm k keg m ma mae magma make mamma me meek meg q