task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ruby
Ruby
dict = File.readlines("unixdict.txt").collect(&:strip) i = 0 res = dict.collect(&:reverse).sort.select do |z| i += 1 while z > dict[i] and i < dict.length-1 z == dict[i] and z < z.reverse end puts "There are #{res.length} semordnilaps, of which the following are 5:" res.take(5).each {|z| puts "#{z} #{z.reverse}"}
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
SEDOL[Code_?(Function[v,StringFreeQ[v,{"A","E","I","O","U"}]])]:= Code<>ToString[10-Mod[ToExpression[Quiet[Flatten[Characters[Code] /.x_?LetterQ->(ToCharacterCode[x]-55)]]].{1,3,1,7,3,9},10]] Scan[Print[SEDOL[#]] &, {"710889","B0YBKJ","406566","B0YBLH","228276","B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030","DUMMY"}]
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#MUMPS
MUMPS
SEDOL NEW A,B SEDOL1 READ !,"Enter the first 6 digits of a SEDOL: ",A SET B=$$SEDOLCHK(A) WRITE !,$SELECT($LENGTH(B)=1:"Full SEDOL is "_A_B,1:B) GOTO SEDOL1 QUIT SEDOLCHK(STOCK) NEW WT,VAL,I,CHK,C,FLAG SET WT="1317391",VAL=0,FLAG=0 FOR I=1:1:6 SET C=$$TOUPPER($EXTRACT(STOCK,I)),VAL=VAL+($$SEDVAL(C)*$EXTRACT(WT,I)) SET:"AEIOUaeiou"[C FLAG=1 SET:$LENGTH(STOCK)'=6 FLAG=1 KILL WT,I,CHK,C QUIT $SELECT(FLAG:"INVALID",'FLAG:(10-(VAL#10))#10) SEDVAL(X) QUIT $SELECT($ISVALIDNUM(X):X,1:$ASCII(X)-$ASCII("@")+9) TOUPPER(X) NEW UP,LO SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ",LO="abcdefghijklmnopqrstuvwxyz" QUIT $TRANSLATE(X,LO,UP)
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Picat
Picat
go =>   println([f(I) : I in 1..22]), nl, check(1_000_000), nl.   % The formula f(N) = N + floor(1/2 + sqrt(N)).   check(Limit) => Squares = new_map([I*I=1:I in 1..sqrt(Limit)]), Check = [[I,T] : I in 1..Limit-1, T=f(I), Squares.has_key(T)], println(check=Check.len).
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#PicoLisp
PicoLisp
(de sqfun (N) (+ N (sqrt N T)) ) # 'sqrt' rounds when called with 'T'   (for I 22 (println I (sqfun I)) )   (for I 1000000 (let (N (sqfun I) R (sqrt N)) (when (= N (* R R)) (prinl N " is square") ) ) )
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Maxima
Maxima
/* illustrating some functions on sets; names are self-explanatory */   a: {1, 2, 3, 4}; {1, 2, 3, 4}   b: {2, 4, 6, 8}; {2, 4, 6, 8}   intersection(a, b); {2, 4}   union(a, b); {1, 2, 3, 4, 6, 8}   powerset(a); {{}, {1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 4}, {1, 3}, {1, 3, 4}, {1, 4}, {2}, {2, 3}, {2, 3, 4}, {2, 4}, {3}, {3, 4}, {4}}   set_partitions(a); {{{1}, {2}, {3}, {4}}, {{1}, {2}, {3, 4}}, {{1}, {2, 3}, {4}}, {{1}, {2, 3, 4}}, {{1}, {2, 4}, {3}}, {{1, 2}, {3}, {4}}, {{1, 2}, {3, 4}}, {{1, 2, 3}, {4}}, {{1, 2, 3, 4}}, {{1, 2, 4}, {3}}, {{1, 3}, {2}, {4}}, {{1, 3}, {2, 4}}, {{1, 3, 4}, {2}}, {{1, 4}, {2}, {3}}, {{1, 4}, {2, 3}}}   setdifference(a, b); {1, 3}   emptyp(a); false   elementp(2, a); true   cardinality(a); 4   cartesian_product(a, b); {[1, 2], [1, 4], [1, 6], [1, 8], [2, 2], [2, 4], [2, 6], [2, 8], [3, 2], [3, 4], [3, 6], [3, 8], [4, 2], [4, 4], [4, 6], [4, 8]}   subsetp(a, b); false   symmdifference(a, b); {1, 3, 6, 8}   partition_set(union(a, b), evenp); [{1, 3}, {2, 4, 6, 8}]   c: setify(makelist(fib(n), n, 1, 20)); {1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765}   equiv_classes(c, lambda([m, n], mod(m - n, 3) = 0)); {{1, 13, 34, 55, 610, 1597, 2584}, {2, 5, 8, 89, 233, 377, 4181}, {3, 21, 144, 987, 6765}}   disjointp(a, b); false   adjoin(7, a); {1, 2, 3, 4, 7}   a; {1, 2, 3, 4}   disjoin(1, a); {2, 3, 4}   a; {1, 2, 3, 4}   subset(c, primep); {2, 3, 5, 13, 89, 233, 1597}   permutations(a); {[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]}   setequalp(a, b); false
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#EDSAC_order_code
EDSAC order code
  [Sieve of Eratosthenes] [EDSAC program. Initial Orders 2]   [Memory usage: 56..87 library subroutine P6, for printing 88..222 main program 224..293 mask table: 35 long masks; each has 34 1's and a single 0 294..1023 array of bits for integers 2, 3, 4, ..., where bit is changed from 1 to 0 when integer is crossed out. The address of the mask table must be even, and clear of the main program. To change it, just change the value after "T47K" below. The address of the bit array will then be changed automatically.]   [Subroutine M3, prints header, terminated by blank row of tape. It's an "interlude", which runs and then gets overwritten.] PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF @&*SIEVE!OF!ERATOSTHENES!#2020 @&*BASED!ON!CODE!BY!EIITI!WADA!#2001 ..PZ   [Subroutine P6, prints strictly positive integer. 32 locations; working locations 1, 4, 5.] T 56 K GKA3FT25@H29@VFT4DA3@TFH30@S6@T1FV4DU4DAFG26@TFTF O5FA4DF4FS4FL4FT4DA1FS3@G9@EFSFO31@E20@J995FJF!F   [Store address of mask table in (say) location 47 (chosen because its code letter M is first letter of "Mask"). Address must be even and clear of main program.] T 47 K P 224 F [<-------- address of mask table]   [Main program] T 88 K [Define load address for main program. Must be even, because of long values at start.] G K [set @ (theta) for relative addressing]   [Long constants] T#Z PF TZ [clears sandwich digit between 0 and 1] [0] PD PF [long value 1; also low word = short 1] T2#Z PF T2Z [clears sandwich digit between 2 and 3] [2] PF K4096F [long value 1000...000 binary; also high word = teleprinter null]   [Short constants The address in the following C order is the (exclusive) end of the bit table. Must be even: max = 1024, min = M + 72 where M is address of mask table set up above. Usually 1024, but may be reduced, e.g. to make the program run faster.] [4] C1024 D [or e.g. C 326 D to make it much faster] [5] U F ['U' = 'T' - 'C'] [6] K F ['K' = 'S' - 'C'] [7] H #M [H order for start of mask table] [8] H 70#M [used to test for end of mask table] [9] P 2 F [constant4, or 2 in address field] [10] P 70 F [constant 140, or 70 in address field] [11] @ F [carriage return] [12] & F [line feed]   [Short variables] [13] P 1 F [p = number under test Let p = 35*q + r, where 0 <= r < 35] [14] P F [4*q] [15] P 4 F [4*r]   [Initial values of orders; required only for optional code below.] [16] C 70#M [initial value of a variable C order] [17] T #M [initial value of a variable T order] [18] T 70#M [initial value of a variable T order]   [19] [Enter with acc = 0]   [Optional code to do some initializing at run time. This code allows the program to run again without being loaded again.] A 7 @ [initial values of variable orders] T 65 @ A 16 @ T 66 @ A 17 @ T 44 @ A 18 @ T 52 @   [Initialize variables] A @ [load 1 (short)] L D [shift left 1] U 13 @ [p := 2] L 1 F [shift left 2] T 15 @ [4*r := 8] T 14 @ [4*q := 0] [End of optional code]   [Make table of 35 masks 111...110, 111...101, ..., 011...111 Treat the mask 011...111 separately to avoid accumulator overflow. Assume acc = 0 here.] S #@ [acc all 1's] S 2 #@ [acc := 0111...111] [35] T 68 #M [store at high end of mask table] S #@ [acc := -1] L D [make mask 111...1110] G 43 @ [jump to store it [Loop shifting the mask right and storing the result in the mask table. Uses first entry of bit array as temporary store.] [39] T F [clear acc] A 70 #M [load previous mask] L D [shift left] A #@ [add 1] [43] U 70 #M [update current mask] [44] T #M [store it in table (order changed at run time)] A 44 @ [load preceding T order] A 9 @ [inc address by 2] U 44 @ [store back] S 35 @ [reached high entry yet?] G 39 @ [loop back if not] [Mask table is now complete]   [Initialize bit array: no numbers crossed out, so all bits are 1] [50] T F [clear acc] S #@ [subtract long 1, make top 35 bits all 1's] [52] T 70 #M [store as long value, both words all 1's (order changed at run time)] A 52 @ [load preceding order] A 9 @ [add 2 to address field] U 52 @ [and store back] S 5 @ [convert to C order with same address (*)] S 4 @ [test for end of bit array] G 50 @ [loop until stored all 1's in bit table] [(*) Done so that end of bit table can be stored at one place only in list of constants, i.e. 'C m D' only, not 'T m D' as well.]   [Start of main loop.] [Testing whether number has been crossed out] [59] T F [acc := 0] A 66 @ [deriving S order from C order] A 6 @ T 64 @ S #@ [acc := -1] [64] S F [acc := 1's complement of bit-table entry (order changed at run time)] [65] H #M [mult reg := start of mask array (order changed at run time)] [66] C 70#M [acc := -1 iff p (current number) is crossed out (order changed at run time)] [The next order is to avoid accumulator overflow if acc = max positive number] E 70 @ [if acc >= 0, jump to process new prime] A #@ [if acc < 0, add 1 to test for -1] E 106 @ [if acc now >= 0 number is crossed out, jump to test next] [Here if new prime found. Send it to the teleprinter] [70] O 11 @ [print CR] O 12 @ [print LF] T F [clear acc] A 13 @ [load prime] T F [store in C(0) for print routine] A 75 @ [for subroutine return] G 56 F [print prime]   [Cross out its multiples by setting corresponding bits to 0] A 65 @ [load H order above] T 102 @ [plant in crossing-out loop] A 66 @ [load C order above] T1 03 @ [plant in crossing-out loop]   [Start of crossing-out loop. Here acc must = 0] [81] A 102 @ [load H order below] A 15 @ [inc address field by 2*r, where p = 35q + r] U 102 @ [update H order] S 8 @ [compare with 'H 70 #M'] G 93 @ [skip if not gone beyond end of mask table] T F [wrap mask address and inc address in bit tsble] A 102 @ [load H order below] S 10 @ [reduce mask address by 70] T 102 @ [update H order] A 103 @ [load C order below] A 9 @ [add 2 to address] T 103 @ [update C order] [93] T F [clear acc] A 103 @ [load C order below] A 14 @ [inc address field by 2*q, where p = 35q + r] U 103 @ [update C order] S 4 @ [test for end of bit array] E 106 @ [if finished crossing out, loop to test next number] A 4 @ [restore C order] A 5 @ [make T order with same address] T 104 @ [store below]   [Execute the crossing-out orders created above] [102] X F [mult reg := mask (order created at run time)] [103] X F [acc := logical and with bit-table entry (order created at run time)] [104] X F [update entry (order created at run time)] E 81 @ [loop back with acc = 0]   [106] T F [clear acc] A 13 @ [load p = number under test] A @ [add 1 (single)] T 13 @ [update] A 15 @ [load 4*r, where p = 35q + r] A 9 @ [add 4] U 15 @ [store back (r inc'd by 1)] S 10 @ [is 4*r now >= 140?] G 119 @ [no, skip] T 15 @ [yes, reduce 4*r by 140] A 14 @ [load 4*q] A 9 @ [add 4] T 14 @ [store back (q inc'd by 1)] [119] T F [clear acc] A 65 @ [load 'H ... D' order, which refers to a mask] A 9 @ [inc mask address by 2] U 65 @ [update order] S 8 @ [over end of mask table?] G 59 @ [no, skip wrapround code] A 7 @ [yes, add constant to wrap round] T 65 @ [update H order] A 66 @ A 9 @ [inc address by 2] U 66 @ [and store back] S 4 @ [test for end, as defined by C order at start] G 59 @ [loop back if not at end]   [Finished whole thing] [132] O 3 @ [output null to flush teleprinter buffer] Z F [stop] E 19 Z [address to start execution] P F [acc = 0 at start]  
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#zkl
zkl
fcn drawPat(x0,y0,s,img){ // Draw 3x3 pattern with hole in middle foreach y,x in (3,3){ if(x.isEven or y.isEven){ // don't draw middle pattern if(s>1) self.fcn(x*s + x0, y*s + y0, s/3, img); // recurse else img[x + x0, y + y0]=0xff0000; // red } } }
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Rust
Rust
use std::collections::HashSet; use std::fs::File; use std::io::{self, BufRead}; use std::iter::FromIterator;   fn semordnilap(filename: &str) -> std::io::Result<()> { let file = File::open(filename)?; let mut seen = HashSet::new(); let mut count = 0; for line in io::BufReader::new(file).lines() { let mut word = line?; word.make_ascii_lowercase(); let rev = String::from_iter(word.chars().rev()); if seen.contains(&rev) { if count < 5 { println!("{}\t{}", word, rev); } count += 1; } else { seen.insert(word); } } println!("\nSemordnilap pairs found: {}", count); Ok(()) }   fn main() { match semordnilap("unixdict.txt") { Ok(()) => {} Err(error) => eprintln!("{}", error), } }
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Scala
Scala
val wordsAll = scala.io.Source. fromURL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"). getLines().map(_.toLowerCase).toIndexedSeq     /** * Given a sequence of lower-case words return a sub-sequence * of matches containing the word and its reverse if the two * words are different. */ def semordnilap( words:IndexedSeq[String] ) : IndexedSeq[(String,String)] = {   words. zipWithIndex. // index will be needed to eliminate duplicate filter { case (w,i) => val j = words.indexOf(w.reverse) // eg. (able,62) and (elba,7519) i < j && w != w.reverse // save the matches which are not palindromes }. map { case (w,_) => (w,w.reverse) // drop the index } }   val ss = semordnilap(wordsAll)   { println( s"${ss.size} matches, including: \n" ) println( ss.take(5).mkString( "\n" ) ) }
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Nim
Nim
proc c2v(c: char): int = assert c notin "AEIOU" if c < 'A': ord(c) - ord('0') else: ord(c) - ord('7')   const weight = [1, 3, 1, 7, 3, 9]   proc checksum(sedol: string): char = var val = 0 for i, ch in sedol: val += c2v(ch) * weight[i] result = chr((10 - val mod 10) mod 10 + ord('0'))   for sedol in ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]: echo sedol, " → ", sedol & checksum(sedol)
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#OCaml
OCaml
let char2value c = assert (not (String.contains "AEIOU" c)); match c with | '0'..'9' -> int_of_char c - int_of_char '0' | 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10 | _ -> assert false   let sedolweight = [1;3;1;7;3;9]   let explode s = s |> String.to_seq |> List.of_seq   let checksum sedol = let tmp = List.fold_left2 (fun sum ch weight -> sum + char2value ch * weight) 0 (explode sedol) sedolweight in string_of_int ((10 - (tmp mod 10)) mod 10) ;;   List.iter (fun sedol -> print_endline (sedol ^ checksum sedol)) [ "710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL"; "557910"; "B0YBKR"; "585284"; "B0YBKT" ]
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#PL.2FI
PL/I
  put skip edit ((n, n + floor(sqrt(n) + 0.5) do n = 1 to n)) (skip, 2 f(5));  
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#PostScript
PostScript
/nonsquare { dup sqrt .5 add floor add } def /issquare { dup sqrt floor dup mul eq } def   1 1 22 { nonsquare = } for   1 1 1000 { dup nonsquare issquare { (produced a square!) = = exit } if pop } for  
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Nanoquery
Nanoquery
class set declare internal_list   def set() internal_list = list() end def set(list) internal_list = list end   def append(value) if not value in internal_list internal_list.append(value) end return this end def contains(value) return value in internal_list end def difference(other) diff = list() for value in this.internal_list diff.append(value) end   for i in range(len(diff) - 1, 0) if diff[i] in other.internal_list diff.remove(i) end end   return new(set, diff) end def operator=(other) for value in other.internal_list if not value in this.internal_list return false end end return true end def intersection(other) intersect = list() for value in this.internal_list if other.contains(value) intersect.append(value) end end return new(set, intersect) end def subset(other) for value in this.internal_list if not value in other.internal_list return false end end return true end def union(other) u = list()   for value in this.internal_list u.append(value) end   for value in other.internal_list if not value in u u.append(value) end end   return new(set, u) end   def toString() return str(this.internal_list) end end
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Eiffel
Eiffel
class APPLICATION   create make   feature make -- Run application. do across primes_through (100) as ic loop print (ic.item.out + " ") end end   primes_through (a_limit: INTEGER): LINKED_LIST [INTEGER] -- Prime numbers through `a_limit' require valid_upper_limit: a_limit >= 2 local l_tab: ARRAY [BOOLEAN] do create Result.make create l_tab.make_filled (True, 2, a_limit) across l_tab as ic loop if ic.item then Result.extend (ic.target_index) across ((ic.target_index * ic.target_index) |..| l_tab.upper).new_cursor.with_step (ic.target_index) as id loop l_tab [id.item] := False end end end end end
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Seed7
Seed7
$ include "seed7_05.s7i"; include "gethttp.s7i";   const func string: reverse (in string: word) is func result var string: drow is ""; local var integer: index is 0; begin for index range length(word) downto 1 do drow &:= word[index]; end for; end func;   const proc: main is func local var array string: wordList is 0 times ""; var set of string: words is (set of string).value; var string: word is ""; var string: drow is ""; var integer: count is 0; begin wordList := split(lower(getHttp("www.puzzlers.org/pub/wordlists/unixdict.txt")), "\n"); for word range wordList do drow := reverse(word); if drow not in words then incl(words, word); else if count < 5 then writeln(word <& " " <& drow); end if; incr(count); end if; end for; writeln; writeln("Semordnilap pairs: " <& count); end func;
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Sidef
Sidef
var c = 0 var seen = Hash()   ARGF.each { |line| line.chomp! var r = line.reverse ((seen{r} := 0 ++) && (c++ < 5) && say "#{line} #{r}") -> || (seen{line} := 0 ++) }   say c
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Oforth
Oforth
func: sedol(s) [ 1, 3, 1, 7, 3, 9 ] s zipWith(#[ dup isDigit ifTrue: [ '0' - ] else: [ 'A' - 10 + ] * ]) sum 10 mod 10 swap - 10 mod StringBuffer new s << swap '0' + <<c ;
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Pascal
Pascal
program Sedols(output);   function index(c: char): integer; const alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var i: integer; begin index := 0; for i := low(alpha) to high(alpha) do if c = alpha[i] then index := i; end;   function checkdigit(c: string): char; const weight: array [1..6] of integer = (1, 3, 1, 7, 3, 9); var i, sum: integer; begin sum := 0; for i := 1 to 6 do sum := sum + (index(c[i]) - 1) * weight[i]; checkdigit := char((10 - (sum mod 10)) mod 10 + 48); end;   const codes: array [1..11] of string = ('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT', 'B00030');   var seforl: string; i: integer;   begin for i := low(codes) to high(codes) do begin seforl := codes[i]; setlength(seforl, 7); seforl[7] := checkdigit(codes[i]); writeln(codes[i], ' -> ', seforl); end; end.
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#PowerShell
PowerShell
filter Get-NonSquare { return $_ + [Math]::Floor(1/2 + [Math]::Sqrt($_)) }
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#PureBasic
PureBasic
OpenConsole() For a = 1 To 22 ; Integer, so no floor needed tmp = 1 / 2 + Sqr(a) Print(Str(a + tmp) + ", ") Next PrintN("") PrintN("Starting check till one million") For a = 1 To 1000000 value.d = a + Round((1 / 2 + Sqr(a)), #PB_Round_Down) root = Sqr(value) If value - root*root = 0 found + 1 If found < 20 PrintN("Found a square! " + Str(value)) ElseIf found = 20 PrintN("And more") EndIf EndIf Next If found PrintN(Str(found) + " Squares found, see above") Else PrintN("No squares, all ok") EndIf ; Wait for enter Input()
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Nemerle
Nemerle
using System.Console; using Nemerle.Collections;   module RCSet { HasSubset[T](this super : Set[T], sub : Set[T]) : bool { super.ForAll(x => sub.Contains(x)) }   Main() : void { def names1 = Set(["Bob", "Billy", "Tom", "Dick", "Harry"]); def names2 = Set(["Bob", "Mary", "Alice", "Louisa"]); //def names3 = Set(["Bob", "Bob"]); // unfortunately, duplicated elements are not well handled by the stock // implementation, this statement would throw an ArgumentException def elem = names1.Contains("Bob"); // element test def names1u2 = names1.Sum(names2); // union def names1d2 = names1.Subtract(names2); // difference def names1i2 = names1.Intersect(names2); // intersection def same = names1.Equals(names2); // equality def sub12 = names1.HasSubset(names2); // subset   WriteLine($"$names1u2\n$names1d2\n$names1i2"); WriteLine($"$same\t$sub12"); } }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Elixir
Elixir
defmodule Prime do def eratosthenes(limit \\ 1000) do sieve = [false, false | Enum.to_list(2..limit)] |> List.to_tuple check_list = [2 | Stream.iterate(3, &(&1+2)) |> Enum.take(round(:math.sqrt(limit)/2))] Enum.reduce(check_list, sieve, fn i,tuple -> if elem(tuple,i) do clear_num = Stream.iterate(i*i, &(&1+i)) |> Enum.take_while(fn x -> x <= limit end) clear(tuple, clear_num) else tuple end end) end   defp clear(sieve, list) do Enum.reduce(list, sieve, fn i, acc -> put_elem(acc, i, false) end) end end   limit = 199 sieve = Prime.eratosthenes(limit) Enum.each(0..limit, fn n -> if x=elem(sieve, n), do: :io.format("~3w", [x]), else: :io.format(" .") if rem(n+1, 20)==0, do: IO.puts "" end)
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#SNOBOL4
SNOBOL4
  * Program: semordnilap.sbl * To run: sbl semordnilap.sbl < unixdict.txt * Description: A semordnilap is a word (or phrase) that spells * a different word (or phrase) backward. "Semordnilap" * is a word that itself is a semordnilap. * Example: lager and regal * Reads file unixdict.txt * Comment: Tested using the Spitbol for Linux version of SNOBOL4   output = "Some Semordnilap Pairs from File unixdict.txt" atable = table(25200,,-1) ntable = table(25200,,-2)   * Read dictionary file into memory in1 word = input :f(p1) count = count + 1 atable[word] = word ntable[count] = word :(in1)   * Process dictionary to find unique semordnilaps p1 i = lt(i,count) i + 1 :f(p2) newword = atable[reverse(ntable[i])] leq(newword,-1) :s(p1) ident(ntable[i],newword) :s(p1) output = lt(outcount,5) ntable[i] ', ' newword atable[ntable[i]] = atable[newword] = -1 outcount = outcount + 1 :(p1) p2 output = 'The number of semordnilap pairs is: ' outcount END  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Stata
Stata
set seed 17760704 import delimited http://www.puzzlers.org/pub/wordlists/unixdict.txt, clear save temp, replace replace v1=strreverse(v1) merge 1:1 v1 using temp, nogen keep(3) drop if v1>=strreverse(v1) count 158 sample 5, count gen v2=strreverse(v1) list, noheader noobs +-------------+ | evil live | | pat tap | | at ta | | nit tin | | ku uk | +-------------+
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Perl
Perl
use List::Util qw(sum); use POSIX qw(strtol);   sub zip(&\@\@) { my $f = shift; my @a = @{shift()}; my @b = @{shift()}; my @result; push(@result, $f->(shift @a, shift @b)) while @a && @b; return @result; }   my @weights = (1, 3, 1, 7, 3, 9); sub sedol($) { my $s = shift; $s =~ /[AEIOU]/ and die "No vowels"; my @vs = map {(strtol $_, 36)[0]} split //, $s; my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights); my $check_digit = (10 - $checksum % 10) % 10; return $s . $check_digit; }   while (<>) { chomp; print sedol($_), "\n"; }
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Python
Python
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n))   >>> # first 22 values has no squares: >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27   >>> # The following check shows no squares up to one million: >>> def is_square(n): return sqrt(n).is_integer()   >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares))   StopIteration:
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Nim
Nim
var # creation s = {0, 3, 5, 10} t = {3..20, 50..55}   if 5 in s: echo "5 is in!" # element test   var c = s + t # union d = s * t # intersection e = s - t # difference   if s <= t: echo "s ⊆ t" # subset   if s < t: echo "s ⊂ t" # strong subset   if s == t: echo "s = s" # equality   s.incl(4) # add 4 to set s.excl(5) # remove 5 from set
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Elm
Elm
module Main exposing (main)   import Browser exposing (element) import Task exposing (Task, succeed, perform, andThen) import Html exposing (Html, div, text) import Time exposing (now, posixToMillis)   type CIS a = CIS a (() -> CIS a)   uptoCIS2List : comparable -> CIS comparable -> List comparable uptoCIS2List n cis = let loop (CIS hd tl) lst = if hd > n then List.reverse lst else loop (tl()) (hd :: lst) in loop cis []   countCISTo : comparable -> CIS comparable -> Int countCISTo n cis = let loop (CIS hd tl) cnt = if hd > n then cnt else loop (tl()) (cnt + 1) in loop cis 0   primesTreeFolding : () -> CIS Int primesTreeFolding() = let merge (CIS x xtl as xs) (CIS y ytl as ys) = case compare x y of LT -> CIS x <| \ () -> merge (xtl()) ys EQ -> CIS x <| \ () -> merge (xtl()) (ytl()) GT -> CIS y <| \ () -> merge xs (ytl()) pmult bp = let adv = bp + bp pmlt p = CIS p <| \ () -> pmlt (p + adv) in pmlt (bp * bp) allmlts (CIS bp bptl) = CIS (pmult bp) <| \ () -> allmlts (bptl()) pairs (CIS frst tls) = let (CIS scnd tlss) = tls() in CIS (merge frst scnd) <| \ () -> pairs (tlss()) cmpsts (CIS (CIS hd tl) tls) = CIS hd <| \ () -> merge (tl()) <| cmpsts <| pairs (tls()) testprm n (CIS hd tl as cs) = if n < hd then CIS n <| \ () -> testprm (n + 2) cs else testprm (n + 2) (tl()) oddprms() = CIS 3 <| \ () -> testprm 5 <| cmpsts <| allmlts <| oddprms() in CIS 2 <| \ () -> oddprms()   type alias Model = ( Int, String, String )   type Msg = Start Int | Done ( Int, Int )   cLIMIT : Int cLIMIT = 1000000   timemillis : () -> Task Never Int timemillis() = now |> andThen (\ t -> succeed (posixToMillis t))   test : Int -> Cmd Msg test lmt = let cnt = countCISTo lmt (primesTreeFolding()) -- (soeDict()) in timemillis() |> andThen (\ t -> succeed ( t, cnt )) |> perform Done   myupdate : Msg -> Model -> (Model, Cmd Msg) myupdate msg mdl = let (strttm, oldstr, _) = mdl in case msg of Start tm -> ( ( tm, oldstr, "Running..." ), test cLIMIT ) Done (stptm, answr) -> ( ( stptm, oldstr, "Found " ++ String.fromInt answr ++ " primes to " ++ String.fromInt cLIMIT ++ " in " ++ String.fromInt (stptm - strttm) ++ " milliseconds." ) , Cmd.none )   myview : Model -> Html msg myview mdl = let (_, str1, str2) = mdl in div [] [ div [] [text str1], div [] [text str2] ]   main : Program () Model Msg main = element { init = \ _ -> ( ( 0 , "The primes up to 100 are: " ++ (primesTreeFolding() |> uptoCIS2List 100 |> List.map String.fromInt |> String.join ", ") ++ "." , "" ), perform Start (timemillis()) ) , update = myupdate , subscriptions = \ _ -> Sub.none , view = myview }
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#SuperCollider
SuperCollider
( var text, words, sdrow, semordnilap, selection; File.use("unixdict.txt".resolveRelative, "r", { |f| x = text = f.readAllString }); words = text.split(Char.nl).collect { |each| each.asSymbol }; sdrow = text.reverse.split(Char.nl).collect { |each| each.asSymbol }; semordnilap = sect(words, sdrow); // converted to symbols so intersection is possible semordnilap = semordnilap.collect { |each| each.asString }; "There are % in unixdict.txt\n".postf(semordnilap.size); "For example those, with more than 3 characters:".postln; selection = semordnilap.select { |each| each.size >= 4 }.scramble.keep(4); selection.do { |each| "% %\n".postf(each, each.reverse); }; )
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Phix
Phix
type string6(object s) return string(s) and length(s)=6 end type type sedolch(integer ch) return ch>='0' and ch<='Z' and (ch<='9' or ch>='A') and not find(ch,"AEIOU") end type function sedol(string6 t) sedolch c integer s = 0 for i=1 to 6 do c = t[i] s += iff(c>='A'?c-'A'+10:c-'0')*{1,3,1,7,3,9}[i] end for return t & mod(10-mod(s,10),10)+'0' end function constant tests = {"710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"} for i=1 to length(tests) do ?sedol(tests[i]) end for
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Quackery
Quackery
$ "bigrat.qky" loadfile   [ dup n->v 2 vsqrt drop 1 2 v+ / + ] is nonsquare ( n --> n )   [ sqrt nip 0 = ] is squarenum ( n --> b )   say "Non-squares: " 22 times [ i^ 1+ nonsquare echo sp ] cr cr 0 999999 times [ i^ 1+ nonsquare squarenum if 1+ ] echo say " square numbers found"
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#R
R
nonsqr <- function(n) n + floor(1/2 + sqrt(n)) nonsqr(1:22)
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   int main (int argc, const char *argv[]) { @autoreleasepool {   NSSet *s1 = [NSSet setWithObjects:@"a", @"b", @"c", @"d", @"e", nil]; NSSet *s2 = [NSSet setWithObjects:@"b", @"c", @"d", @"e", @"f", @"h", nil]; NSSet *s3 = [NSSet setWithObjects:@"b", @"c", @"d", nil]; NSSet *s4 = [NSSet setWithObjects:@"b", @"c", @"d", nil]; NSLog(@"s1: %@", s1); NSLog(@"s2: %@", s2); NSLog(@"s3: %@", s3); NSLog(@"s4: %@", s4);   // Membership NSLog(@"b in s1: %d", [s1 containsObject:@"b"]); NSLog(@"f in s1: %d", [s1 containsObject:@"f"]);   // Union NSMutableSet *s12 = [NSMutableSet setWithSet:s1]; [s12 unionSet:s2]; NSLog(@"s1 union s2: %@", s12);   // Intersection NSMutableSet *s1i2 = [NSMutableSet setWithSet:s1]; [s1i2 intersectSet:s2]; NSLog(@"s1 intersect s2: %@", s1i2);   // Difference NSMutableSet *s1_2 = [NSMutableSet setWithSet:s1]; [s1_2 minusSet:s2]; NSLog(@"s1 - s2: %@", s1_2);   // Subset of NSLog(@"s3 subset of s1: %d", [s3 isSubsetOfSet:s1]);   // Equality NSLog(@"s3 = s4: %d", [s3 isEqualToSet:s4]);   // Cardinality NSLog(@"size of s1: %lu", [s1 count]);   // Has intersection (not disjoint) NSLog(@"does s1 intersect s2? %d", [s1 intersectsSet:s2]);   // Adding and removing elements from a mutable set NSMutableSet *mut_s1 = [NSMutableSet setWithSet:s1]; [mut_s1 addObject:@"g"]; NSLog(@"mut_s1 after adding g: %@", mut_s1); [mut_s1 addObject:@"b"]; NSLog(@"mut_s1 after adding b again: %@", mut_s1); [mut_s1 removeObject:@"c"]; NSLog(@"mut_s1 after removing c: %@", mut_s1);   } return 0; }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Emacs_Lisp
Emacs Lisp
(defun sieve-set (limit) (let ((xs (make-vector (1+ limit) 0))) (cl-loop for i from 2 to limit when (zerop (aref xs i)) collect i and do (cl-loop for m from (* i i) to limit by i do (aset xs m 1)))))
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Swift
Swift
guard let data = try? String(contentsOfFile: "unixdict.txt") else { fatalError() }   let words = Set(data.components(separatedBy: "\n")) let pairs = words .map({ ($0, String($0.reversed())) }) .filter({ $0.0 < $0.1 && words.contains($0.1) })   print("Found \(pairs.count) pairs") print("Five examples: \(pairs.prefix(5))")
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#PHP
PHP
function char2value($c) { assert(stripos('AEIOU', $c) === FALSE); return intval($c, 36); }   $sedolweight = array(1,3,1,7,3,9);   function checksum($sedol) { global $sedolweight; $tmp = array_sum(array_map(create_function('$ch, $weight', 'return char2value($ch) * $weight;'), str_split($sedol), $sedolweight) ); return strval((10 - ($tmp % 10)) % 10); }   foreach (array('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT') as $sedol) echo $sedol, checksum($sedol), "\n";
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Racket
Racket
  #lang racket   (define (non-square n) (+ n (exact-floor (+ 1/2 (sqrt n)))))   (map non-square (range 1 23))   (define (square? n) (integer? (sqrt n)))   (for/or ([n (in-range 1 1000001)]) (square? (non-square n)))  
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Raku
Raku
sub nth-term (Int $n) { $n + round sqrt $n }   # Print the first 22 values of the sequence say (nth-term $_ for 1 .. 22);   # Check that the first million values of the sequence are indeed non-square for 1 .. 1_000_000 -> $i { say "Oops, nth-term($i) is square!" if (sqrt nth-term $i) %% 1; }
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#OCaml
OCaml
# module IntSet = Set.Make(struct type t = int let compare = compare end);; (* Create a module for our type of set *) module IntSet : sig type elt = int type t val empty : t val is_empty : t -> bool val mem : elt -> t -> bool val add : elt -> t -> t val singleton : elt -> t val remove : elt -> t -> t val union : t -> t -> t val inter : t -> t -> t val diff : t -> t -> t val compare : t -> t -> int val equal : t -> t -> bool val subset : t -> t -> bool val iter : (elt -> unit) -> t -> unit val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a val for_all : (elt -> bool) -> t -> bool val exists : (elt -> bool) -> t -> bool val filter : (elt -> bool) -> t -> t val partition : (elt -> bool) -> t -> t * t val cardinal : t -> int val elements : t -> elt list val min_elt : t -> elt val max_elt : t -> elt val choose : t -> elt val split : elt -> t -> t * bool * t val find : elt -> t -> elt val of_list : elt list -> t end # IntSet.empty;; (* Empty set. A set is an abstract type that will not display in the interpreter *) - : IntSet.t = <abstr> # IntSet.elements (IntSet.empty);; (* Get the previous set into a list *) - : IntSet.elt list = [] # let s1 = IntSet.of_list [1;2;3;4;3];; val s1 : IntSet.t = <abstr> # IntSet.elements s1;; - : IntSet.elt list = [1; 2; 3; 4] # let s2 = IntSet.of_list [3;4;5;6];; val s2 : IntSet.t = <abstr> # IntSet.elements s2;; - : IntSet.elt list = [3; 4; 5; 6] # IntSet.elements (IntSet.union s1 s2);; (* Union *) - : IntSet.elt list = [1; 2; 3; 4; 5; 6] # IntSet.elements (IntSet.inter s1 s2);; (* Intersection *) - : IntSet.elt list = [3; 4] # IntSet.elements (IntSet.diff s1 s2);; (* Difference *) - : IntSet.elt list = [1; 2] # IntSet.subset s1 s1;; (* Subset *) - : bool = true # IntSet.subset (IntSet.of_list [3;1]) s1;; - : bool = true # IntSet.equal (IntSet.of_list [3;2;4;1]) s1;; (* Equality *) - : bool = true # IntSet.equal s1 s2;; - : bool = false # IntSet.mem 2 s1;; (* Membership *) - : bool = true # IntSet.mem 10 s1;; - : bool = false # IntSet.cardinal s1;; (* Cardinality *) - : int = 4 # IntSet.elements (IntSet.add 99 s1);; (* Create a new set by inserting *) - : IntSet.elt list = [1; 2; 3; 4; 99] # IntSet.elements (IntSet.remove 3 s1);; (* Create a new set by deleting *) - : IntSet.elt list = [1; 2; 4]
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Erlang
Erlang
  -module( sieve_of_eratosthenes ).   -export( [primes_upto/1] ).   primes_upto( N ) -> Ns = lists:seq( 2, N ), Dict = dict:from_list( [{X, potential_prime} || X <- Ns] ), {Upto_sqrt_ns, _T} = lists:split( erlang:round(math:sqrt(N)), Ns ), {N, Prime_dict} = lists:foldl( fun find_prime/2, {N, Dict}, Upto_sqrt_ns ), lists:sort( dict:fetch_keys(Prime_dict) ).       find_prime( N, {Max, Dict} ) -> find_prime( dict:find(N, Dict), N, {Max, Dict} ).   find_prime( error, _N, Acc ) -> Acc; find_prime( {ok, _Value}, N, {Max, Dict} ) when Max > N*N -> {Max, lists:foldl( fun dict:erase/2, Dict, lists:seq(N*N, Max, N))}; find_prime( {ok, _Value}, _, R) -> R.  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Tcl
Tcl
package require Tcl 8.5 package require http   # Fetch the words set t [http::geturl http://www.puzzlers.org/pub/wordlists/unixdict.txt] set wordlist [split [http::data $t] \n] http::cleanup $t   # Build hash table for speed foreach word $wordlist { set reversed([string reverse $word]) "dummy" }   # Find where a reversal exists foreach word $wordlist { if {[info exists reversed($word)] && $word ne [string reverse $word]} { # Remove to prevent pairs from being printed twice unset reversed([string reverse $word]) # Add to collection of pairs set pairs($word/[string reverse $word]) "dummy" } } set pairlist [array names pairs] ;# NB: pairs are in *arbitrary* order   # Report what we've found puts "Found [llength $pairlist] reversed pairs" foreach pair $pairlist { puts "Example: $pair" if {[incr i]>=5} break }
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#PicoLisp
PicoLisp
(de sedol (Str) (pack Str (char (+ `(char "0") (% (- 10 (% (sum '((W C) (cond ((>= "9" C "0") (* W (format C)) ) ((>= "Z" (setq C (uppc C)) "A") (* W (+ 10 (- (char C) `(char "A")))) ) ) ) (1 3 1 7 3 9) (chop Str) ) 10 ) ) 10 ) ) ) ) )   (for S '("710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030") (prinl (sedol S)) )
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Red
Red
Red ["Sequence of non-squares"]   repeat i 999'999 [ n: i + round/floor 0.5 + sqrt i if i < 23 [prin [to-integer n ""]] if equal? round/floor n sqrt n [ print "Square found!" break ] ]
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#REXX
REXX
/*REXX pgm displays some non─square numbers, & also displays a validation check up to 1M*/ parse arg N M . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 22 /*Not specified? Then use the default.*/ if M=='' | M=="," then M= 1000000 /* " " " " " " */ say 'The first ' N " non─square numbers:" /*display a header of what's to come. */ say /* [↑] default for M is one million.*/ say center('index', 20) center("non─square numbers", 20) say center('' , 20, "═") center('' , 20, "═") do j=1 for N say center(j, 20) center(j +floor(1/2 +sqrt(j)), 20) end /*j*/ #= 0 do k=1 for M /*have it step through a million of 'em*/ $= k + floor( sqrt(k) + .5 ) /*use the specified formula (algorithm)*/ iRoot= iSqrt($) /*··· and also use the ISQRT function.*/ if iRoot * iRoot == $ then #= # + 1 /*have we found a mistook? (sic) */ end /*k*/ say; if #==0 then #= 'no' /*use gooder English for display below.*/ say 'Using the formula: floor[ 1/2 + sqrt(n) ], ' # " squares found up to " M'.' /* [↑] display (possible) error count.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ floor: parse arg floor_; return trunc( floor_ - (floor_ < 0) ) /*──────────────────────────────────────────────────────────────────────────────────────*/ iSqrt: procedure; parse arg x; #=1; r= 0; do while # <= x; #= #*4; end do while #>1; #=#%4; _=x-r-#; r=r%2; if _<0 then iterate; x=_; r=r+#; end; return r /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_%2 do j=0 while h>9; m.j= h; h= h % 2 + 1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g)*.5; end /*k*/; return g
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Ol
Ol
  ; test set (define set1 '(1 2 3 4 5 6 7 8 9)) (define set2 '(3 4 5 11 12 13 14)) (define set3 '(4 5 6 7)) (define set4 '(1 2 3 4 5 6 7 8 9))   ; union (print (union set1 set2)) ; ==> (1 2 6 7 8 9 3 4 5 11 12 13 14)   ; intersection (print (intersect set1 set2)) ; ==> (3 4 5)   ; difference (print (diff set1 set2)) ; ==> (1 2 6 7 8 9)   ; subset (no predefined function) (define (subset? a b) (all (lambda (i) (has? b i)) a)) (print (subset? set3 set1)) ; ==> #true (print (subset? set3 set2)) ; ==> #false   ; equality (print (equal? set1 set2)) ; ==> #false (print (equal? set1 set4)) ; ==> #true  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#ERRE
ERRE
  PROGRAM SIEVE_ORG  ! --------------------------------------------------  ! Eratosthenes Sieve Prime Number Program in BASIC  ! (da 3 a SIZE*2) from Byte September 1981  !--------------------------------------------------- CONST SIZE%=8190   DIM FLAGS%[SIZE%]   BEGIN PRINT("Only 1 iteration") COUNT%=0 FOR I%=0 TO SIZE% DO IF FLAGS%[I%]=TRUE THEN  !$NULL ELSE PRIME%=I%+I%+3 K%=I%+PRIME% WHILE NOT (K%>SIZE%) DO FLAGS%[K%]=TRUE K%=K%+PRIME% END WHILE PRINT(PRIME%;) COUNT%=COUNT%+1 END IF END FOR PRINT PRINT(COUNT%;" PRIMES") END PROGRAM  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Transd
Transd
#lang transd   MainModule: { _start: (λ (with fs FileStream() (open-r fs "/mnt/vault/tmp/unixdict.txt") ) (with v ( -| (read-text fs) (split) (group-by (λ s String() -> String() (ret (min s (reverse (cp s)))))) (values) (filter where: (λ v Vector<String>() (ret (== (size v) 2)))) (shuffle))   (lout "Total number of semordnilaps: " (size v)) (lout "Random five: " Range(in: v 0 5)))) ) }
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT,{} requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt") DICT semordnilap CREATE 99999 COMPILE LOOP r=requestdata rstrings=STRINGS(r," ? ") rreverse=REVERSE(rstrings) revstring=EXCHANGE (rreverse,":'':':'::") group=APPEND (r,revstring) sort=ALPHA_SORT (group) DICT semordnilap APPEND/QUIET/COUNT sort,num,cnt,"","" ENDLOOP DICT semordnilap UNLOAD wordgroups,num,howmany get_palins=FILTER_INDEX (howmany,-," 1 ") size=SIZE(get_palins) PRINT "unixdict.txt contains ", size, " palindromes" PRINT " " palindromes=SELECT (wordgroups,#get_palins) LOOP n=1,5 take5=SELECT (palindromes,#n) PRINT n,". ",take5 ENDLOOP ENDCOMPILE  
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#PL.2FI
PL/I
/* Compute SEDOLs; includes check for invalid characters. */ sedol: procedure options (main); /* 3 March 2012 */ declare alphabet character (36) static initial ('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'); declare weight (6) fixed static initial (1, 3, 1, 7, 3, 9); declare s character (6); declare (i, v, k) fixed;   do while ('1'b); get edit (s) (a(6)); put skip edit (s) (a); /* Check for invalid characters: */ if verify(s, '0123456789BCDFGHJKLMNPQRSTVWXYZ') > 0 then stop; v = 0; do i = 1 to 6; k = index(alphabet, substr(s, i, 1)) - 1; v = v + weight(i) * k; end; k = mod(v, 10); v = mod(10 - k, 10); put edit (s, v) (x(2), a, f(1)); put edit (' ') (a); end; end sedol;
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Ring
Ring
  for n=1 to 22 x = n + floor(1/2 + sqrt(n)) see "" + x + " " next see nl  
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Ruby
Ruby
def f(n) n + (0.5 + Math.sqrt(n)).floor end   (1..22).each { |n| puts "#{n} #{f(n)}" }   non_squares = (1..1_000_000).map { |n| f(n) } squares = (1..1001).map { |n| n**2 } # Note: 1001*1001 = 1_002_001 > 1_001_000 = f(1_000_000) (squares & non_squares).each do |n| puts "Oops, found a square f(#{non_squares.index(n)}) = #{n}" end
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#ooRexx
ooRexx
-- Set creation -- Using the OF method s1 = .set~of(1, 2, 3, 4, 5, 6) -- Explicit addition of individual items s2 = .set~new s2~put(2) s2~put(4) s2~put(6) -- group addition s3 = .set~new s3~putall(.array~of(1, 3, 5)) -- Test m ? S -- "m is an element in set S" say s1~hasindex(1) s3~hasindex(2) -- "1 0", which is "true" and "false" -- A ? B -- union; a set of all elements either in set A or in set B. s4 = s2~union(s3) -- {1, 2, 3, 4, 5, 6} Call show 's4',s4 -- A ? B -- intersection; a set of all elements in both set A and set B. s5 = s1~intersection(s2) -- {2, 4, 6} Call show 's5',s5 -- A ? B -- difference; a set of all elements in set A, except those in set B. s6 = s1~difference(s2) -- {1, 3, 5} Call show 's6',s6 -- A ? B -- subset; true if every element in set A is also in set B. say s1~subset(s2) s2~subset(s1) -- "0 1" -- A = B -- equality; true if every element of set A is in set B and vice-versa. -- No direct equivalence method, but the XOR method can be used to determine this say s1~xor(s4)~isempty -- true Exit show: Procedure Use Arg set_name,set Say set_name':' set~makearray~makestring((LINE),',') return
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Euphoria
Euphoria
constant limit = 1000 sequence flags,primes flags = repeat(1, limit) for i = 2 to sqrt(limit) do if flags[i] then for k = i*i to limit by i do flags[k] = 0 end for end if end for   primes = {} for i = 2 to limit do if flags[i] = 1 then primes &= i end if end for ? primes
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#VBScript
VBScript
  Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1)   Set objUnixDict = CreateObject("Scripting.Dictionary") Set objSemordnilap = CreateObject("Scripting.Dictionary")   Do Until objInFile.AtEndOfStream line = objInFile.ReadLine If Len(line) > 1 Then objUnixDict.Add line,"" End If reverse_line = StrReverse(line) If reverse_line <> line And objUnixDict.Exists(reverse_line) Then objSemordnilap.Add line, reverse_line End If Loop   'Display the first 5 keys. k = 0 For Each Key In objSemordnilap.Keys WScript.StdOut.Write Key & " - " & objSemordnilap.Item(Key) WScript.StdOut.WriteLine k = k + 1 If k = 5 Then Exit For End If Next   WScript.StdOut.Write "Total Count: " & objSemordnilap.Count WScript.StdOut.WriteLine   objInFile.Close Set objFSO = Nothing Set objUnixDict = Nothing Set objSemordnilap = Nothing  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Wren
Wren
import "io" for File   var dict = File.read("unixdict.txt").split("\n") var wmap = {} dict.each { |w| wmap[w] = true } var pairs = [] var used = {} for (word in dict) { if (word != "") { var pal = word[-1..0] if (word != pal && wmap[pal] && !used[pal]) { pairs.add([word, pal]) used[word] = true } } } System.print("There are %(pairs.count) unique semordnilap pairs in the dictionary.") System.print("\nIn sorted order, the first five are:") for (i in 0..4) System.print("  %(pairs[i][0]), %(pairs[i][1])") System.print("\nand the last five are:") for (i in -5..-1) System.print("  %(pairs[i][0]), %(pairs[i][1])")
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Potion
Potion
sedolnum = (c) : if ("0" ord <= c ord and c ord <= "9" ord): c number integer. else: 10 + c ord - "A" ord. .   sedol = (str) : weight = (1, 3, 1, 7, 3, 9) sum = 0 6 times (i) : sum = sum + sedolnum(str(i)) * weight(i) . (str, (10 - (sum % 10)) % 10) join .
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#PowerShell
PowerShell
function Add-SEDOLCheckDigit { Param ( # Validate input as six-digit SEDOL number [ValidatePattern( "^[0123456789bcdfghjklmnpqrstvwxyz]{6}$" )] [parameter ( Mandatory = $True ) ] [string] $SixDigitSEDOL )   # Convert to array of single character strings, using type char as an intermediary $SEDOL = [string[]][char[]]$SixDigitSEDOL   # Define place weights $Weight = @( 1, 3, 1, 7, 3, 9 )   # Define character values (implicit in 0-based location within string) $Characters = "0123456789abcdefghijklmnopqrstuvwxyz"   $CheckSum = 0   # For each digit, multiply the character value by the weight and add to check sum 0..5 | ForEach { $CheckSum += $Characters.IndexOf( $SEDOL[$_].ToLower() ) * $Weight[$_] }   # Derive the check digit from the partial check sum $CheckDigit = ( 10 - $CheckSum % 10 ) % 10   # Return concatenated result return ( $SixDigitSEDOL + $CheckDigit ) }   # Test $List = @( "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL" "557910" "B0YBKR" "585284" "B0YBKT" "B00030" )   ForEach ( $PartialSEDOL in $List ) { Add-SEDOLCheckDigit -SixDigitSEDOL $PartialSEDOL }
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Rust
Rust
  fn f(n: i64) -> i64 { n + (0.5 + (n as f64).sqrt()) as i64 }   fn is_sqr(n: i64) -> bool { let a = (n as f64).sqrt() as i64; n == a * a || n == (a+1) * (a+1) || n == (a-1) * (a-1) }   fn main() { println!( "{:?}", (1..23).map(|n| f(n)).collect::<Vec<i64>>() ); let count = (1..1_000_000).map(|n| f(n)).filter(|&n| is_sqr(n)).count(); println!("{} unexpected squares found", count); }  
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Scala
Scala
def nonsqr(n:Int)=n+math.round(math.sqrt(n)).toInt   for(n<-1 to 22) println(n + " "+ nonsqr(n))   val test=(1 to 1000000).exists{n => val j=math.sqrt(nonsqr(n)) j==math.floor(j) } println("squares up to one million="+test)
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PARI.2FGP
PARI/GP
setsubset(s,t)={ for(i=1,#s, if(!setsearch(t,s[i]), return(0)) ); 1 }; s=Set([1,2,2]) t=Set([4,2,4]) setsearch(s,1) setunion(s,t) setintersect(s,t) setminus(s,t) setsubset(s,t) s==t
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#F.23
F#
  let primes max = let mutable xs = [|2..max|] let limit = max |> float |> sqrt |> int for x in [|2..limit|] do xs <- xs |> Array.except [|x*x..x..max|] xs  
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated strings def LF=$0A, CR=$0D, EOF=$1A;   proc RevStr(S); \Reverse order of characters in a string char S; int I, J, T; [J:= 0; while S(J) do J:= J+1; J:= J-1; I:= 0; while I<J do [T:= S(I); S(I):= S(J); S(J):= T; \swap I:= I+1; J:= J-1; ]; ];   func StrEqual(S1, S2); \Compare strings, return 'true' if equal char S1, S2; int I; [for I:= 0 to 80-1 do [if S1(I) # S2(I) then return false; if S1(I) = 0 then return true; ]; ];   int C, I, J, SJ, Count; char Dict, Word(80); [\Read file on command line redirected as input, i.e: <unixdict.txt Dict:= GetHp; \starting address of block of local "heap" memory I:= 0; \ [GetHp does exact same thing as Reserve(0)] repeat repeat C:= ChIn(1) until C#LF; \get chars sans line feeds if C = CR then C:= 0; \replace carriage return with terminator Dict(I):= C; I:= I+1; until C = EOF; SetHp(Dict+I); \set heap pointer beyond Dict I:= 0; Count:= 0; loop [J:= 0; \get word at I repeat C:= Dict(I+J); Word(J):= C; J:= J+1; until C=0; RevStr(Word); J:= J+I; \set J to following word in Dict if Dict(J) = EOF then quit; SJ:= J; \save index to following word loop [if StrEqual(Word, Dict+J) then [Count:= Count+1; if Count <= 5 then [RevStr(Word); \show some examples Text(0, Word); ChOut(0, ^ ); Text(0, Dict+J); CrLf(0); ]; quit; ]; repeat J:= J+1 until Dict(J) = 0; J:= J+1; if Dict(J) = EOF then quit; ]; I:= SJ; \next word ]; IntOut(0, Count); CrLf(0); ]
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#zkl
zkl
var [const] words= // create hashed unixdict of striped words (word:True, ...) File("dict.txt").howza(11).pump(Dictionary().howza(8).add.fp1(True)); ss:=words.pump(List, // push stripped unixdict words through some functions fcn(w){ words.holds(w.reverse()) }, Void.Filter, // filter palindromes // create ("word","drow") if "word"<"drow" (ie remove duplicates) fcn(w){ r:=w.reverse(); if(w<r) T(w,r) else Void.Skip });   ss.len().println(); //--> 158 ss.shuffle()[0,5].println();
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#PureBasic
PureBasic
Procedure.s SEDOLs(rawstring$) Protected i, j, sum, c, m For i=1 To Len(rawstring$) c=Asc(Mid(rawstring$,i,1)) Select c Case Asc("0") To Asc("9") j=Val(Mid(rawstring$,i,1)) Default j=c-Asc("A") EndSelect Select i Case 1, 3, 7: m=1 Case 2, 5: m=3 Case 4: m=7 Default: m=9 EndSelect sum+j*m Next sum=(10-(sum%10))%10 ProcedureReturn rawstring$+Str(sum) EndProcedure   Define result$, i Restore Tests For i=0 To 10 Read.s SEDOL$ result$+SEDOLs(SEDOL$) If i%2 result$+#CRLF$ ElseIf i<10 result$+", " EndIf Next MessageRequester("SEDOLs","Result"+#CRLF$+result$)   DataSection Tests: Data.s "710889","B0YBKJ","406566","B0YBLH","228276" Data.s "B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030" EndDataSection
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Scheme
Scheme
(define non-squares (lambda (index) (+ index (inexact->exact (floor (+ (/ 1 2) (sqrt index)))))))   (define sequence (lambda (function) (lambda (start) (lambda (stop) (if (> start stop) (list) (cons (function start) (((sequence function) (+ start 1)) stop)))))))   (define square? (lambda (number) ((lambda (root) (= (* root root) number)) (floor (sqrt number)))))   (define any? (lambda (predicate?) (lambda (list) (and (not (null? list)) (or (predicate? (car list)) ((any? predicate?) (cdr list)))))))   (display (((sequence non-squares) 1) 22)) (newline)   (display ((any? square?) (((sequence non-squares) 1) 999999))) (newline)
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pascal
Pascal
program Rosetta_Set;   {$mode objfpc}{$H+}   uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} Classes;   {$R *.res} type CharSet = set of char;   var A, B, C, S: CharSet; M: char;   function SetToString(const ASet: CharSet): string; var J: char; begin Result := ''; // Test all chars for J in char do // If the char is in set, add to result if J in ASet then Result := Result + J + ', '; // Clear the result if Result > '' then Delete(Result, Length(Result) - 1, 2); end;   procedure PrintSet(const ASet: CharSet; const ASetName: string; const ATitle: string = ''); begin if ATitle > '' then WriteLn(ATitle); WriteLn(ASetName, ' = [', SetToString(ASet), ']', #10); end;   procedure ShowEqual(const ASetA, ASetB: CharSet; const ASetNameA, ASetNameB: string); begin WriteLn(ASetNameA, ' = [', SetToString(ASetA), ']'); WriteLn(ASetNameB, ' = [', SetToString(ASetB), ']'); if ASetA = ASetB then WriteLn(ASetNameA, ' = ', ASetNameB) else WriteLn(ASetNameA, ' <> ', ASetNameB); end;     begin // Set Creation A := ['A', 'B', 'C', 'D', 'E', 'F']; B := ['E', 'F', 'G', 'H', 'I', 'J']; PrintSet(A, 'A', 'Set Creation'); PrintSet(B, 'B');   // Test m ∈ S -- "m is an element in set S" M := 'A'; if M in A then WriteLn('"A" is in set A');   // A ∪ B -- union; a set of all elements either in set A or in set B. S := A + B; PrintSet(S, 'S', 'S = A U B -- union; a set of all elements either in set A or in set B.');   // A ∩ B -- intersection; a set of all elements in both set A and set B. S := A * B; PrintSet(S, 'S', 'S = A ∩ B -- intersection; a set of all elements in both set A and set B.');   // A \ B -- difference; a set of all elements in set A, except those in set B. S := A - B; PrintSet(S, 'S', 'S = A \ B -- difference; a set of all elements in set A, except those in set B.');   // A ⊆ B -- subset; true if every element in set A is also in set B. Writeln('A ⊆ B -- subset; true if every element in set A is also in set B.'); if A <= B then WriteLn('A in B') else Writeln('A is not in B'); Writeln; //A = B -- equality; true if every element of set A is in set B and vice-versa. Writeln('A = B -- equality; true if every element of set A is in set B and vice-versa.');   ShowEqual(A, B, 'A', 'B'); S := A * B; C := ['E', 'F']; ShowEqual(S, C, 'S', 'C');   readln;   end.
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Factor
Factor
USING: bit-arrays io kernel locals math math.functions math.ranges prettyprint sequences ; IN: rosetta-code.sieve-of-erato   <PRIVATE   : init-sieve ( n -- seq )  ! Include 0 and 1 for easy indexing. 1 - <bit-array> dup set-bits ?{ f f } prepend ;   ! Given the sieve and a prime starting index, create a range of ! values to mark composite. Start at the square of the prime. : to-mark ( seq n -- range ) [ length 1 - ] [ dup dup * ] bi* -rot <range> ;   ! Mark multiples of prime n as composite. : mark-nths ( seq n -- ) dupd to-mark [ swap [ f ] 2dip set-nth ] with each ;   : next-prime ( index seq -- n ) [ t = ] find-from drop ;   PRIVATE>   :: sieve ( n -- seq ) n sqrt 2 n init-sieve :> ( limit i! s ) [ i limit < ]  ! sqrt optimization [ s i mark-nths i 1 + s next-prime i! ] while t s indices ;   : sieve-demo ( -- ) "Primes up to 120 using sieve of Eratosthenes:" print 120 sieve . ;   MAIN: sieve-demo
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Python
Python
def char2value(c): assert c not in 'AEIOU', "No vowels" return int(c, 36)   sedolweight = [1,3,1,7,3,9]   def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp % 10)) % 10)   for sedol in ''' 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT '''.split(): print sedol + checksum(sedol)
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const func integer: nonsqr (in integer: n) is return n + trunc(0.5 + sqrt(flt(n)));   const proc: main is func local var integer: i is 0; var float: j is 0.0; begin # First 22 values (as a list) has no squares: for i range 1 to 22 do write(nonsqr(i) <& " "); end for; writeln;   # The following check shows no squares up to one million: for i range 1 to 1000000 do j := sqrt(flt(nonsqr(i))); if j = floor(j) then writeln("Found square for nonsqr(" <& i <& ")"); end if; end for; end func;
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Sidef
Sidef
func nonsqr(n) { 0.5 + n.sqrt -> floor + n } {|i| nonsqr(i) }.map(1..22).join(' ').say   { |i| if (nonsqr(i).is_sqr) { die "Found a square in the sequence: #{i}" } } << 1..1e6
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Perl
Perl
use strict;   package Set; # likely will conflict with stuff on CPAN use overload '""' => \&str, 'bool' => \&count, '+=' => \&add, '-=' => \&del, '-' => \&diff, '==' => \&eq, '&' => \&intersection, '|' => \&union, '^' => \&xdiff;   sub str { my $set = shift; # This has drawbacks: stringification is used as set key # if the set is added to another set as an element, which # may cause inconsistencies if the element set is modified # later. In general, a hash key loses its object identity # anyway, so it's not unique to us. "Set{ ". join(", " => sort map("$_", values %$set)) . " }" }   sub new { my $pkg = shift; my $h = bless {}; $h->add($_) for @_; $h }   sub add { my ($set, $elem) = @_; $set->{$elem} = $elem; $set }   sub del { my ($set, $elem) = @_; delete $set->{$elem}; $set }   sub has { # set has element my ($set, $elem) = @_; exists $set->{$elem} }   sub union { my ($this, $that) = @_; bless { %$this, %$that } }   sub intersection { my ($this, $that) = @_; my $s = new Set; for (keys %$this) { $s->{$_} = $this->{$_} if exists $that->{$_} } $s }   sub diff { my ($this, $that) = @_; my $s = Set->new; for (keys %$this) { $s += $this->{$_} unless exists $that->{$_} } $s }   sub xdiff { # xor, symmetric diff my ($this, $that) = @_; my $s = new Set; bless { %{ ($this - $that) | ($that - $this) } } }   sub count { scalar(keys %{+shift}) }   sub eq { my ($this, $that) = @_; !($this - $that) && !($that - $this); }   sub contains { # this is a superset of that my ($this, $that) = @_; for (keys %$that) { return 0 unless $this->has($_) } return 1 }   package main; my ($x, $y, $z, $w);   $x = Set->new(1, 2, 3); $x += $_ for (5 .. 7); $y = Set->new(1, 2, 4, $x); # not the brightest idea   print "set x is: $x\nset y is: $y\n"; for (1 .. 4, $x) { print "$_ is", $y->has($_) ? "" : " not", " in y\n"; }   print "union: ", $x | $y, "\n"; print "intersect: ", $x & $y, "\n"; print "z = x - y = ", $z = $x - $y, "\n"; print "y is ", $x->contains($y) ? "" : "not ", "a subset of x\n"; print "z is ", $x->contains($z) ? "" : "not ", "a subset of x\n"; print "z = (x | y) - (x & y) = ", $z = ($x | $y) - ($x & $y), "\n"; print "w = x ^ y = ", $w = ($x ^ $y), "\n"; print "w is ", ($w == $z) ? "" : "not ", "equal to z\n"; print "w is ", ($w == $x) ? "" : "not ", "equal to x\n";
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#FOCAL
FOCAL
1.1 T "PLEASE ENTER LIMIT" 1.2 A N 1.3 I (2047-N)5.1 1.4 D 2 1.5 Q   2.1 F X=2,FSQT(N); D 3 2.2 F W=2,N; I (SIEVE(W)-2)4.1   3.1 I (-SIEVE(X))3.3 3.2 F Y=X*X,X,N; S SIEVE(Y)=2 3.3 R   4.1 T %4.0,W,!   5.1 T "PLEASE ENTER A NUMBER LESS THAN 2048."!; G 1.1
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Q
Q
scd:{ v:{("i"$x) - ?[("0"<=x) & x<="9"; "i"$"0"; -10+"i"$"A"]} each x; / Turn characters of SEDOL into their values w:sum v*1 3 1 7 3 9; / Weighted sum of values d:(10 - w mod 10) mod 10; / Check digit value x,"c"$(("i"$"0")+d) / Append to SEDOL }   scd each ("710889";"B0YBKJ";"406566";"B0YBLH";"228276";"B0YBKL";"557910";"B0YBKR";"585284";"B0YBKT";"B00030")
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Smalltalk
Smalltalk
| nonSquare isSquare squaresFound | nonSquare := [:n | n + (n sqrt) rounded ]. isSquare := [:n | n = (((n sqrt) asInteger) raisedTo: 2) ]. Transcript show: 'The first few non-squares:'; cr. 1 to: 22 do: [:n | Transcript show: (nonSquare value: n) asString; cr ]. squaresFound := 0. 1 to: 1000000 do: [:n | (isSquare value: (nonSquare value: n)) ifTrue: [ squaresFound := squaresFound + 1 ] ]. Transcript show: 'Squares found for values up to 1,000,000: '; show: squaresFound asString; cr
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Standard_ML
Standard ML
- fun nonsqr n = n + round (Math.sqrt (real n)); val nonsqr = fn : int -> int - List.tabulate (23, nonsqr); val it = [0,2,3,5,6,7,8,10,11,12,13,14,...] : int list - let fun loop i = if i = 1000000 then true else let val j = Math.sqrt (real (nonsqr i)) in Real.!= (j, Real.realFloor j) andalso loop (i+1) end in loop 1 end; val it = true : bool
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Phix
Phix
with javascript_semantics function is_element(object x, sequence set) return find(x,set)!=0 end function function set_union(sequence set1, set2) for i=1 to length(set2) do if not is_element(set2[i],set1) then set1 = append(set1,set2[i]) end if end for return set1 end function function set_intersection(sequence set1, set2) sequence res = {} for i=1 to length(set1) do if is_element(set1[i],set2) then res = append(res,set1[i]) end if end for return res end function function set_difference(sequence set1, set2) sequence res = {} for i=1 to length(set1) do if not is_element(set1[i],set2) then res = append(res,set1[i]) end if end for return res end function function set_subset(sequence set1, set2) for i=1 to length(set1) do if not is_element(set1[i],set2) then return false end if end for return true end function function set_equality(sequence set1, set2) if length(set1)!=length(set2) then return false end if return set_subset(set1,set2) end function --test code: ?is_element(3,{1,2,3}) -- 1 ?is_element(4,{1,2,3}) -- 0 ?set_union({1,2,3},{3,4,5}) -- {1,2,3,4,5} ?set_intersection({1,2,3},{3,4,5}) -- {3} ?set_difference({1,2,3},{3,4,5}) -- {1,2} ?set_subset({1,2,3},{3,4,5}) -- 0 ?set_subset({1,2},{1,2,3}) -- 1 ?set_equality({1,2,3},{3,4,5}) -- 0 ?set_equality({1,2,3},{3,1,2}) -- 1
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Forth
Forth
: prime? ( n -- ? ) here + c@ 0= ; : composite! ( n -- ) here + 1 swap c! ; : sieve ( n -- ) here over erase 2 begin 2dup dup * > while dup prime? if 2dup dup * do i composite! dup +loop then 1+ repeat drop ." Primes: " 2 do i prime? if i . then loop ; 100 sieve
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#R
R
# Read in data from text connection datalines <- readLines(tc <- textConnection("710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT")); close(tc)   # Check data valid checkSedol <- function(datalines) { ok <- grep("^[[:digit:][:upper:]]{6}$", datalines) if(length(ok) < length(datalines)) { stop("there are invalid lines") } } checkSedol(datalines)   # Append check digit appendCheckDigit <- function(x) { if(length(x) > 1) return(sapply(x, appendCheckDigit)) ascii <- as.integer(charToRaw(x)) scores <- ifelse(ascii < 65, ascii - 48, ascii - 55) weights <- c(1, 3, 1, 7, 3, 9) chkdig <- (10 - sum(scores * weights) %% 10) %% 10 paste(x, as.character(chkdig), sep="") } withchkdig <- appendCheckDigit(datalines)   #Print in format requested writeLines(withchkdig)
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Tcl
Tcl
package require Tcl 8.5   set f {n {expr {$n + floor(0.5 + sqrt($n))}}}   for {set x 1} {$x <= 22} {incr x} { puts [format "%d\t%s" $x [apply $f $x]] }   puts "looking for a square..." for {set x 1} {$x <= 1000000} {incr x} { set y [apply $f $x] set s [expr {sqrt($y)}] if {$s == int($s)} { error "found a square in the sequence: $x -> $y" } } puts "done"
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#TI-89_BASIC
TI-89 BASIC
■ n+floor(1/2+√(n)) → f(n) Done ■ seq(f(n),n,1,22) {2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27}
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PicoLisp
PicoLisp
(setq Set1 (1 2 3 7 abc "def" (u v w)) Set2 (2 3 5 hello (x y z)) Set3 (3 hello (x y z)) )     # Element tests (any non-NIL value means "yes") : (member "def" Set1) -> ("def" (u v w))   : (member "def" Set2) -> NIL   : (member '(x y z) Set2) -> ((x y z))     # Union : (uniq (append Set1 Set2)) -> (1 2 3 7 abc "def" (u v w) 5 hello (x y z))     # Intersection : (sect Set1 Set2) -> (2 3)     # Difference : (diff Set1 Set2) -> (1 7 abc "def" (u v w))     # Test for subset : (not (diff Set1 Set2)) -> NIL # Set1 is not a subset of Set2   : (not (diff Set3 Set2)) -> T # Set3 is a subset of Set2     # Test for equality : (= (sort (copy Set1)) (sort (copy Set2))) -> NIL   : (= (sort (copy Set2)) (sort (copy Set2))) -> T
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Fortran
Fortran
program sieve   implicit none integer, parameter :: i_max = 100 integer :: i logical, dimension (i_max) :: is_prime   is_prime = .true. is_prime (1) = .false. do i = 2, int (sqrt (real (i_max))) if (is_prime (i)) is_prime (i * i : i_max : i) = .false. end do do i = 1, i_max if (is_prime (i)) write (*, '(i0, 1x)', advance = 'no') i end do write (*, *)   end program sieve
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Racket
Racket
#lang racket ;;; Since the Task gives us unchecksummed and checksummed SEDOLs, and ;;; we'll just take a list of the output SEDOLs and remove their last ;;; characters for the input (define output-SEDOLS (list "7108899" "B0YBKJ7" "4065663" "B0YBLH2" "2282765" "B0YBKL9" "5579107" "B0YBKR5" "5852842" "B0YBKT7" "B000300")) (define (output->input-SEDOL S) (substring S 0 6)) (define input-SEDOLS (map output->input-SEDOL output-SEDOLS))   ;;; checksum calculation (define (SEDOL-character-value c) (if (char-numeric? c) (- (char->integer c) (char->integer #\0)) (+ 10 (- (char->integer c) (char->integer #\A))))) (define (SEDOL-character-sum S) (for/sum ((c S)  ; if we run out of c's before the final 1 in weight, we'll have the unchecksummed weighted sum (weight (in-list '(1 3 1 7 3 9 1)))) (* weight (SEDOL-character-value c)))) (define (SEDOL-checksum S) (number->string (modulo (- 10 (SEDOL-character-sum S)) 10)))   ;;; build output from input (define (SEDOL-append-checksum S) (string-append S (SEDOL-checksum S)))   ;;; Extra credit -- according to wikipedia: ;;; "SEDOLs are seven characters in length" ;;; "vowels are never used" ;;; there seems to be no statement as to case, but we'll assert that too! ;;; ;;; valid-SEDOL? is a predicate... it doesn't report a reason (define (invalid-SEDOL? S) (define (invalid-SEDOL-character? c) (if (and (not (char-upper-case? c)) (not (char-numeric? c))) (format "contains non upper case/non numeric ~a" c) (case c [(#\A #\E #\I #\O #\U) (format "contains vowel ~a" c)] [else #f]))) (cond [(< (string-length S) 7) "too few characters"] [(> (string-length S) 7) "too many characters"] [(not (zero? (modulo (SEDOL-character-sum S) 10))) "invalid checksum"] [(for/first ((c S) #:when (invalid-SEDOL-character? c)) c) => identity] [else #f])) ; a.k.a. valid!   (module+ main (for* ((S input-SEDOLS)) (displayln (SEDOL-append-checksum S))) (newline) (displayln "Extra Credit!") (displayln (invalid-SEDOL? "B0YBKT7")) ; expect #f output (displayln (invalid-SEDOL? "B000301")) ; expect "invalid checksum" output )   (module+ test (require rackunit) (check-= (SEDOL-character-value #\3) 3 0) (check-= (SEDOL-character-value #\B) 11 0) (check-equal? (invalid-SEDOL? "B000301") "invalid checksum") (for ((S output-SEDOLS)) (check-false (invalid-SEDOL? S)) (check-equal? (SEDOL-append-checksum (substring S 0 6)) S (format "test SEDOL for ~a" S))))
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Raku
Raku
sub sedol( Str $s ) { die 'No vowels allowed' if $s ~~ /<[AEIOU]>/; die 'Invalid format' if $s !~~ /^ <[0..9B..DF..HJ..NP..TV..Z]>**6 $ /;   my %base36 = (flat 0..9, 'A'..'Z') »=>« ^36; my @weights = 1, 3, 1, 7, 3, 9;   my @vs = %base36{ $s.comb }; my $checksum = [+] @vs Z* @weights; my $check_digit = (10 - $checksum % 10) % 10; return $s ~ $check_digit; }   say sedol($_) for < 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 >;
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Transd
Transd
#lang transd   MainModule: { nonsqr: (λ i Int() (ret (+ i (to-Int (floor (+ 0.5 (sqrt i))))))),   _start: (lambda locals: d Double() (for i in Range(1 23) do (textout (nonsqr i) " "))   (for i in Range(1 1000001) do (= d (sqrt (nonsqr i))) (if (eq d (floor d)) (throw String("Square: " i))))   (textout "\n\nUp to 1 000 000 - no squares found.") ) }
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#True_BASIC
True BASIC
FUNCTION nonSquare (n) LET nonSquare = n + INT(0.5 + SQR(n)) END FUNCTION   ! Display first 22 values PRINT "The first 22 numbers generated by the sequence are : " FOR i = 1 TO 22 PRINT nonSquare(i); " "; NEXT i PRINT   ! Check FOR squares up TO one million LET found = 0 FOR i = 1 TO 1e6 LET j = SQR(nonSquare(i)) IF j = INT(j) THEN LET found = 1 PRINT i, " square numbers found" EXIT FOR END IF NEXT i IF found = 0 THEN PRINT "No squares found" END
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PowerShell
PowerShell
  [System.Collections.Generic.HashSet[object]]$set1 = 1..4 [System.Collections.Generic.HashSet[object]]$set2 = 3..6   # Operation + Definition + Result #--------------------------------+---------------------+------------------------- $set1.UnionWith($set2) # Union $set1 = 1, 2, 3, 4, 5, 6 $set1.IntersectWith($set2) # Intersection $set1 = 3, 4 $set1.ExceptWith($set2) # Difference $set1 = 1, 2 $set1.SymmetricExceptWith($set2) # Symmetric difference $set1 = 1, 2, 6, 5 $set1.IsSupersetOf($set2) # Test superset False $set1.IsSubsetOf($set2) # Test subset False $set1.Equals($set2) # Test equality False $set1.IsProperSupersetOf($set2) # Test proper superset False $set1.IsProperSubsetOf($set2) # Test proper subset False   5 -in $set1 # Test membership False 7 -notin $set1 # Test non-membership True  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Free_Pascal
Free Pascal
  program prime_sieve; {$mode objfpc}{$coperators on} uses SysUtils, GVector; type TPrimeList = specialize TVector<DWord>; function Sieve(aLimit: DWord): TPrimeList; var IsPrime: array of Boolean; I, SqrtBound: DWord; J: QWord; begin Result := TPrimeList.Create; Inc(aLimit, Ord(aLimit < High(DWord))); //not a problem because High(DWord) is composite SetLength(IsPrime, aLimit); FillChar(Pointer(IsPrime)^, aLimit, Byte(True)); SqrtBound := Trunc(Sqrt(aLimit)); for I := 2 to aLimit do if IsPrime[I] then begin Result.PushBack(I); if I <= SqrtBound then begin J := I * I; repeat IsPrime[J] := False; J += I; until J > aLimit; end; end; end;   //usage   var Limit: DWord = 0; function ReadLimit: Boolean; var Lim: Int64; begin if (ParamCount = 1) and Lim.TryParse(ParamStr(1), Lim) then if (Lim >= 0) and (Lim <= High(DWord)) then begin Limit := DWord(Lim); exit(True); end; Result := False; end; procedure PrintUsage; begin WriteLn('Usage: prime_sieve Limit'); WriteLn(' where Limit in the range [0, ', High(DWord), ']'); Halt; end; procedure PrintPrimes(aList: TPrimeList); var I: DWord; begin for I := 0 to aList.Size - 2 do Write(aList[I], ', '); WriteLn(aList[aList.Size - 1]); aList.Free; end; begin if not ReadLimit then PrintUsage; try PrintPrimes(Sieve(Limit)); except on e: Exception do WriteLn('An exception ', e.ClassName, ' occurred with message: ', e.Message); end; end.  
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#REXX
REXX
╔════════════════════════════════════════════════════════════════════╗ ║ If the SEDOL is 6 characters, a check digit is added. ║ ║ ║ ║ If the SEDOL is 7 characters, a check digit is created and it's ║ ║ verified that it's equal to the check digit already on the SEDOL. ║ ╚════════════════════════════════════════════════════════════════════╝
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Ring
Ring
  see sedol("710889") + nl see sedol("B0YBKJ") + nl see sedol("406566") + nl see sedol("B0YBLH") + nl see sedol("228276") + nl see sedol("B0YBKL") + nl see sedol("557910") + nl see sedol("B0YBKR") + nl see sedol("585284") + nl see sedol("B0YBKT") + nl see sedol("B00030") + nl   func sedol d d = upper(d) s = 0 weights = [1, 3, 1, 7, 3, 9] for i = 1 to 6 a = substr(d,i,1) if ascii(a) >= 48 and ascii(a) <= 57 s += number(a) * weights[i] else s += (ascii(a) - 55) * weights[i] ok next return d + (10 - (s % 10)) % 10  
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Ursala
Ursala
#import nat #import flo   nth_non_square = float; plus^/~& math..trunc+ plus/0.5+ sqrt is_square = sqrt; ^E/~& math..trunc   #show+   examples = %neALP ^(~&,nth_non_square)*t iota23 check = (is_square*~+nth_non_square*t; ~&i&& %eLP)||-[no squares found]-! iota 1000000
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#VBA
VBA
  Sub Main() Dim i&, c&, j#, s$ Const N& = 1000000 s = "values for n in the range 1 to 22 : " For i = 1 To 22 s = s & ns(i) & ", " Next For i = 1 To N j = Sqr(ns(i)) If j = CInt(j) Then c = c + 1 Next   Debug.Print s Debug.Print c & " squares less than " & N End Sub   Private Function ns(l As Long) As Long ns = l + Int(1 / 2 + Sqr(l)) End Function
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Prolog
Prolog
:- use_module(library(lists)).   set :- A = [2, 4, 1, 3], B = [5, 2, 3, 2], ( is_set(A) -> format('~w is a set~n', [A]) ; format('~w is not a set~n', [A])), ( is_set(B) -> format('~w is a set~n', [B]) ; format('~w is not a set~n', [B])),   % create a set from a list   list_to_set(B, BS), ( is_set(BS) -> format('~nCreate a set from a list~n~w is a set~n', [BS]) ; format('~w is not a set~n', [BS])),   intersection(A, BS, I), format('~n~w intersection ~w => ~w~n', [A, BS, I]), union(A, BS, U), format('~w union ~w => ~w~n', [A, BS, U]), difference(A, BS, D), format('~w difference ~w => ~w~n', [A, BS, D]),   X = [1,2], ( subset(X, A) -> format('~n~w is a subset of ~w~n', [X, A]) ; format('~w is not a subset of ~w~n', [X, A])), Y = [1,5], ( subset(Y, A) -> format('~w is a subset of ~w~n', [Y, A]) ; format('~w is not a subset of ~w~n', [Y, A])), Z = [1, 2, 3, 4], ( equal(Z, A) -> format('~n~w is equal to ~w~n', [Z, A]) ; format('~w is not equal to ~w~n', [Z, A])), T = [1, 2, 3], ( equal(T, A) -> format('~w is equal to ~w~n', [T, A]) ; format('~w is not equal to ~w~n', [T, A])).       % compute difference of sets difference(A, B, D) :- exclude(member_(B), A, D).   member_(L, X) :- member(X, L).   equal([], []). equal([H1 | T1], B) :- select(H1, B, B1), equal(T1, B1).  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#FreeBASIC
FreeBASIC
' FB 1.05.0   Sub sieve(n As Integer) If n < 2 Then Return Dim a(2 To n) As Integer For i As Integer = 2 To n : a(i) = i : Next Dim As Integer p = 2, q ' mark non-prime numbers by setting the corresponding array element to 0 Do For j As Integer = p * p To n Step p a(j) = 0 Next j ' look for next non-zero element in array after 'p' q = 0 For j As Integer = p + 1 To Sqr(n) If a(j) <> 0 Then q = j Exit For End If Next j If q = 0 Then Exit Do p = q Loop   ' print the non-zero numbers remaining i.e. the primes For i As Integer = 2 To n If a(i) <> 0 Then Print Using "####"; a(i); End If Next Print End Sub   Print "The primes up to 1000 are :" Print sieve(1000) Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Related tasks   Luhn test   ISIN
#Ruby
Ruby
Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" Sedolweight = [1,3,1,7,3,9]   def char2value(c) raise ArgumentError, "Invalid char #{c}" unless Sedol_char.include?(c) c.to_i(36) end   def checksum(sedol) raise ArgumentError, "Invalid length" unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight } ((10 - (sum % 10)) % 10).to_s end   data = %w(710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A)   data.each do |sedol| print "%-8s " % sedol begin puts sedol + checksum(sedol) rescue => e p e end end
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Wren
Wren
import "/fmt" for Fmt   System.print("The first 22 numbers in the sequence are:") System.print(" n term") for (n in 1...1e6) { var s = n + (0.5 + n.sqrt).floor var ss = s.sqrt.round if (ss * ss == s) { Fmt.print("The $r number in the sequence $d = $d x $d is a square.", n, s, ss, ss) return } if (n <= 22) Fmt.print(" $2d $2d", n, s) } System.print("\nNo squares were found in the first 999,999 terms.")
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PureBasic
PureBasic
Procedure.s booleanText(b) ;returns 'True' or 'False' for a boolean input If b: ProcedureReturn "True": EndIf ProcedureReturn "False" EndProcedure   Procedure.s listSetElements(Map a(), delimeter.s = " ") ;format elements for display Protected output$   ForEach a() output$ + MapKey(a()) + delimeter Next   ProcedureReturn "(" + RTrim(output$, delimeter) + ")" EndProcedure   Procedure.s listSortedSetElements(Map a(), delimeter.s = " ") ;format elements for display as sorted for easy comparison Protected output$ NewList b.s()   ForEach a() AddElement(b()): b() = MapKey(a()) Next SortList(b(), #PB_Sort_Ascending | #PB_Sort_NoCase) ForEach b() output$ + b() + delimeter Next   ProcedureReturn "(" + RTrim(output$, delimeter) + ")" EndProcedure   Procedure cardinalityOf(Map a()) ProcedureReturn MapSize(a()) EndProcedure   Procedure createSet(elements.s, Map o(), delimeter.s = " ", clearSet = 1) Protected i, elementCount   If clearSet: ClearMap(o()): EndIf elementCount = CountString(elements, delimeter) + 1 ;add one for the last element which won't have a delimeter For i = 1 To elementCount AddMapElement(o(), StringField(elements, i, delimeter)) Next   ProcedureReturn MapSize(o()) EndProcedure   Procedure adjoinTo(elements.s, Map o(), delimeter.s = " ") ProcedureReturn createSet(elements, o(), delimeter, 0) EndProcedure   Procedure disjoinFrom(elements.s, Map o(), delimeter.s = " ") Protected i, elementCount   elementCount = CountString(elements, delimeter) + 1 ;add one for the last element which won't have a delimeter For i = 1 To elementCount DeleteMapElement(o(), StringField(elements, i, delimeter)) Next   ProcedureReturn MapSize(o()) EndProcedure   Procedure isElementOf(element.s, Map a()) ProcedureReturn FindMapElement(a(), element) EndProcedure       Procedure unionOf(Map a(), Map b(), Map o()) CopyMap(a(), o()) ForEach b() AddMapElement(o(), MapKey(b())) Next   ProcedureReturn MapSize(o()) EndProcedure   Procedure intersectionOf(Map a(), Map b(), Map o()) ClearMap(o()) ForEach a() If FindMapElement(b(), MapKey(a())) AddMapElement(o(), MapKey(a())) EndIf Next   ProcedureReturn MapSize(o()) EndProcedure   Procedure differenceOf(Map a(), Map b(), Map o()) CopyMap(a(), o()) ForEach b() If FindMapElement(o(), MapKey(b())) DeleteMapElement(o()) Else AddMapElement(o(), MapKey(b())) EndIf Next   ProcedureReturn MapSize(o()) EndProcedure   Procedure isSubsetOf(Map a(), Map b()) ;boolean ForEach a() If Not FindMapElement(b(), MapKey(a())) ProcedureReturn 0 EndIf Next ProcedureReturn 1 EndProcedure   Procedure isProperSubsetOf(Map a(), Map b()) ;boolean If MapSize(a()) = MapSize(b()) ProcedureReturn 0 EndIf ProcedureReturn isSubsetOf(a(), b()) EndProcedure   Procedure isEqualTo(Map a(), Map b()) If MapSize(a()) = MapSize(b()) ProcedureReturn isSubsetOf(a(), b()) EndIf ProcedureReturn 0 EndProcedure   Procedure isEmpty(Map a()) ;boolean If MapSize(a()) ProcedureReturn 0 EndIf ProcedureReturn 1 EndProcedure   If OpenConsole() NewMap a() NewMap b() NewMap o() ;for output sets NewMap c()   createSet("red blue green orange yellow", a()) PrintN("Set A = " + listSortedSetElements(a()) + " of cardinality " + Str(cardinalityOf(a())) + ".") createSet("lady green red", b()) PrintN("Set B = " + listSortedSetElements(b()) + " of cardinality " + Str(cardinalityOf(b())) + ".") PrintN("'red' is an element of A is " + booleanText(isElementOf("red", a())) + ".") PrintN("'red' is an element of B is " + booleanText(isElementOf("red", b())) + ".") PrintN("'blue' is an element of B is " + booleanText(isElementOf("blue", b())) + ".")   unionOf(a(), b(), o()) PrintN(#crlf$ + "Union of A & B is " + listSortedSetElements(o()) + ".") intersectionOf(a(), b(), o()) PrintN("Intersection of A & B is " + listSortedSetElements(o()) + ".") differenceOf(a(), b(), o()) PrintN("Difference of A & B is " + listSortedSetElements(o()) + ".")   PrintN(listSortedSetElements(a()) + " equals " + listSortedSetElements(a()) + " is " + booleanText(isEqualTo(a(), a())) + ".") PrintN(listSortedSetElements(a()) + " equals " + listSortedSetElements(b()) + " is " + booleanText(isEqualTo(a(), b())) + ".")   createSet("red green", c()) PrintN(#crlf$ + listSortedSetElements(c()) + " is a subset of " + listSortedSetElements(a()) + " is "+ booleanText(isSubsetOf(c(), a())) + ".") PrintN(listSortedSetElements(c()) + " is a proper subset of " + listSortedSetElements(b()) + " is "+ booleanText(isProperSubsetOf(c(), b())) + ".") PrintN(listSortedSetElements(c()) + " is a proper subset of " + listSortedSetElements(a()) + " is "+ booleanText(isProperSubsetOf(c(), a())) + ".") PrintN(listSortedSetElements(b()) + " is a proper subset of " + listSortedSetElements(b()) + " is "+ booleanText(isProperSubsetOf(b(), b())) + ".")   PrintN(#crlf$ + "Set C = " + listSortedSetElements(c()) + " of cardinality " + Str(cardinalityOf(c())) + ".") adjoinTo("dog cat mouse", c()) PrintN("Add 'dog cat mouse' to C to get " + listSortedSetElements(c()) + " of cardinality " + Str(cardinalityOf(c())) + ".") disjoinFrom("red green dog", c()) PrintN("Take away 'red green dog' from C to get " + listSortedSetElements(c()) + " of cardinality " + Str(cardinalityOf(c())) + ".")     Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Frink
Frink
  n = eval[input["Enter highest number: "]] results = array[sieve[n]] println[results] println[length[results] + " prime numbers less than or equal to " + n]   sieve[n] := { // Initialize array array = array[0 to n] array@1 = 0   for i = 2 to ceil[sqrt[n]] if array@i != 0 for j = i^2 to n step i array@j = 0   return select[array, { |x| x != 0 }] }