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/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.
|
#Common_Lisp
|
Common Lisp
|
(defun non-square-sequence ()
(flet ((non-square (n)
"Compute the N-th number of the non-square sequence"
(+ n (floor (+ 1/2 (sqrt n)))))
(squarep (n)
"Tests, whether N is a square"
(let ((r (floor (sqrt n))))
(= (* r r) n))))
(loop
:for n :upfrom 1 :to 22
:do (format t "~2D -> ~D~%" n (non-square n)))
(loop
:for n :upfrom 1 :to 1000000
:when (squarep (non-square n))
:do (format t "Found a square: ~D -> ~D~%"
n (non-square n)))))
|
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
|
#CoffeeScript
|
CoffeeScript
|
# For ad-hoc set features, it sometimes makes sense to use hashes directly,
# rather than abstract to this level, but I'm showing a somewhat heavy
# solution to show off CoffeeScript class syntax.
class Set
constructor: (elems...) ->
@hash = {}
for elem in elems
@hash[elem] = true
add: (elem) ->
@hash[elem] = true
remove: (elem) ->
delete @hash[elem]
has: (elem) ->
@hash[elem]?
union: (set2) ->
set = new Set()
for elem of @hash
set.add elem
for elem in set2.to_array()
set.add elem
set
intersection: (set2) ->
set = new Set()
for elem of @hash
set.add elem if set2.has elem
set
minus: (set2) ->
set = new Set()
for elem of @hash
set.add elem if !set2.has elem
set
is_subset_of: (set2) ->
for elem of @hash
return false if !set2.has elem
true
equals: (set2) ->
this.is_subset_of(set2) and set2.is_subset_of this
to_array: ->
(elem for elem of @hash)
each: (f) ->
for elem of @hash
f(elem)
to_string: ->
@to_array()
run_tests = ->
set1 = new Set("apple", "banana") # creation
console.log set1.has "apple" # true (membership)
console.log set1.has "worms" # false (membership)
set2 = new Set("banana", "carrots")
console.log set1.union(set2).to_string() # [ 'apple', 'banana', 'carrots' ] (union)
console.log set1.intersection(set2).to_string() # [ 'banana' ] (intersection)
console.log set1.minus(set2).to_string() # [ 'apple' ] (difference)
set3 = new Set("apple")
console.log set3.is_subset_of set1 # true
console.log set3.is_subset_of set2 # false
set4 = new Set("apple", "banana")
console.log set4.equals set1 # true
console.log set4.equals set2 # false
set5 = new Set("foo")
set5.add "bar" # add
console.log set5.to_string() # [ 'foo', 'bar' ]
set5.remove "bar" # remove
console.log set5.to_string() # [ 'foo' ]
# iteration, prints apple then banana (order not guaranteed)
set1.each (elem) ->
console.log elem
run_tests()
|
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
|
#AutoHotkey
|
AutoHotkey
|
MsgBox % "12345678901234567890`n" Sieve(20)
Sieve(n) { ; Sieve of Eratosthenes => string of 0|1 chars, 1 at position k: k is prime
Static zero := 48, one := 49 ; Asc("0"), Asc("1")
VarSetCapacity(S,n,one)
NumPut(zero,S,0,"char")
i := 2
Loop % sqrt(n)-1 {
If (NumGet(S,i-1,"char") = one)
Loop % n//i
If (A_Index > 1)
NumPut(zero,S,A_Index*i-1,"char")
i += 1+(i>2)
}
Return S
}
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Racket
|
Racket
|
#lang racket
(define (consolidate ss)
(define (comb s cs)
(cond [(set-empty? s) cs]
[(empty? cs) (list s)]
[(set-empty? (set-intersect s (first cs)))
(cons (first cs) (comb s (rest cs)))]
[(consolidate (cons (set-union s (first cs)) (rest cs)))]))
(foldl comb '() ss))
(consolidate (list (set 'a 'b) (set 'c 'd)))
(consolidate (list (set 'a 'b) (set 'b 'c)))
(consolidate (list (set 'a 'b) (set 'c 'd) (set 'd 'b)))
(consolidate (list (set 'h 'i 'k) (set 'a 'b) (set 'c 'd) (set 'd 'b) (set 'f 'g 'h)))
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Raku
|
Raku
|
multi consolidate() { () }
multi consolidate(Set \this is copy, *@those) {
gather {
for consolidate |@those -> \that {
if this ∩ that { this = this ∪ that }
else { take that }
}
take this;
}
}
enum Elems <A B C D E F G H I J K>;
say $_, "\n ==> ", consolidate |$_
for [set(A,B), set(C,D)],
[set(A,B), set(B,D)],
[set(A,B), set(C,D), set(D,B)],
[set(H,I,K), set(A,B), set(C,D), set(D,B), set(F,G,H)];
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#Wren
|
Wren
|
import "/crypto" for Sha1
import "/fmt" for Fmt
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"The quick brown fox jumps over the lazy dog",
"The quick brown fox jumps over the lazy cog",
"Rosetta Code"
]
for (s in strings) {
var hash = Sha1.digest(s)
Fmt.print("$s <== '$0s'", hash, s)
}
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#zkl
|
zkl
|
$ zkl // run the REPL
zkl: var MsgHash=Import("zklMsgHash")
MsgHash
zkl: MsgHash.SHA1("Rosetta Code")
48c98f7e5a6e736d790ab740dfc3f51a61abe2b5
zkl: var hash=MsgHash.SHA1("Rosetta Code",1,False) // hash once, return hash as bytes
Data(20)
zkl: hash.bytes()
L(72,201,143,126,90,110,115,109,121,10,183,64,223,195,245,26,97,171,226,181)
zkl: hash.bytes().apply("toString",16).concat()
48c98f7e5a6e736d79ab740dfc3f51a61abe2b5
zkl: MsgHash.SHA1("a"*1000,1000); // hash 1000 a's 1000 times
34aa973cd4c4daa4f61eeb2bdbad27316534016f
|
http://rosettacode.org/wiki/Show_ASCII_table
|
Show ASCII table
|
Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
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
|
#PL.2FM
|
PL/M
|
100H: /* SHOW AN ASCII TABLE FROM 32 TO 127 */
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* I/O ROUTINES */
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$BYTE: PROCEDURE( N );
DECLARE N BYTE;
DECLARE V BYTE;
V = N MOD 100;
CALL PR$CHAR( ' ' );
CALL PR$CHAR( '0' + ( N / 100 ) );
CALL PR$CHAR( '0' + ( V / 10 ) );
CALL PR$CHAR( '0' + ( V MOD 10 ) );
END PR$BYTE;
/* ASCII TABLE */
DECLARE C BYTE;
DO C = 32 TO 127;
CALL PR$BYTE( C );
CALL PR$STRING( .': $' );
IF C = 32 THEN CALL PR$STRING( .'SPC$' );
ELSE IF C = 127 THEN CALL PR$STRING( .'DEL$' );
ELSE DO;
CALL PR$CHAR( ' ' );
CALL PR$CHAR( C );
CALL PR$CHAR( ' ' );
END;
IF ( ( C - 31 ) MOD 6 ) = 0 THEN CALL PR$STRING( .( 0DH, 0AH, '$' ) );
END;
EOF
|
http://rosettacode.org/wiki/Sierpinski_triangle
|
Sierpinski triangle
|
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
|
#Scala
|
Scala
|
scala -e "for(y<-0 to 15){println(\" \"*(15-y)++(0 to y).map(x=>if((~y&x)>0)\" \"else\" *\")mkString)}"
|
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
|
#PostScript
|
PostScript
|
%!PS-Adobe-3.0
%%BoundingBox 0 0 300 300
/r { moveto 0 -1 1 0 0 1 3 { rlineto } repeat closepath fill } def
/serp { gsave
3 1 roll translate
1 3 div dup scale
1 1 r
dup 1 sub dup 0 eq not {
0 0 0 1 0 2 1 0 1 2 2 0 2 1 2 2 17 -1 roll 8 { serp } repeat
} if pop
grestore
} def
300 300 scale 0 0 r 1 setgray
0 0 5 serp
pop showpage
%%EOF
|
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
|
#EchoLisp
|
EchoLisp
|
(lib 'struct)
(lib 'sql)
(lib 'words)
(lib 'dico.fr.no-accent) ;; load dictionary
(string-delimiter "")
;; check reverse r of w is a word
;; take only one pair : r < w
(define (semordnilap? w)
(define r (list->string (reverse (string->list w))))
(and (word? r) (string<? r w)))
;; to get longest first
(define (string-sort a b) (> (string-length a) (string-length b)))
(define (task)
;; select unique words into the list 'mots'
(define mots (make-set (words-select #:any null 999999)))
(define semordnilap
(list-sort string-sort (for/list ((w mots))
#:when (semordnilap? w)
w )))
(writeln 'pairs '→ (length semordnilap))
(writeln 'longest '→ (take semordnilap 5)))
{{out}}
(task)
pairs → 345
longest → (rengager tresser strasse reveler retrace)
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const func boolean: a (in boolean: aBool) is func
result
var boolean: result is FALSE;
begin
writeln("a");
result := aBool;
end func;
const func boolean: b (in boolean: aBool) is func
result
var boolean: result is FALSE;
begin
writeln("b");
result := aBool;
end func;
const proc: test (in boolean: param1, in boolean: param2) is func
begin
writeln(param1 <& " and " <& param2 <& " = " <& a(param1) and b(param2));
writeln(param1 <& " or " <& param2 <& " = " <& a(param1) or b(param2));
end func;
const proc: main is func
begin
test(FALSE, FALSE);
test(FALSE, TRUE);
test(TRUE, FALSE);
test(TRUE, TRUE);
end func;
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Sidef
|
Sidef
|
func a(bool) { print 'A'; return bool }
func b(bool) { print 'B'; return bool }
# Test-driver
func test() {
for op in ['&&', '||'] {
for x,y in [[1,1],[1,0],[0,1],[0,0]] {
"a(%s) %s b(%s): ".printf(x, op, y)
eval "a(Bool(x)) #{op} b(Bool(y))"
print "\n"
}
}
}
# Test and display
test()
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#OCaml
|
OCaml
|
let h = Smtp.connect "smtp.gmail.fr";;
Smtp.helo h "hostname";;
Smtp.mail h "<[email protected]>";;
Smtp.rcpt h "<[email protected]>";;
let email_header = "\
From: John Smith <[email protected]>
To: John Doe <[email protected]>
Subject: surprise";;
let email_msg = "Happy Birthday";;
Smtp.data h (email_header ^ "\r\n\r\n" ^ email_msg);;
Smtp.quit h;;
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#Perl
|
Perl
|
use Net::SMTP;
use Authen::SASL;
# Net::SMTP's 'auth' method needs Authen::SASL to work, but
# this is undocumented, and if you don't have the latter, the
# method will just silently fail. Hence we explicitly use
# Authen::SASL here.
sub send_email
{my %o =
(from => '', to => [], cc => [],
subject => '', body => '',
host => '', user => '', password => '',
@_);
ref $o{$_} or $o{$_} = [$o{$_}] foreach 'to', 'cc';
my $smtp = new Net::SMTP($o{host} ? $o{host} : ())
or die "Couldn't connect to SMTP server";
$o{password} and
$smtp->auth($o{user}, $o{password}) ||
die 'SMTP authentication failed';
$smtp->mail($o{user});
$smtp->recipient($_) foreach @{$o{to}}, @{$o{cc}};
$smtp->data;
$o{from} and $smtp->datasend("From: $o{from}\n");
$smtp->datasend('To: ' . join(', ', @{$o{to}}) . "\n");
@{$o{cc}} and $smtp->datasend('Cc: ' . join(', ', @{$o{cc}}) . "\n");
$o{subject} and $smtp->datasend("Subject: $o{subject}\n");
$smtp->datasend("\n$o{body}");
$smtp->dataend;
return 1;}
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#Elixir
|
Elixir
|
defmodule Prime do
def semiprime?(n), do: length(decomposition(n)) == 2
def decomposition(n), do: decomposition(n, 2, [])
defp decomposition(n, k, acc) when n < k*k, do: Enum.reverse(acc, [n])
defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc])
defp decomposition(n, k, acc), do: decomposition(n, k+1, acc)
end
IO.inspect Enum.filter(1..100, &Prime.semiprime?(&1))
Enum.each(1675..1680, fn n ->
:io.format "~w -> ~w\t~s~n", [n, Prime.semiprime?(n), Prime.decomposition(n)|>Enum.join(" x ")]
end)
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#Erlang
|
Erlang
|
-module(factors).
-export([factors/1,kthfactor/2]).
factors(N) ->
factors(N,2,[]).
factors(1,_,Acc) -> Acc;
factors(N,K,Acc) when N rem K == 0 ->
factors(N div K,K, [K|Acc]);
factors(N,K,Acc) ->
factors(N,K+1,Acc).
% is integer N factorable into M primes?
kthfactor(N,M) ->
case length(factors(N)) of M ->
factors(N);
_ ->
false 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
|
#AutoHotkey
|
AutoHotkey
|
codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB
Loop, Parse, codes, `,
output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n"
Msgbox %output%
SEDOL(code) {
Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9
If (StrLen(code) != 6)
Return "Invalid length."
StringCaseSense On
Loop, Parse, code
If A_LoopField is Number
check_digit += A_LoopField * weight%A_Index%
Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z
check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index%
Else
Return "Invalid character."
Return code . Mod(10-Mod(check_digit,10),10)
}
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#Factor
|
Factor
|
USING: kernel math.parser prettyprint sequences ;
IN: rosetta-code.self-describing-numbers
: digits ( n -- seq ) number>string string>digits ;
: digit-count ( seq n -- m ) [ = ] curry count ;
: self-describing-number? ( n -- ? )
digits dup [ digit-count = ] with map-index [ t = ] all? ;
100,000,000 <iota> [ self-describing-number? ] filter .
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#Forth
|
Forth
|
\ where unavailable.
: third ( A b c -- A b c A ) >r over r> swap ;
: (.) ( u -- c-addr u ) 0 <# #s #> ;
\ COUNT is a standard word with a very different meaning, so this
\ would typically be beheaded, or given another name, or otherwise
\ given a short lifespan, so to speak.
: count ( c-addr1 u1 c -- c-addr1 u1 c+1 u )
0 2over bounds do
over i c@ = if 1+ then
loop swap 1+ swap ;
: self-descriptive? ( u -- f )
(.) [char] 0 third third bounds ?do
count i c@ [char] 0 - <> if drop 2drop false unloop exit then
loop drop 2drop true ;
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
sum[g_] := g + Total@IntegerDigits@g
ming[n_] := n - IntegerLength[n]*9
self[n_] := NoneTrue [Range[ming[n], n - 1], sum[#] == n &]
Module[{t = 1, x = 1},
Reap[
While[t <= 50,
If[self[x], Sow[x]; t++]; x++]
][[2, 1]]]
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Nim
|
Nim
|
import bitops, strutils, std/monotimes, times
const MaxCount = 2 * 1_000_000_000 + 9 * 9
# Bit string used to represent an array of booleans.
type BitString = object
len: Natural # length in bits.
values: seq[byte] # Sequence containing the bits.
proc newBitString(n: Natural): BitString =
## Return a new bit string of length "n" bits.
result.len = n
result.values.setLen((n + 7) shr 3)
template checkIndex(i, length: Natural) {.used.} =
## Check if index "i" is less than the array length.
if i >= length:
raise newException(IndexDefect, "index $1 not in 0 .. $2".format(i, length))
proc `[]`(bs: BitString; i: Natural): bool =
## Return the value of bit at index "i" as a boolean.
when compileOption("boundchecks"):
checkIndex(i, bs.len)
result = bs.values[i shr 3].testbit(i and 0x07)
proc `[]=`(bs: var BitString; i: Natural; value: bool) =
## Set the bit at index "i" to the given value.
when compileOption("boundchecks"):
checkIndex(i, bs.len)
if value: bs.values[i shr 3].setBit(i and 0x07)
else: bs.values[i shr 3].clearBit(i and 0x07)
proc fill(sieve: var BitString) =
## Fill a sieve.
var n = 0
for a in 0..1:
for b in 0..9:
for c in 0..9:
for d in 0..9:
for e in 0..9:
for f in 0..9:
for g in 0..9:
for h in 0..9:
for i in 0..9:
for j in 0..9:
sieve[a + b + c + d + e + f + g + h + i + j + n] = true
inc n
let t0 = getMonoTime()
var sieve = newBitString(MaxCount + 1)
sieve.fill()
echo "Sieve time: ", getMonoTime() - t0
# Find first 50.
echo "\nFirst 50 self numbers:"
var count = 0
var line = ""
for n in 0..MaxCount:
if not sieve[n]:
inc count
line.addSep(" ")
line.add $n
if count == 50: break
echo line
# Find 1st, 10th, 100th, ..., 100_000_000th.
echo "\n Rank Value"
var limit = 1
count = 0
for n in 0..MaxCount:
if not sieve[n]: inc count
if count == limit:
echo ($count).align(10), ($n).align(12)
limit *= 10
echo "Total time: ", getMonoTime() - t0
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Pascal
|
Pascal
|
program selfnumb;
{$IFDEF FPC}
{$MODE Delphi}
{$Optimization ON,ALL}
{$IFEND}
{$IFDEF DELPHI} {$APPTYPE CONSOLE} {$IFEND}
uses
sysutils;
const
MAXCOUNT =103*10000*10000+11*9+ 1;
type
tDigitSum9999 = array[0..9999] of Uint8;
tpDigitSum9999 = ^tDigitSum9999;
var
DigitSum9999 : tDigitSum9999;
sieve : array of boolean;
procedure dosieve;
var
pSieve : pBoolean;
pDigitSum :tpDigitSum9999;
n,c,b,a,s : NativeInt;
Begin
pSieve := @sieve[0];
pDigitSum := @DigitSum9999[0];
n := 0;
for a := 0 to 102 do
for b := 0 to 9999 do
Begin
s := pDigitSum^[a]+pDigitSum^[b]+n;
for c := 0 to 9999 do
Begin
pSieve[pDigitSum^[c]+s] := true;
s+=1;
end;
inc(n,10000);
end;
end;
procedure InitDigitSum;
var
i,d,c,b,a : NativeInt;
begin
i := 9999;
for a := 9 downto 0 do
for b := 9 downto 0 do
for c := 9 downto 0 do
for d := 9 downto 0 do
Begin
DigitSum9999[i] := a+b+c+d;
dec(i);
end;
end;
procedure OutPut(cnt,i:NativeUint);
Begin
writeln(cnt:10,i:12);
end;
var
pSieve : pboolean;
T0 : Uint64;
i,cnt,limit,One: NativeUInt;
BEGIN
setlength(sieve,MAXCOUNT);
pSieve := @sieve[0];
T0 := GetTickCount64;
InitDigitSum;
dosieve;
writeln('Sievetime : ',(GetTickCount64-T0 )/1000:8:3,' sec');
//find first 50
cnt := 0;
for i := 0 to MAXCOUNT do
Begin
if NOT(pSieve[i]) then
Begin
inc(cnt);
if cnt <= 50 then
write(i:4)
else
BREAK;
end;
end;
writeln;
One := 1;
limit := One;
cnt := 0;
for i := 0 to MAXCOUNT do
Begin
inc(cnt,One-Ord(pSieve[i]));
if cnt = limit then
Begin
OutPut(cnt,i);
limit := limit*10;
end;
end;
END.
|
http://rosettacode.org/wiki/Set_of_real_numbers
|
Set of real numbers
|
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | a < x and x < b }
[a, b): {x | a ≤ x and x < b }
(a, b]: {x | a < x and x ≤ b }
Note that if a = b, of the four only [a, a] would be non-empty.
Task
Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
Provide methods for these common set operations (x is a real number; A and B are sets):
x ∈ A: determine if x is an element of A
example: 1 is in [1, 2), while 2, 3, ... are not.
A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B}
example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B}
example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B}
example: [0, 2) − (1, 3) = [0, 1]
Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
(0, 1] ∪ [0, 2)
[0, 2) ∩ (1, 2]
[0, 3) − (0, 1)
[0, 3) − [0, 1]
Implementation notes
'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
Optional work
Create a function to determine if a given set is empty (contains no element).
Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that
|sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
|
#Python
|
Python
|
class Setr():
def __init__(self, lo, hi, includelo=True, includehi=False):
self.eqn = "(%i<%sX<%s%i)" % (lo,
'=' if includelo else '',
'=' if includehi else '',
hi)
def __contains__(self, X):
return eval(self.eqn, locals())
# union
def __or__(self, b):
ans = Setr(0,0)
ans.eqn = "(%sor%s)" % (self.eqn, b.eqn)
return ans
# intersection
def __and__(self, b):
ans = Setr(0,0)
ans.eqn = "(%sand%s)" % (self.eqn, b.eqn)
return ans
# difference
def __sub__(self, b):
ans = Setr(0,0)
ans.eqn = "(%sand not%s)" % (self.eqn, b.eqn)
return ans
def __repr__(self):
return "Setr%s" % self.eqn
sets = [
Setr(0,1, 0,1) | Setr(0,2, 1,0),
Setr(0,2, 1,0) & Setr(1,2, 0,1),
Setr(0,3, 1,0) - Setr(0,1, 0,0),
Setr(0,3, 1,0) - Setr(0,1, 1,1),
]
settexts = '(0, 1] ∪ [0, 2);[0, 2) ∩ (1, 2];[0, 3) − (0, 1);[0, 3) − [0, 1]'.split(';')
for s,t in zip(sets, settexts):
print("Set %s %s. %s" % (t,
', '.join("%scludes %i"
% ('in' if v in s else 'ex', v)
for v in range(3)),
s.eqn))
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#Factor
|
Factor
|
USING: combinators kernel lists lists.lazy math math.functions
math.ranges prettyprint sequences ;
: prime? ( n -- ? )
{
{ [ dup 2 < ] [ drop f ] }
{ [ dup even? ] [ 2 = ] }
[ 3 over sqrt 2 <range> [ mod 0 > ] with all? ]
} cond ;
! Create an infinite lazy list of primes.
: primes ( -- list ) 0 lfrom [ prime? ] lfilter ;
! Show the first fifteen primes.
15 primes ltake list>array .
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#FileMaker
|
FileMaker
|
#May 10th., 2018.
Set Error Capture [On]
Allow User Abort [Off]
# Set default number of minutes
Set Variable [$maxduration; Value:1]
# Ask user for a desired duration of the test
Show Custom Dialog [ "Setup";
"Enter the number of minutes (0,1-15, 6s increments) you would like this test to run.¶" &
"Hit any of the modifier-keys until the result-dialog appears, when you wish to break off the test.";
$maxduration ]
If [Get ( LastMessageChoice ) = 1]
# Set all start-variables
Set Variable [
$result;
Value: Let ( [
$start = Get ( CurrentTimeUTCMilliseconds ) ;
x = Ceiling ( Abs ( 10 * $maxduration ) ) / 10 ;
y = Case ( x < ,1 ; ,1 ; x > 15 ; 15 ; x ) ;
$time = y * 60000 ; // 1 minute = 60000 milliseconds
$number = 1 ;
$primenumbers = 2 ;
$duration = ""
] ;
""
)]
Loop
# Increase each iteration by 2 (besides 2 there are no even prime numbers)
# exit after duration is exceeded or when a modifier-key is actuated
Exit Loop If [ Let ( [
$number = $number + 2 ;
$i = 1
] ;
$duration > $time or
Get ( ActiveModifierKeys ) ≥ 1
)]
Loop
# Loop until it is determined that a number is or isn't a prime number or the duration is exceeded
# supplement $primenumbers each time one is found, update $duration each iteration
Exit Loop If [ Let ( [
$x = GetValue ( $primenumbers ; ValueCount ( $primenumbers ) - $i ) ;
$d = If ( $x > 0 ; $number / $x ) ;
$e = If ( Floor ( $d ) = $d ; $d ) ;
$i = $i + 1 ;
s = ( $x - 1 ) > $number/2 and $e = "" ;
$primenumbers = If ( $x = "" or s ;
List ( $primenumbers ; $number ) ;
$primenumbers ) ;
$duration = Get ( CurrentTimeUTCMilliseconds ) - $start
] ;
$x = "" or $e > 0 or s or $duration > $time
)]
End Loop
End Loop
# Count the number of primes found
Set Variable [
$result;
Value: Let ( [
$n = ValueCount ( $primenumbers ) ;
$$array = $primenumbers
] ;
""
)]
# Show results to user
Show Custom Dialog [ "Result";
List (
"Prime numbers found: " & $n ;
"Largest prime number: " & GetValue ( $primenumbers ; 1 ) ;
"Duration of test (ms): " & $duration )]
End If
#
|
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.
|
#D
|
D
|
import std.stdio, std.math, std.algorithm, std.range;
int nonSquare(in int n) pure nothrow @safe @nogc {
return n + cast(int)(0.5 + real(n).sqrt);
}
void main() {
iota(1, 23).map!nonSquare.writeln;
foreach (immutable i; 1 .. 1_000_000) {
immutable ns = i.nonSquare;
assert(ns != (cast(int)real(ns).sqrt) ^^ 2);
}
}
|
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
|
#Common_Lisp
|
Common Lisp
|
(setf a '(1 2 3 4))
(setf b '(2 3 4 5))
(format t "sets: ~a ~a~%" a b)
;;; element
(loop for x from 1 to 6 do
(format t (if (member x a)
"~d ∈ A~%"
"~d ∉ A~%") x))
(format t "A ∪ B: ~a~%" (union a b))
(format t "A ∩ B: ~a~%" (intersection a b))
(format t "A \\ B: ~a~%" (set-difference a b))
(format t (if (subsetp a b)
"~a ⊆ ~a~%"
"~a ⊈ ~a~%") a b)
(format t (if (and (subsetp a b)
(subsetp b a))
"~a = ~a~%"
"~a ≠ ~a~%") a b)
|
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
|
#AutoIt
|
AutoIt
|
#include <Array.au3>
$M = InputBox("Integer", "Enter biggest Integer")
Global $a[$M], $r[$M], $c = 1
For $i = 2 To $M -1
If Not $a[$i] Then
$r[$c] = $i
$c += 1
For $k = $i To $M -1 Step $i
$a[$k] = True
Next
EndIf
Next
$r[0] = $c - 1
ReDim $r[$c]
_ArrayDisplay($r)
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#REXX
|
REXX
|
/*REXX program demonstrates a method of set consolidating using some sample sets. */
@.=; @.1 = '{A,B} {C,D}'
@.2 = "{A,B} {B,D}"
@.3 = '{A,B} {C,D} {D,B}'
@.4 = '{H,I,K} {A,B} {C,D} {D,B} {F,G,H}'
@.5 = '{snow,ice,slush,frost,fog} {icebergs,icecubes} {rain,fog,sleet}'
do j=1 while @.j\=='' /*traipse through each of sample sets. */
call SETconsolidate @.j /*have the function do the heavy work. */
end /*j*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isIn: return wordpos(arg(1), arg(2))\==0 /*is (word) argument 1 in the set arg2?*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
SETconsolidate: procedure; parse arg old; #= words(old); new=
say ' the old set=' space(old)
do k=1 for # /* [↓] change all commas to a blank. */
!.k= translate( word(old, k), , '},{') /*create a list of words (aka, a set).*/
end /*k*/ /* [↑] ··· and also remove the braces.*/
do until \changed; changed= 0 /*consolidate some sets (well, maybe).*/
do set=1 for #-1
do item=1 for words(!.set); x= word(!.set, item)
do other=set+1 to #
if isIn(x, !.other) then do; changed= 1 /*it's changed*/
!.set= !.set !.other; !.other=
iterate set
end
end /*other*/
end /*item */
end /*set */
end /*until ¬changed*/
do set=1 for #; $= /*elide dups*/
do items=1 for words(!.set); x= word(!.set, items)
if x==',' then iterate; if x=='' then leave
$= $ x /*build new.*/
do until \isIn(x, !.set); _= wordpos(x, !.set)
_= wordpos(x, !.set)
!.set= subword(!.set, 1, _-1) ',' subword(!.set, _+1) /*purify set*/
end /*until ¬isIn ··· */
end /*items*/
!.set= translate( strip($), ',', " ")
end /*set*/
do i=1 for #; if !.i=='' then iterate /*ignore any set that is a null set. */
new= space(new '{'!.i"}") /*prepend and append a set identifier. */
end /*i*/
say ' the new set=' new; say
return
|
http://rosettacode.org/wiki/Show_ASCII_table
|
Show ASCII table
|
Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
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
|
#Prolog
|
Prolog
|
ascii :-
forall(between(32, 47, N), row(N)).
row(N) :- N > 127, nl, !.
row(N) :-
code(N),
ascii(N),
Nn is N + 16,
row(Nn).
code(N) :- N < 100, format(' ~d : ', N).
code(N) :- N >= 100, format(' ~d : ', N).
ascii(32) :- write(' Spc '), !.
ascii(127) :- write(' Del '), !.
ascii(A) :- char_code(D,A), format(' ~w ', D).
|
http://rosettacode.org/wiki/Sierpinski_triangle
|
Sierpinski triangle
|
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
|
#Scheme
|
Scheme
|
(define (sierpinski n)
(for-each
(lambda (x) (display (list->string x)) (newline))
(let loop ((acc (list (list #\*))) (spaces (list #\ )) (n n))
(if (zero? n)
acc
(loop
(append
(map (lambda (x) (append spaces x spaces)) acc)
(map (lambda (x) (append x (list #\ ) x)) acc))
(append spaces spaces)
(- n 1))))))
|
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
|
#PowerShell
|
PowerShell
|
function Draw-SierpinskiCarpet ( [int]$N )
{
$Carpet = @( '#' ) * [math]::Pow( 3, $N )
ForEach ( $i in 1..$N )
{
$S = [math]::Pow( 3, $i - 1 )
ForEach ( $Row in 0..($S-1) )
{
$Carpet[$Row+$S+$S] = $Carpet[$Row] * 3
$Carpet[$Row+$S] = $Carpet[$Row] + ( " " * $Carpet[$Row].Length ) + $Carpet[$Row]
$Carpet[$Row] = $Carpet[$Row] * 3
}
}
$Carpet
}
Draw-SierpinskiCarpet 3
|
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
|
#Eiffel
|
Eiffel
|
class
SEMORDNILAP
create
make
feature
make
--Semordnilaps in 'solution'.
local
count, i, middle, upper, lower: INTEGER
reverse: STRING
do
read_wordlist
create solution.make_empty
from
i := 1
until
i > word_array.count
loop
word_array [i].mirror
reverse := word_array [i]
from
lower := i + 1
upper := word_array.count
until
lower >= upper
loop
middle := (upper - lower) // 2 + lower
if reverse.same_string (word_array [middle]) then
count := count + 1
upper := 0
lower := 1
solution.force (word_array [i], count)
elseif reverse.is_less (word_array [middle]) then
upper := middle - 1
else
lower := middle + 1
end
end
if lower < word_array.count and then reverse.same_string (word_array [lower]) then
count := count + 1
upper := 0
lower := 1
solution.force (word_array [i], count)
end
i := i + 1
end
end
solution: ARRAY [STRING]
original_list: STRING = "unixdict.txt"
feature {NONE}
read_wordlist
-- Preprocessed word_array for finding Semordnilaps.
local
l_file: PLAIN_TEXT_FILE
wordlist: LIST [STRING]
do
create l_file.make_open_read_write (original_list)
l_file.read_stream (l_file.count)
wordlist := l_file.last_string.split ('%N')
l_file.close
create word_array.make_empty
across
1 |..| wordlist.count as i
loop
word_array.force (wordlist.at (i.item), i.item)
end
end
word_array: ARRAY [STRING]
end
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Simula
|
Simula
|
BEGIN
BOOLEAN PROCEDURE A(BOOL); BOOLEAN BOOL;
BEGIN OUTCHAR('A'); A := BOOL;
END A;
BOOLEAN PROCEDURE B(BOOL); BOOLEAN BOOL;
BEGIN OUTCHAR('B'); B := BOOL;
END B;
PROCEDURE OUTBOOL(BOOL); BOOLEAN BOOL;
OUTCHAR(IF BOOL THEN 'T' ELSE 'F');
PROCEDURE TEST;
BEGIN
PROCEDURE ANDTEST;
BEGIN
BOOLEAN X, Y, Z;
FOR X := TRUE, FALSE DO
FOR Y := TRUE, FALSE DO
BEGIN
OUTTEXT("A("); OUTBOOL(X);
OUTTEXT(") AND ");
OUTTEXT("B("); OUTBOOL(Y);
OUTTEXT("): ");
Z := A(X) AND THEN B(Y);
OUTIMAGE;
END;
END ANDTEST;
PROCEDURE ORTEST;
BEGIN
BOOLEAN X, Y, Z;
FOR X := TRUE, FALSE DO
FOR Y := TRUE, FALSE DO
BEGIN
OUTTEXT("A("); OUTBOOL(X);
OUTTEXT(") OR ");
OUTTEXT("B("); OUTBOOL(Y);
OUTTEXT("): ");
Z := A(X) OR ELSE B(Y);
OUTIMAGE;
END;
END ORTEST;
ANDTEST;
ORTEST;
END TEST;
TEST;
END.
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Smalltalk
|
Smalltalk
|
Smalltalk at: #a put: nil.
Smalltalk at: #b put: nil.
a := [:x| 'executing a' displayNl. x].
b := [:x| 'executing b' displayNl. x].
('false and false = %1' %
{ (a value: false) and: [ b value: false ] })
displayNl.
('true or false = %1' %
{ (a value: true) or: [ b value: false ] })
displayNl.
('false or true = %1' %
{ (a value: false) or: [ b value: true ] })
displayNl.
('true and false = %1' %
{ (a value: true) and: [ b value: false ] })
displayNl.
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#Phix
|
Phix
|
without js -- (libcurl)
include builtins\libcurl.e
constant USER = "[email protected]",
PWD = "secret",
URL = "smtps://smtp.gmail.com:465",
FROM = "[email protected]",
TO = "[email protected]",
CC = "[email protected]",
FMT = "Date: Mon, 13 Jun 2018 11:30:00 +0100\r\n"&
"To: %s\r\n"&
"From: %s (Example User)\r\n"&
"Cc: %s (Another example User)\r\n"&
"Subject: Sanding mail via Phix\r\n"&
"\r\n"&
"This mail is being sent by a Phix program.\r\n"&
"\r\n"&
"It connects to the GMail SMTP server, by far the most popular mail program of all.\r\n"&
"Which is, however, probably not written in Phix.\r\n"
function read_callback(atom pbuffer, integer size, nmemb, atom pUserData)
-- copy a maximum of size*nmemb bytes into pbuffer
if size==0 or nmemb==0 or size*nmemb<1 then return 0 end if
{integer sent, integer len, atom pPayload} = peekns({pUserData,3})
integer bytes_written = min(size*nmemb,len-sent)
mem_copy(pbuffer,pPayload+sent,bytes_written)
sent += bytes_written
pokeN(pUserData,sent,machine_word())
return bytes_written
end function
constant read_cb = call_back({'+',routine_id("read_callback")})
constant string payload_text = sprintf(FMT,{TO,FROM,CC})
curl_global_init()
CURLcode res = CURLE_OK
atom slist_recipients = NULL
atom curl = curl_easy_init()
curl_easy_setopt(curl, CURLOPT_USERNAME, USER)
curl_easy_setopt(curl, CURLOPT_PASSWORD, PWD)
curl_easy_setopt(curl, CURLOPT_URL, URL)
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL)
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0)
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0)
curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM)
slist_recipients = curl_slist_append(slist_recipients, TO)
slist_recipients = curl_slist_append(slist_recipients, CC)
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, slist_recipients)
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_cb);
atom pUserData = allocate(machine_word()*3),
pPayload = allocate_string(payload_text)
pokeN(pUserData,{0,length(payload_text),pPayload},machine_word())
curl_easy_setopt(curl, CURLOPT_READDATA, pUserData)
curl_easy_setopt(curl, CURLOPT_UPLOAD, true)
--curl_easy_setopt(curl, CURLOPT_VERBOSE, true)
res = curl_easy_perform(curl)
if res!=CURLE_OK then
printf(2, "curl_easy_perform() failed: %d (%s)\n",{res,curl_easy_strerror(res)})
end if
curl_slist_free_all(slist_recipients)
curl_easy_cleanup(curl)
curl_global_cleanup()
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#ERRE
|
ERRE
|
PROGRAM SEMIPRIME_NUMBER
!VAR I%
PROCEDURE SEMIPRIME(N%->RESULT%)
LOCAL F%,P%
P%=2
LOOP
EXIT IF NOT(F%<2 AND P%*P%<=N%)
WHILE (N% MOD P%)=0 DO
N%=N% DIV P%
F%+=1
END WHILE
P%+=1
END LOOP
RESULT%=F%-(N%>1)=2
END PROCEDURE
BEGIN
PRINT(CHR$(12);) !CLS
FOR I%=2 TO 100 DO
SEMIPRIME(I%->RESULT%)
IF RESULT% THEN PRINT(I%;) END IF
END FOR
PRINT
END PROGRAM
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#F.23
|
F#
|
let isSemiprime (n: int) =
let rec loop currentN candidateFactor numberOfFactors =
if numberOfFactors > 2 then numberOfFactors
elif currentN = candidateFactor then numberOfFactors+1
elif currentN % candidateFactor = 0 then loop (currentN/candidateFactor) candidateFactor (numberOfFactors+1)
else loop currentN (candidateFactor+1) numberOfFactors
if n < 2 then false else 2 = loop n 2 0
seq { 1 .. 100 } |> Seq.choose (fun n -> if isSemiprime n then Some(n) else None)
|> Seq.toList |> printfn "%A"
seq { 1675 .. 1680 }
|> Seq.choose (fun n -> if isSemiprime n then Some(n) else None)
|> Seq.toList
|> printfn "%A"
|
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
|
#AWK
|
AWK
|
function ord(a)
{
return amap[a]
}
function sedol_checksum(sed)
{
sw[1] = 1; sw[2] = 3; sw[3] = 1
sw[4] = 7; sw[5] = 3; sw[6] = 9
sum = 0
for(i=1; i <= 6; i++) {
c = substr(toupper(sed), i, 1)
if ( c ~ /[[:digit:]]/ ) {
sum += c*sw[i]
} else {
sum += (ord(c)-ord("A")+10)*sw[i]
}
}
return (10 - (sum % 10)) % 10
}
BEGIN { # prepare amap for ord
for(_i=0;_i<256;_i++) {
astr = sprintf("%c", _i)
amap[astr] = _i
}
}
/[AEIOUaeiou]/ {
print "'" $0 "' not a valid SEDOL code"
next
}
{
if ( (length($0) > 7) || (length($0) < 6) ) {
print "'" $0 "' is too long or too short to be valid SEDOL"
next
}
sedol = substr($0, 1, 6)
sedolcheck = sedol_checksum(sedol)
if ( length($0) == 7 ) {
if ( (sedol sedolcheck) != $0 ) {
print sedol sedolcheck " (original " $0 " has wrong check digit"
} else {
print sedol sedolcheck
}
} else {
print sedol sedolcheck
}
}
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Function selfDescribing (n As UInteger) As Boolean
If n = 0 Then Return False
Dim ns As String = Str(n)
Dim count(0 To 9) As Integer '' all elements zero by default
While n > 0
count(n Mod 10) += 1
n \= 10
Wend
For i As Integer = 0 To Len(ns) - 1
If ns[i] - 48 <> count(i) Then Return False '' numerals have ascii values from 48 to 57
Next
Return True
End Function
Print "The self-describing numbers less than 100 million are:"
For i As Integer = 0 To 99999999
If selfDescribing(i) Then Print i; " ";
Next
Print
Print "Press any key to quit"
Sleep
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#Go
|
Go
|
package main
import (
"fmt"
"strconv"
"strings"
)
// task 1 requirement
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}
return true
}
// task 2 code (takes a while to run)
func main() {
for n := int64(0); n < 1e10; n++ {
if sdn(n) {
fmt.Println(n)
}
}
}
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Perl
|
Perl
|
use strict;
use warnings;
use feature 'say';
use List::Util qw(max sum);
my ($i, $pow, $digits, $offset, $lastSelf, @selfs)
= ( 1, 10, 1, 9, 0, );
my $final = 50;
while () {
my $isSelf = 1;
my $sum = my $start = sum split //, max(($i-$offset), 0);
for ( my $j = $start; $j < $i; $j++ ) {
if ($j+$sum == $i) { $isSelf = 0 ; last }
($j+1)%10 != 0 ? $sum++ : ( $sum = sum split '', ($j+1) );
}
if ($isSelf) {
push @selfs, $lastSelf = $i;
last if @selfs == $final;
}
next unless ++$i % $pow == 0;
$pow *= 10;
$offset = 9 * $digits++
}
say "The first 50 self numbers are:\n" . join ' ', @selfs;
|
http://rosettacode.org/wiki/Set_of_real_numbers
|
Set of real numbers
|
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | a < x and x < b }
[a, b): {x | a ≤ x and x < b }
(a, b]: {x | a < x and x ≤ b }
Note that if a = b, of the four only [a, a] would be non-empty.
Task
Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
Provide methods for these common set operations (x is a real number; A and B are sets):
x ∈ A: determine if x is an element of A
example: 1 is in [1, 2), while 2, 3, ... are not.
A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B}
example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B}
example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B}
example: [0, 2) − (1, 3) = [0, 1]
Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
(0, 1] ∪ [0, 2)
[0, 2) ∩ (1, 2]
[0, 3) − (0, 1)
[0, 3) − [0, 1]
Implementation notes
'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
Optional work
Create a function to determine if a given set is empty (contains no element).
Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that
|sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
|
#Racket
|
Racket
|
#lang racket
;; Use a macro to allow infix operators
(require (only-in racket [#%app #%%app]))
(define-for-syntax infixes '())
(define-syntax (definfix stx)
(syntax-case stx ()
[(_ (x . xs) body ...) #'(definfix x (λ xs body ...))]
[(_ x body) (begin (set! infixes (cons #'x infixes)) #'(define x body))]))
(define-syntax (#%app stx)
(syntax-case stx ()
[(_ X op Y)
(and (identifier? #'op) (ormap (λ(o) (free-identifier=? #'op o)) infixes))
#'(#%%app op X Y)]
[(_ f x ...) #'(#%%app f x ...)]))
;; Ranges: (X +-+ Y) => [X,Y]; (X --- Y) => (X,Y); and same for `+--' and `--+'
;; Simple implementation as functions
;; Constructors
(definfix ((+-+ X Y) n) (<= X n Y)) ; [X,Y]
(definfix ((--- X Y) n) (< X n Y)) ; (X,Y)
(definfix ((+-- X Y) n) (and (<= X n) (< n Y))) ; [X,Y)
(definfix ((--+ X Y) n) (and (< X n) (<= n Y))) ; (X,Y]
(definfix ((== X) n) (= X n)) ; [X,X]
;; Set operations
(definfix ((∪ . Rs) n) (ormap (λ(p) (p n)) Rs))
(definfix ((∩ . Rs) n) (andmap (λ(p) (p n)) Rs))
(definfix ((∖ R1 R2) n) (and (R1 n) (not (R2 n)))) ; set-minus, not backslash
(define ((¬ R) n) (not (R n)))
;; Special sets
(define (∅ n) #f)
(define (ℜ n) #t)
(define-syntax-rule (try set)
(apply printf "~a => ~a ~a ~a\n" (~s #:width 23 'set)
(let ([pred set]) (for/list ([i 3]) (if (pred i) 'Y 'N)))))
(try ((0 --+ 1) ∪ (0 +-- 2)))
(try ((0 +-- 2) ∩ (1 --+ 2)))
(try ((0 +-- 3) ∖ (0 --- 1)))
(try ((0 +-- 3) ∖ (0 +-+ 1)))
|
http://rosettacode.org/wiki/Set_of_real_numbers
|
Set of real numbers
|
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | a < x and x < b }
[a, b): {x | a ≤ x and x < b }
(a, b]: {x | a < x and x ≤ b }
Note that if a = b, of the four only [a, a] would be non-empty.
Task
Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
Provide methods for these common set operations (x is a real number; A and B are sets):
x ∈ A: determine if x is an element of A
example: 1 is in [1, 2), while 2, 3, ... are not.
A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B}
example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B}
example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B}
example: [0, 2) − (1, 3) = [0, 1]
Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
(0, 1] ∪ [0, 2)
[0, 2) ∩ (1, 2]
[0, 3) − (0, 1)
[0, 3) − [0, 1]
Implementation notes
'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
Optional work
Create a function to determine if a given set is empty (contains no element).
Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that
|sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
|
#Raku
|
Raku
|
class Iv {
has $.range handles <min max excludes-min excludes-max minmax ACCEPTS>;
method empty {
$.min after $.max or $.min === $.max && ($.excludes-min || $.excludes-max)
}
multi method Bool() { not self.empty };
method length() { $.max - $.min }
method gist() {
($.excludes-min ?? '(' !! '[') ~
$.min ~ ',' ~ $.max ~
($.excludes-max ?? ')' !! ']');
}
}
class IvSet {
has Iv @.intervals;
sub canon (@i) {
my @new = consolidate(|@i).grep(*.so);
@new.sort(*.range.min);
}
method new(@ranges) {
my @iv = canon @ranges.map: { Iv.new(:range($_)) }
self.bless(:intervals(@iv));
}
method complement {
my @new;
my @old = @!intervals;
if not @old {
return iv -Inf..Inf;
}
my $pre;
push @old, Inf^..Inf unless @old[*-1].max === Inf;
if @old[0].min === -Inf {
$pre = @old.shift;
}
else {
$pre = -Inf..^-Inf;
}
while @old {
my $old = @old.shift;
my $excludes-min = !$pre.excludes-max;
my $excludes-max = !$old.excludes-min;
push @new, Range.new($pre.max,$old.min,:$excludes-min,:$excludes-max);
$pre = $old;
}
IvSet.new(@new);
}
method ACCEPTS(IvSet:D $me: $candidate) {
so $.intervals.any.ACCEPTS($candidate);
}
method empty { so $.intervals.all.empty }
multi method Bool() { not self.empty };
method length() { [+] $.intervals».length }
method gist() { join ' ', $.intervals».gist }
}
sub iv(**@ranges) { IvSet.new(@ranges) }
multi infix:<∩> (Iv $a, Iv $b) {
if $a.min ~~ $b or $a.max ~~ $b or $b.min ~~ $a or $b.max ~~ $a {
my $min = $a.range.min max $b.range.min;
my $max = $a.range.max min $b.range.max;
my $excludes-min = not $min ~~ $a & $b;
my $excludes-max = not $max ~~ $a & $b;
Iv.new(:range(Range.new($min,$max,:$excludes-min, :$excludes-max)));
}
}
multi infix:<∪> (Iv $a, Iv $b) {
my $min = $a.range.min min $b.range.min;
my $max = $a.range.max max $b.range.max;
my $excludes-min = not $min ~~ $a | $b;
my $excludes-max = not $max ~~ $a | $b;
Iv.new(:range(Range.new($min,$max,:$excludes-min, :$excludes-max)));
}
multi infix:<∩> (IvSet $ars, IvSet $brs) {
my @overlap;
for $ars.intervals -> $a {
for $brs.intervals -> $b {
if $a.min ~~ $b or $a.max ~~ $b or $b.min ~~ $a or $b.max ~~ $a {
my $min = $a.range.min max $b.range.min;
my $max = $a.range.max min $b.range.max;
my $excludes-min = not $min ~~ $a & $b;
my $excludes-max = not $max ~~ $a & $b;
push @overlap, Range.new($min,$max,:$excludes-min, :$excludes-max);
}
}
}
IvSet.new(@overlap)
}
multi infix:<∪> (IvSet $a, IvSet $b) {
iv |$a.intervals».range, |$b.intervals».range;
}
multi consolidate() { () }
multi consolidate($this is copy, *@those) {
gather {
for consolidate |@those -> $that {
if $this ∩ $that { $this ∪= $that }
else { take $that }
}
take $this;
}
}
multi infix:<−> (IvSet $a, IvSet $b) { $a ∩ $b.complement }
multi prefix:<−> (IvSet $a) { $a.complement; }
constant ℝ = iv -Inf..Inf;
my $s1 = iv(0^..1) ∪ iv(0..^2);
my $s2 = iv(0..^2) ∩ iv(1^..2);
my $s3 = iv(0..^3) − iv(0^..^1);
my $s4 = iv(0..^3) − iv(0..1) ;
say "\t\t\t\t0\t1\t2";
say "(0, 1] ∪ [0, 2) -> $s1.gist()\t", 0 ~~ $s1,"\t", 1 ~~ $s1,"\t", 2 ~~ $s1;
say "[0, 2) ∩ (1, 2] -> $s2.gist()\t", 0 ~~ $s2,"\t", 1 ~~ $s2,"\t", 2 ~~ $s2;
say "[0, 3) − (0, 1) -> $s3.gist()\t", 0 ~~ $s3,"\t", 1 ~~ $s3,"\t", 2 ~~ $s3;
say "[0, 3) − [0, 1] -> $s4.gist()\t", 0 ~~ $s4,"\t", 1 ~~ $s4,"\t", 2 ~~ $s4;
say '';
say "ℝ is not empty: ", !ℝ.empty;
say "[0,3] − ℝ is empty: ", not iv(0..3) − ℝ;
my $A = iv(0..10) ∩
iv |(0..10).map({ $_ - 1/6 .. $_ + 1/6 }).cache;
my $B = iv 0..sqrt(1/6),
|(1..99).map({ sqrt($_-1/6) .. sqrt($_ + 1/6) }), sqrt(100-1/6)..10;
say 'A − A is empty: ', not $A − $A;
say '';
my $C = $A − $B;
say "A − B =";
say " ",.gist for $C.intervals;
say "Length A − B = ", $C.length;
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#Forth
|
Forth
|
variable p-start \ beginning of prime buffer
variable p-end \ end of prime buffer
: +prime ( n -- )
p-end @ tuck ! cell+ p-end ! ;
: setup-pgen ( addr n -- n )
dup 3 < abort" The buffer must be large enough to store at least three primes."
swap dup p-start ! p-end !
2 +prime 3 +prime 5 +prime 3 - ;
: sq s" dup *" evaluate ; immediate
: prime? ( n -- f ) \ test a candidate for primality.
>r p-start @ [ 2 cells ] literal + begin
dup @ dup ( a -- a n n )
sq r@ > if rdrop 2drop true exit then
r@ swap mod 0= if rdrop drop false exit then
cell+
again ;
: ?+prime ( n1 n2 -- n1 n2 ) \ add n2 to output array if prime and n1 != 0
dup prime? over 0<> and
if
dup +prime swap 1- swap
then ;
: genprimes ( addr n -- ) \ store first n primes at address "addr"
setup-pgen 7 \ stack: #found, candidate
begin
?+prime 4 + ?+prime 2 +
over 0= until 2drop ;
: .primes ( n -- )
pad swap 2dup genprimes
cells bounds do
i pad - [ 10 cells ] literal mod 0= if cr then
i @ 5 .r
cell +loop ;
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#Fortran
|
Fortran
|
CONCOCTED BY R.N.MCLEAN, APPLIED MATHS COURSE, AUCKLAND UNIVERSITY, MCMLXXI.
INTEGER ENUFF,PRIME(44)
CALCULATION SHOWS PRIME(43) = 181, AND PRIME(44) = 191.
INTEGER N,F,Q,XP2
INTEGER INC,IP,LP,PP
INTEGER ALINE(20),LL,I
DATA ENUFF/44/
DATA PP/4/
DATA PRIME(1),PRIME(2),PRIME(3),PRIME(4)/1,2,3,5/
COPY THE KNOWN PRIMES TO THE OUTPUT LINE.
DO 1 I = 1,PP
1 ALINE(I) = PRIME(I)
LL = PP
LP = 3
XP2 = PRIME(LP + 1)**2
N = 5
INC = 4
CONSIDER ANOTHER CANDIDATE. VIA INC, DODGE MULTIPLES OF 2 AND 3.
10 INC = 6 - INC
N = N + INC
IF (N - XP2) 20,11,20
11 LP = LP + 1
XP2 = PRIME(LP + 1)**2
GO TO 40
CHECK SUCCESSIVE PRIMES AS FACTORS, STARTING WITH PRIME(4) = 5.
20 IP = 4
21 F = PRIME(IP)
Q = N/F
IF (Q*F - N) 22,40,22
22 IP = IP + 1
IF (IP - LP) 21,21,30
CAUGHT ANOTHER PRIME.
30 IF (PP - ENUFF) 31,32,32
31 PP = PP + 1
PRIME(PP) = N
32 IF (LL - 20) 35,33,33
33 WRITE (6,34) (ALINE(I), I = 1,LL)
34 FORMAT (20I6)
LL = 0
35 LL = LL + 1
ALINE(LL) = N
COMPLETED?
40 IF (N - 32767) 10,41,41
41 WRITE (6,34) (ALINE(I), I = 1,LL)
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.
|
#Delphi
|
Delphi
|
program Sequence_of_non_squares;
uses
System.SysUtils, System.Math;
function nonsqr(i: Integer): Integer;
begin
Result := Trunc(i + Floor(0.5 + Sqrt(i)));
end;
var
i: Integer;
j: Double;
begin
for i := 1 to 22 do
write(nonsqr(i), ' ');
Writeln;
for i := 1 to 999999 do
begin
j := Sqrt(nonsqr(i));
if (j = Floor(j)) then
Writeln(i, 'Is Square');
end;
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
|
#D
|
D
|
void main() {
import std.stdio, std.algorithm, std.range;
// Not true sets, items can be repeated, but must be sorted.
auto s1 = [1, 2, 3, 4, 5, 6].assumeSorted;
auto s2 = [2, 5, 6, 3, 4, 8].sort(); // [2,3,4,5,6,8].
auto s3 = [1, 2, 5].assumeSorted;
assert(s1.canFind(4)); // Linear search.
assert(s1.contains(4)); // Binary search.
assert(s1.setUnion(s2).equal([1,2,2,3,3,4,4,5,5,6,6,8]));
assert(s1.setIntersection(s2).equal([2, 3, 4, 5, 6]));
assert(s1.setDifference(s2).equal([1]));
assert(s1.setSymmetricDifference(s2).equal([1, 8]));
assert(s3.setDifference(s1).empty); // It's a subset.
assert(!s1.equal(s2));
auto s4 = [[1, 4, 7, 8], [1, 7], [1, 7, 8], [4], [7]];
const s5 = [1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8];
assert(s4.nWayUnion.equal(s5));
}
|
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
|
#AWK
|
AWK
|
$ awk '{for(i=2;i<=$1;i++) a[i]=1;
> for(i=2;i<=sqrt($1);i++) for(j=2;j<=$1;j++) delete a[i*j];
> for(i in a) printf i" "}'
100
71 53 17 5 73 37 19 83 47 29 7 67 59 11 97 79 89 31 13 41 23 2 61 43 3
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Ring
|
Ring
|
# Project : Set consolidation
load "stdlib.ring"
test = ["AB","AB,CD","AB,CD,DB","HIK,AB,CD,DB,FGH"]
for t in test
see consolidate(t) + nl
next
func consolidate(s)
sets = split(s,",")
n = len(sets)
for i = 1 to n
p = i
ts = ""
for j = i to 1 step -1
if ts = ""
p = j
ok
ts = ""
for k = 1 to len(sets[p])
if j > 1
if substring(sets[j-1],substr(sets[p],k,1),1) = 0
ts = ts + substr(sets[p],k,1)
ok
ok
next
if len(ts) < len(sets[p])
if j > 1
sets[j-1] = sets[j-1] + ts
sets[p] = "-"
ts = ""
ok
else
p = i
ok
next
next
consolidate = s + " = " + substr(list2str(sets),nl,",")
return consolidate
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Ruby
|
Ruby
|
require 'set'
tests = [[[:A,:B], [:C,:D]],
[[:A,:B], [:B,:D]],
[[:A,:B], [:C,:D], [:D,:B]],
[[:H,:I,:K], [:A,:B], [:C,:D], [:D,:B], [:F,:G,:H]]]
tests.map!{|sets| sets.map(&:to_set)}
tests.each do |sets|
until sets.combination(2).none?{|a,b| a.merge(b) && sets.delete(b) if a.intersect?(b)}
end
p sets
end
|
http://rosettacode.org/wiki/Show_ASCII_table
|
Show ASCII table
|
Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
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
|
#PureBasic
|
PureBasic
|
If OpenConsole("Show_Ascii_table: rosettacode.org")
Define r.i, c.i
For r=0 To 15
For c=32+r To 112+r Step 16
Print(RSet(Str(c),3)+" : ")
Select c
Case 32
Print("Spc")
Case 127
Print("Del")
Default
Print(LSet(Chr(c),3))
EndSelect
Print(Space(3))
Next
PrintN("")
Next
Input()
EndIf
|
http://rosettacode.org/wiki/Sierpinski_triangle
|
Sierpinski triangle
|
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const func array string: sierpinski (in integer: n) is func
result
var array string: parts is 1 times "*";
local
var integer: i is 0;
var string: space is " ";
var array string: parts2 is 0 times "";
var string: x is "";
begin
for i range 1 to n do
parts2 := 0 times "";
for x range parts do
parts2 &:= [] (space & x & space);
end for;
for x range parts do
parts2 &:= [] (x & " " & x);
end for;
parts := parts2;
space &:= space;
end for;
end func;
const proc: main is func
begin
writeln(join(sierpinski(4), "\n"));
end func;
|
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
|
#Processing
|
Processing
|
float delta;
void setup() {
size(729, 729);
fill(0);
background(255);
noStroke();
rect(width/3, height/3, width/3, width/3);
rectangles(width/3, height/3, width/3);
}
void rectangles(int x, int y, int s) {
if (s < 1) return;
int xc = x-s;
int yc = y-s;
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
if (!(row == 1 && col == 1)) {
int xx = xc+row*s;
int yy = yc+col*s;
delta = s/3;
rect(xx+delta, yy+delta, delta, delta);
rectangles(xx+s/3, yy+s/3, s/3);
}
}
}
}
|
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
|
#Elixir
|
Elixir
|
words = File.stream!("unixdict.txt")
|> Enum.map(&String.strip/1)
|> Enum.group_by(&min(&1, String.reverse &1))
|> Map.values
|> Enum.filter(&(length &1) == 2)
IO.puts "Semordnilap pair: #{length(words)}"
IO.inspect Enum.take(words,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
|
#Erlang
|
Erlang
|
#!/usr/bin/env escript
main([]) -> main(["unixdict.txt"]);
main([DictFile]) ->
Dict = sets:from_list(read_lines(DictFile)),
Semordnilaps =
lists:filter(fun([W,R]) -> W < R end,
lists:map(fun(W) -> [W, lists:reverse(W)] end,
semordnilaps(Dict))),
io:fwrite("There are ~b semordnilaps in ~s~n",
[length(Semordnilaps), DictFile]),
lists:map(fun([W,R]) -> io:fwrite("~s/~s~n", [W, R]) end,
lists:sort(lists:sublist(shuffle(Semordnilaps),1,5))).
read_lines(Filename) when is_list(Filename) ->
{ ok, File } = file:open(Filename, [read]),
read_lines(File);
read_lines(File) when is_pid(File) ->
case file:read_line(File) of
{ok, Data} -> [chop(Data) | read_lines(File)];
eof -> []
end.
is_semordnilap(Word, Dict) ->
Rev = lists:reverse(Word),
sets:is_element(Word, Dict) and sets:is_element(Rev, Dict).
semordnilaps(Dict) ->
lists:filter(fun(W) -> is_semordnilap(W, Dict) end, sets:to_list(Dict)).
shuffle(List) ->
[X||{_,X} <- lists:sort([ {random:uniform(), N} || N <- List])].
chop(L) -> [_|T] = lists:reverse(L), lists:reverse(T).
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#SNOBOL4
|
SNOBOL4
|
define('a(val)') :(a_end)
a out = 'A '
eq(val,1) :s(return)f(freturn)
a_end
define('b(val)') :(b_end)
b out = 'B '
eq(val,1) :s(return)f(freturn)
b_end
* # Test and display
&fullscan = 1
output(.out,1,'-[-r1]') ;* Macro Spitbol
* output(.out,1,'B','-') ;* CSnobol
define('nl()'):(nlx);nl output = :(return);nlx
out = 'T and T: '; null ? *a(1) *b(1); nl()
out = 'T and F: '; null ? *a(1) *b(0); nl()
out = 'F and T: '; null ? *a(0) *b(1); nl()
out = 'F and F: '; null ? *a(0) *b(0); nl()
output =
out = 'T or T: '; null ? *a(1) | *b(1); nl()
out = 'T or F: '; null ? *a(1) | *b(0); nl()
out = 'F or T: '; null ? *a(0) | *b(1); nl()
out = 'F or F: '; null ? *a(0) | *b(0); nl()
end
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Standard_ML
|
Standard ML
|
fun a r = ( print " > function a called\n"; r )
fun b r = ( print " > function b called\n"; r )
fun test_and b1 b2 = (
print ("# testing (" ^ Bool.toString b1 ^ " andalso " ^ Bool.toString b2 ^ ")\n");
ignore (a b1 andalso b b2) )
fun test_or b1 b2 = (
print ("# testing (" ^ Bool.toString b1 ^ " orelse " ^ Bool.toString b2 ^ ")\n");
ignore (a b1 orelse b b2) )
fun test_this test = (
test true true;
test true false;
test false true;
test false false )
;
print "==== Testing and ====\n";
test_this test_and;
print "==== Testing or ====\n";
test_this test_or;
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#PHP
|
PHP
|
mail('[email protected]', 'My Subject', "A Message!", "From: [email protected]");
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#PicoLisp
|
PicoLisp
|
(mail "localhost" 25 "[email protected]" "[email protected]" "Subject" NIL "Hello")
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#Pike
|
Pike
|
int main(){
string to = "[email protected]";
string subject = "Hello There.";
string from = "[email protected]";
string msg = "Hello there! :)";
Protocols.SMTP.Client()->simple_mail(to,subject,from,msg);
}
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#Factor
|
Factor
|
USING: io kernel math.primes.factors prettyprint sequences ;
: semiprime? ( n -- ? ) factors length 2 = ;
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#Forth
|
Forth
|
: semiprime?
0 swap dup 2 do
begin dup i mod 0= while i / swap 1+ swap repeat
over 1 > over i dup * < or if leave then
loop 1 > abs + 2 =
;
: test 100 2 do i semiprime? if i . then loop cr ;
|
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
|
#BASIC
|
BASIC
|
DECLARE FUNCTION getSedolCheckDigit! (str AS STRING)
DO
INPUT a$
PRINT a$ + STR$(getSedolCheckDigit(a$))
LOOP WHILE a$ <> ""
FUNCTION getSedolCheckDigit (str AS STRING)
IF LEN(str) <> 6 THEN
PRINT "Six chars only please"
EXIT FUNCTION
END IF
str = UCASE$(str)
DIM mult(6) AS INTEGER
mult(1) = 1: mult(2) = 3: mult(3) = 1
mult(4) = 7: mult(5) = 3: mult(6) = 9
total = 0
FOR i = 1 TO 6
s$ = MID$(str, i, 1)
IF s$ = "A" OR s$ = "E" OR s$ = "I" OR s$ = "O" OR s$ = "U" THEN
PRINT "No vowels"
EXIT FUNCTION
END IF
IF ASC(s$) >= 48 AND ASC(s$) <= 57 THEN
total = total + VAL(s$) * mult(i)
ELSE
total = total + (ASC(s$) - 55) * mult(i)
END IF
NEXT i
getSedolCheckDigit = (10 - (total MOD 10)) MOD 10
END FUNCTION
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#Haskell
|
Haskell
|
import Data.Char
count :: Int -> [Int] -> Int
count x = length . filter (x ==)
isSelfDescribing :: Integer -> Bool
isSelfDescribing n = nu == f
where
nu = digitToInt <$> show n
f = (`count` nu) <$> [0 .. length nu - 1]
main :: IO ()
main = do
print $
isSelfDescribing <$>
[1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000]
print $ filter isSelfDescribing [0 .. 4000000]
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Phix
|
Phix
|
--
-- Base-10 self numbers by index (single or range).
-- Follows an observed sequence pattern whereby, after the initial single-digit odd numbers, self numbers are
-- grouped in runs whose members occur at numeric intervals of 11. Runs after the first one come in blocks of
-- ten: eight runs of ten numbers followed by two shorter runs. The numeric interval between runs is usually 2,
-- but that between shorter runs, and their length, depend on the highest-order digit change occurring in them.
-- This connection with significant digit change means every ten blocks form a higher-order block, every ten
-- of these a higher-order-still block, and so on.
--
-- The code below appears to be good up to the last self number before 10^12 — ie. 999,999,999,997, which is
-- returned as the 97,777,777,792nd such number. After this, instead of zero-length shorter runs, the actual
-- pattern apparently starts again with a single run of 10, like the one at the beginning.
--
integer startIndex, endIndex, counter
atom currentSelf
sequence output
function doneAfterAdding(integer interval, n)
-- Advance to the next self number in the sequence, append it to the output if required, indicate if finished.
for i=1 to n do
currentSelf += interval
counter += 1
if counter >= startIndex then
output &= currentSelf
end if
if counter = endIndex then return true end if
end for
return false
end function
function selfNumbers(sequence indexRange)
startIndex = indexRange[1]
endIndex = indexRange[$]
counter = 0
currentSelf = -1
output = {}
-- Main process. Start with the single-digit odd numbers and first run.
if doneAfterAdding(2,5) then return output end if
if doneAfterAdding(11,9) then return output end if
-- If necessary, fast forward to last self number before the lowest-order block containing first number rqd.
if counter<startIndex then
-- The highest-order blocks whose ends this handles correctly contain 9,777,777,778 self numbers.
-- The difference between equivalently positioned numbers in these blocks is 100,000,000,001.
-- The figures for successively lower-order blocks have successively fewer 7s and 0s!
atom indexDiff = 9777777778,
numericDiff = 100000000001
while indexDiff>=98 and counter!=startIndex do
if counter+indexDiff < startIndex then
counter += indexDiff
currentSelf += numericDiff
else
indexDiff = (indexDiff+2)/10 -- (..78->80->8)
numericDiff = (numericDiff+9)/10 -- (..01->10->1)
end if
end while
end if
-- Sequencing loop, per lowest-order block.
while true do
-- Eight ten-number runs, each at a numeric interval of 2 from the end of the previous one.
for i=1 to 8 do
if doneAfterAdding(2,1) then return output end if
if doneAfterAdding(11,9) then return output end if
end for
-- Two shorter runs, the second at an interval inversely related to their length.
integer shorterRunLength = 8,
temp = floor(currentSelf/1000)
-- Work out a shorter run length based on the most significant digit change about to happen.
while remainder(temp,10)=9 do
shorterRunLength -= 1
temp = floor(temp/10)
end while
integer interval = 2
for i=1 to 2 do
if doneAfterAdding(interval,1) then return output end if
if doneAfterAdding(11,shorterRunLength) then return output end if
interval += (9-shorterRunLength)*13
end for
end while
end function
atom t0 = time()
printf(1,"The first 50 self numbers are:\n")
pp(selfNumbers({1, 50}),{pp_IntFmt,"%3d",pp_IntCh,false})
for p=8 to 9 do
integer n = power(10,p)
printf(1,"The %,dth safe number is %,d\n",{n,selfNumbers({n})[1]})
end for
printf(1,"completed in %s\n",elapsed(time()-t0))
|
http://rosettacode.org/wiki/Set_of_real_numbers
|
Set of real numbers
|
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | a < x and x < b }
[a, b): {x | a ≤ x and x < b }
(a, b]: {x | a < x and x ≤ b }
Note that if a = b, of the four only [a, a] would be non-empty.
Task
Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
Provide methods for these common set operations (x is a real number; A and B are sets):
x ∈ A: determine if x is an element of A
example: 1 is in [1, 2), while 2, 3, ... are not.
A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B}
example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B}
example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B}
example: [0, 2) − (1, 3) = [0, 1]
Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
(0, 1] ∪ [0, 2)
[0, 2) ∩ (1, 2]
[0, 3) − (0, 1)
[0, 3) − [0, 1]
Implementation notes
'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
Optional work
Create a function to determine if a given set is empty (contains no element).
Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that
|sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
|
#REXX
|
REXX
|
/*REXX program demonstrates a way to represent any set of real numbers and usage. */
call quertySet 1, 3, '[1,2)'
call quertySet , , '[0,2) union (1,3)'
call quertySet , , '[0,1) union (2,3]'
call quertySet , , '[0,2] inter (1,3)'
call quertySet , , '(1,2) ∩ (2,3]'
call quertySet , , '[0,2) \ (1,3)'
say; say center(' start of required tasks ', 40, "═")
call quertySet , , '(0,1] union [0,2)'
call quertySet , , '[0,2) ∩ (1,3)'
call quertySet , , '[0,3] - (0,1)'
call quertySet , , '[0,3] - [0,1]'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
emptySet: parse arg _; nam= valSet(_, 00); return @.3>@.4
/*──────────────────────────────────────────────────────────────────────────────────────*/
isInSet: parse arg #,x; call valSet x
if \datatype(#, 'N') then call set_bad "number isn't not numeric:" #
if (@.1=='(' & #<[email protected]) |,
(@.1=='[' & #< @.2) |,
(@.4==')' & #>[email protected]) |,
(@.4==']' & #> @.3) then return 0
return 1
/*──────────────────────────────────────────────────────────────────────────────────────*/
quertySet: parse arg lv,hv,s1 oop s2 .; op=oop; upper op; cop=
if lv=='' then lv=0; if hv=="" then hv= 2; if op=='' then cop= 0
if wordpos(op, '| or UNION') \==0 then cop= "|"
if wordpos(op, '& ∩ AND INTER INTERSECTION') \==0 then cop= "&"
if wordpos(op, '\ - DIF DIFF DIFFERENCE') \==0 then cop= "\"
say
do i=lv to hv; b = isInSet(i, s1)
if cop\==0 then do
b2= isInSet(i, s2)
if cop=='&' then b= b & b2
if cop=='|' then b= b | b2
if cop=='\' then b= b & \b2
end
express = s1 center(oop, max(5, length(oop) ) ) s2
say right(i, 5) ' is in set' express": " word('no yes', b+1)
end /*i*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
valSet: parse arg q; q=space(q, 0); L=length(q); @.0= ','; @.4= right(q,1)
parse var q @.1 2 @.2 ',' @.3 (@.4)
if @.2>@.3 then parse var L . @.0 @.2 @.3
return space(@.1 @.2 @.0 @.3 @.4, 0)
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Function isPrime(n As Integer) As Boolean
If n < 2 Then Return False
If n = 2 Then Return True
If n Mod 2 = 0 Then Return False
Dim limit As Integer = Sqr(n)
For i As Integer = 3 To limit Step 2
If n Mod i = 0 Then Return False
Next
Return True
End Function
' Print all primes from 101 to 999
For i As Integer = 101 To 999
If isPrime(i) Then
Print Str(i); " ";
End If
Next
Print : Print
Print "Press any key to quit"
Sleep
|
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.
|
#EchoLisp
|
EchoLisp
|
(lib 'sequences)
(define (a n) (+ n (floor (+ 0.5 (sqrt n)))))
(define A000037 (iterator/n a 1))
(take A000037 22)
→ (2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
(filter square? (take A000037 1000000))
→ null
|
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.
|
#Eiffel
|
Eiffel
|
class
APPLICATION
create
make
feature
make
do
sequence_of_non_squares (22)
io.new_line
sequence_of_non_squares (1000000)
end
sequence_of_non_squares (n: INTEGER)
-- Sequence of non-squares up to the n'th member.
require
n_positive: n >= 1
local
non_sq, part: REAL_64
math: DOUBLE_MATH
square: BOOLEAN
do
create math
across
1 |..| (n) as c
loop
part := (0.5 + math.sqrt (c.item.to_double))
non_sq := c.item + part.floor
io.put_string (non_sq.out + "%N")
if math.sqrt (non_sq) - math.sqrt (non_sq).floor = 0 then
square := True
end
end
if square = True then
io.put_string ("There are squares for n equal to " + n.out + ".")
else
io.put_string ("There are no squares for n equal to " + n.out + ".")
end
end
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
|
#Dart
|
Dart
|
void main(){
//Set Creation
Set A = new Set.from([1,2,3]);
Set B = new Set.from([1,2,3,4,5]);
Set C = new Set.from([1,2,4,5]);
print('Set A = $A');
print('Set B = $B');
print('Set C = $C');
print('');
//Test if element is in set
int m = 3;
print('m = 5');
print('m in A = ${A.contains(m)}');
print('m in B = ${B.contains(m)}');
print('m in C = ${C.contains(m)}');
print('');
//Union of two sets
Set AC = A.union(C);
print('Set AC = Union of A and C = $AC');
print('');
//Intersection of two sets
Set A_C = A.intersection(C);
print('Set A_C = Intersection of A and C = $A_C');
print('');
//Difference of two sets
Set A_diff_C = A.difference(C);
print('Set A_diff_C = Difference between A and C = $A_diff_C');
print('');
//Test if set is subset of another set
print('A is a subset of B = ${B.containsAll(A)}');
print('C is a subset of B = ${B.containsAll(C)}');
print('A is a subset of C = ${C.containsAll(A)}');
print('');
//Test if two sets are equal
print('A is equal to B = ${B.containsAll(A) && A.containsAll(B)}');
print('B is equal to AC = ${B.containsAll(AC) && AC.containsAll(B)}');
}
|
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
|
#Bash
|
Bash
|
DIM n AS Integer, k AS Integer, limit AS Integer
INPUT "Enter number to search to: "; limit
DIM flags(limit) AS Integer
FOR n = 2 TO SQR(limit)
IF flags(n) = 0 THEN
FOR k = n*n TO limit STEP n
flags(k) = 1
NEXT k
END IF
NEXT n
' Display the primes
FOR n = 2 TO limit
IF flags(n) = 0 THEN PRINT n; ", ";
NEXT n
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Scala
|
Scala
|
object SetConsolidation extends App {
def consolidate[Type](sets: Set[Set[Type]]): Set[Set[Type]] = {
var result = sets // each iteration combines two sets and reiterates, else returns
for (i <- sets; j <- sets - i; k = i.intersect(j);
if result == sets && k.nonEmpty) result = result - i - j + i.union(j)
if (result == sets) sets else consolidate(result)
}
// Tests:
def parse(s: String) =
s.split(",").map(_.split("").toSet).toSet
def pretty[Type](sets: Set[Set[Type]]) =
sets.map(_.mkString("{",",","}")).mkString(" ")
val tests = List(
parse("AB,CD") -> Set(Set("A", "B"), Set("C", "D")),
parse("AB,BD") -> Set(Set("A", "B", "D")),
parse("AB,CD,DB") -> Set(Set("A", "B", "C", "D")),
parse("HIK,AB,CD,DB,FGH") -> Set(Set("A", "B", "C", "D"), Set("F", "G", "H", "I", "K"))
)
require(Set("A", "B", "C", "D") == Set("B", "C", "A", "D"))
assert(tests.forall{case (test, expect) =>
val result = consolidate(test)
println(s"${pretty(test)} -> ${pretty(result)}")
expect == result
})
}
|
http://rosettacode.org/wiki/Show_ASCII_table
|
Show ASCII table
|
Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
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
|
#Python
|
Python
|
for i in range(16):
for j in range(32+i, 127+1, 16):
if j == 32:
k = 'Spc'
elif j == 127:
k = 'Del'
else:
k = chr(j)
print("%3d : %-3s" % (j,k), end="")
print()
|
http://rosettacode.org/wiki/Sierpinski_triangle
|
Sierpinski triangle
|
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
|
#Sidef
|
Sidef
|
func sierpinski_triangle(n) {
var triangle = ['*']
{ |i|
var sp = (' ' * 2**i)
triangle = (triangle.map {|x| sp + x + sp} +
triangle.map {|x| x + ' ' + x})
} * n
triangle.join("\n")
}
say sierpinski_triangle(4)
|
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
|
#Prolog
|
Prolog
|
main:-
write_sierpinski_carpet('sierpinski_carpet.svg', 486, 4).
write_sierpinski_carpet(File, Size, Order):-
open(File, write, Stream),
format(Stream,
"<svg xmlns='http://www.w3.org/2000/svg' width='~d' height='~d'>\n",
[Size, Size]),
write(Stream, "<rect width='100%' height='100%' fill='white'/>\n"),
Side is Size/3.0,
sierpinski_carpet(Stream, 0, 0, Side, Order),
write(Stream, "</svg>\n"),
close(Stream).
sierpinski_carpet(Stream, X, Y, Side, 0):-
!,
X0 is X + Side,
Y0 is Y + Side,
write_square(Stream, X0, Y0, Side).
sierpinski_carpet(Stream, X, Y, Side, Order):-
Order1 is Order - 1,
Side1 is Side / 3.0,
X0 is X + Side,
Y0 is Y + Side,
X1 is X0 + Side,
Y1 is Y0 + Side,
write_square(Stream, X0, Y0, Side),
sierpinski_carpet(Stream, X, Y, Side1, Order1),
sierpinski_carpet(Stream, X0, Y, Side1, Order1),
sierpinski_carpet(Stream, X1, Y, Side1, Order1),
sierpinski_carpet(Stream, X, Y0, Side1, Order1),
sierpinski_carpet(Stream, X1, Y0, Side1, Order1),
sierpinski_carpet(Stream, X, Y1, Side1, Order1),
sierpinski_carpet(Stream, X0, Y1, Side1, Order1),
sierpinski_carpet(Stream, X1, Y1, Side1, Order1).
write_square(Stream, X, Y, Side):-
format(Stream,
"<rect fill='black' x='~g' y='~g' width='~g' height='~g'/>\n",
[X, Y, Side, Side]).
|
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
|
#F.23
|
F#
|
open System
let seen = new System.Collections.Generic.Dictionary<string,bool>()
let lines = System.IO.File.ReadLines("unixdict.txt")
let sems = seq {
for word in lines do
let drow = new String(Array.rev(word.ToCharArray()))
if fst(seen.TryGetValue(drow)) then yield (drow, word)
seen.[drow] <- true
seen.[word] <- true
}
let s = Seq.toList sems
printfn "%d" s.Length
for i in 0 .. 4 do printfn "%A" s.[i]
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Stata
|
Stata
|
function a(x) {
printf(" a")
return(x)
}
function b(x) {
printf(" b")
return(x)
}
function call(i, j) {
printf("and:")
x = a(i)
if (x) {
x = b(j)
}
printf("\nor:")
y = a(i)
if (!y) {
y = b(j)
}
printf("\n")
return((x,y))
}
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Swift
|
Swift
|
func a(v: Bool) -> Bool {
print("a")
return v
}
func b(v: Bool) -> Bool {
print("b")
return v
}
func test(i: Bool, j: Bool) {
println("Testing a(\(i)) && b(\(j))")
print("Trace: ")
println("\nResult: \(a(i) && b(j))")
println("Testing a(\(i)) || b(\(j))")
print("Trace: ")
println("\nResult: \(a(i) || b(j))")
println()
}
test(false, false)
test(false, true)
test(true, false)
test(true, true)
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#PowerShell
|
PowerShell
|
[hashtable]$mailMessage = @{
From = "[email protected]"
To = "[email protected]"
Cc = "[email protected]"
Attachment = "C:\temp\Waggghhhh!_plan.txt"
Subject = "Waggghhhh!"
Body = "Wagggghhhhhh!"
SMTPServer = "smtp.gmail.com"
SMTPPort = "587"
UseSsl = $true
ErrorAction = "SilentlyContinue"
}
Send-MailMessage @mailMessage
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#PureBasic
|
PureBasic
|
InitNetwork()
CreateMail(0, "[email protected]", "This is the Subject")
SetMailBody(0, "Hello " + Chr(10) + "This is a mail !")
AddMailRecipient(0, "[email protected]", #PB_Mail_To)
AddMailRecipient(0, "[email protected]", #PB_Mail_Cc)
If SendMail(0, "smtp.mail.com")
MessageRequester("Information", "Mail correctly sent !")
Else
MessageRequester("Error", "Can't sent the mail !")
EndIf
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#Frink
|
Frink
|
isSemiprime[n] :=
{
factors = factor[n]
sum = 0
for [num, power] = factors
sum = sum + power
return sum == 2
}
|
http://rosettacode.org/wiki/Semiprime
|
Semiprime
|
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecibo message).
Task
Write a function determining whether a given number is semiprime.
See also
The Wikipedia article: semiprime.
The Wikipedia article: almost prime.
The OEIS sequence: A001358: semiprimes which has a shorter definition: the product of two primes.
|
#Go
|
Go
|
package main
import "fmt"
func semiprime(n int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == 2 {
return false
}
nf++
n /= i
}
}
return nf == 2
}
func main() {
for v := 1675; v <= 1680; v++ {
fmt.Println(v, "->", semiprime(v))
}
}
|
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
|
#BBC_BASIC
|
BBC BASIC
|
PRINT FNsedol("710889")
PRINT FNsedol("B0YBKJ")
PRINT FNsedol("406566")
PRINT FNsedol("B0YBLH")
PRINT FNsedol("228276")
PRINT FNsedol("B0YBKL")
PRINT FNsedol("557910")
PRINT FNsedol("B0YBKR")
PRINT FNsedol("585284")
PRINT FNsedol("B0YBKT")
PRINT FNsedol("B00030")
END
DEF FNsedol(d$)
LOCAL a%, i%, s%, weights%()
DIM weights%(6) : weights%() = 0, 1, 3, 1, 7, 3, 9
FOR i% = 1 TO 6
a% = ASCMID$(d$,i%) - &30
s% += (a% + 7 * (a% > 9)) * weights%(i%)
NEXT
= d$ + CHR$(&30 + (10 - s% MOD 10) MOD 10)
|
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
|
#C
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int sedol_weights[] = {1, 3, 1, 7, 3, 9};
const char *reject = "AEIOUaeiou";
int sedol_checksum(const char *sedol6)
{
int len = strlen(sedol6);
int sum = 0, i;
if ( len == 7 ) {
fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6);
return sedol6[6] & 0x7f;
}
if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) {
fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6);
return -1;
}
for(i=0; i < 6; i++) {
if ( isdigit(sedol6[i]) ) {
sum += (sedol6[i]-'0')*sedol_weights[i];
} else if ( isalpha(sedol6[i]) ) {
sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i];
} else {
fprintf(stderr, "SEDOL with not alphanumeric digit\n");
return -1;
}
}
return (10 - (sum%10))%10 + '0';
}
#define MAXLINELEN 10
int main()
{
char line[MAXLINELEN];
int sr, len;
while( fgets(line, MAXLINELEN, stdin) != NULL ) {
len = strlen(line);
if ( line[len-1] == '\n' ) line[len-1]='\0';
sr = sedol_checksum(line);
if ( sr > 0 )
printf("%s%c\n", line, sr);
}
return 0;
}
|
http://rosettacode.org/wiki/Self-describing_numbers
|
Self-describing numbers
|
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
position 0 has value 2 and there are two 0s in the number;
position 1 has value 0 and there are no 1s in the number;
position 2 has value 2 and there are two 2s;
position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Task Description
Write a function/routine/method/... that will check whether a given positive integer is self-describing.
As an optional stretch goal - generate and display the set of self-describing numbers.
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-referential sequence
Spelling of ordinal numbers
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure count (test_item, str)
result := 0
every item := !str do
if test_item == item then result +:= 1
return result
end
procedure is_self_describing (n)
ns := string (n) # convert to a string
every i := 1 to *ns do {
if count (string(i-1), ns) ~= ns[i] then fail
}
return 1 # success
end
# generator for creating self_describing_numbers
procedure self_describing_numbers ()
n := 1
repeat {
if is_self_describing(n) then suspend n
n +:= 1
}
end
procedure main ()
# write the first 4 self-describing numbers
every write (self_describing_numbers ()\4)
end
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Python
|
Python
|
class DigitSumer :
def __init__(self):
sumdigit = lambda n : sum( map( int,str( n )))
self.t = [sumdigit( i ) for i in xrange( 10000 )]
def __call__ ( self,n ):
r = 0
while n >= 10000 :
n,q = divmod( n,10000 )
r += self.t[q]
return r + self.t[n]
def self_numbers ():
d = DigitSumer()
s = set([])
i = 1
while 1 :
n = i + d( i )
if i in s :
s.discard( i )
else:
yield i
s.add( n )
i += 1
import time
p = 100
t = time.time()
for i,s in enumerate( self_numbers(),1 ):
if i <= 50 :
print s,
if i == 50 : print
if i == p :
print '%7.1f sec %9dth = %d'%( time.time()-t,i,s )
p *= 10
|
http://rosettacode.org/wiki/Self_numbers
|
Self numbers
|
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
See also
OEIS: A003052 - Self numbers or Colombian numbers
Wikipedia: Self numbers
|
#Raku
|
Raku
|
# 20201127 Raku programming solution
my ( $st, $count, $i, $pow, $digits, $offset, $lastSelf, $done, @selfs) =
now, 0, 1, 10, 1, 9, 0, False;
# while ( $count < 1e8 ) {
until $done {
my $isSelf = True;
my $sum = (my $start = max ($i-$offset), 0).comb.sum;
loop ( my $j = $start; $j < $i; $j+=1 ) {
if $j+$sum == $i { $isSelf = False and last }
($j+1)%10 != 0 ?? ( $sum+=1 ) !! ( $sum = ($j+1).comb.sum ) ;
}
if $isSelf {
$count+=1;
$lastSelf = $i;
if $count ≤ 50 {
@selfs.append: $i;
if $count == 50 {
say "The first 50 self numbers are:\n", @selfs;
$done = True;
}
}
}
$i+=1;
if $i % $pow == 0 {
$pow *= 10;
$digits+=1 ;
$offset = $digits * 9
}
}
# say "The 100 millionth self number is ", $lastSelf;
# say "Took ", now - $st, " seconds."
|
http://rosettacode.org/wiki/Set_of_real_numbers
|
Set of real numbers
|
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | a < x and x < b }
[a, b): {x | a ≤ x and x < b }
(a, b]: {x | a < x and x ≤ b }
Note that if a = b, of the four only [a, a] would be non-empty.
Task
Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
Provide methods for these common set operations (x is a real number; A and B are sets):
x ∈ A: determine if x is an element of A
example: 1 is in [1, 2), while 2, 3, ... are not.
A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B}
example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B}
example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B}
example: [0, 2) − (1, 3) = [0, 1]
Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
(0, 1] ∪ [0, 2)
[0, 2) ∩ (1, 2]
[0, 3) − (0, 1)
[0, 3) − [0, 1]
Implementation notes
'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
Optional work
Create a function to determine if a given set is empty (contains no element).
Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that
|sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
|
#Ruby
|
Ruby
|
class Rset
Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do
def include?(x)
(inc_lo ? lo<=x : lo<x) and (inc_hi ? x<=hi : x<hi)
end
def length
hi - lo
end
def to_s
"#{inc_lo ? '[' : '('}#{lo},#{hi}#{inc_hi ? ']' : ')'}"
end
end
def initialize(lo=nil, hi=nil, inc_lo=false, inc_hi=false)
if lo.nil? and hi.nil?
@sets = [] # empty set
else
raise TypeError unless lo.is_a?(Numeric) and hi.is_a?(Numeric)
raise ArgumentError unless valid?(lo, hi, inc_lo, inc_hi)
@sets = [Set[lo, hi, !!inc_lo, !!inc_hi]] # !! -> Boolean values
end
end
def self.[](lo, hi, inc_hi=true)
self.new(lo, hi, true, inc_hi)
end
def self.parse(str)
raise ArgumentError unless str =~ /(\[|\()(.+),(.+)(\]|\))/
b0, lo, hi, b1 = $~.captures # $~ : Regexp.last_match
lo = Rational(lo)
lo = lo.numerator if lo.denominator == 1
hi = Rational(hi)
hi = hi.numerator if hi.denominator == 1
self.new(lo, hi, b0=='[', b1==']')
end
def initialize_copy(obj)
super
@sets = @sets.map(&:dup)
end
def include?(x)
@sets.any?{|set| set.include?(x)}
end
def empty?
@sets.empty?
end
def union(other)
sets = (@sets+other.sets).map(&:dup).sort_by{|set| [set.lo, set.hi]}
work = []
pre = sets.shift
sets.each do |post|
if valid?(pre.hi, post.lo, !pre.inc_hi, !post.inc_lo)
work << pre
pre = post
else
pre.inc_lo |= post.inc_lo if pre.lo == post.lo
if pre.hi < post.hi
pre.hi = post.hi
pre.inc_hi = post.inc_hi
elsif pre.hi == post.hi
pre.inc_hi |= post.inc_hi
end
end
end
work << pre if pre
new_Rset(work)
end
alias | union
def intersection(other)
sets = @sets.map(&:dup)
work = []
other.sets.each do |oset|
sets.each do |set|
if set.hi < oset.lo or oset.hi < set.lo
# ignore
elsif oset.lo < set.lo and set.hi < oset.hi
work << set
else
lo = [set.lo, oset.lo].max
if set.lo == oset.lo
inc_lo = set.inc_lo && oset.inc_lo
else
inc_lo = (set.lo < oset.lo) ? oset.inc_lo : set.inc_lo
end
hi = [set.hi, oset.hi].min
if set.hi == oset.hi
inc_hi = set.inc_hi && oset.inc_hi
else
inc_hi = (set.hi < oset.hi) ? set.inc_hi : oset.inc_hi
end
work << Set[lo, hi, inc_lo, inc_hi] if valid?(lo, hi, inc_lo, inc_hi)
end
end
end
new_Rset(work)
end
alias & intersection
def difference(other)
sets = @sets.map(&:dup)
other.sets.each do |oset|
work = []
sets.each do |set|
if set.hi < oset.lo or oset.hi < set.lo
work << set
elsif oset.lo < set.lo and set.hi < oset.hi
# delete
else
if set.lo < oset.lo
inc_hi = (set.hi==oset.lo and !set.inc_hi) ? false : !oset.inc_lo
work << Set[set.lo, oset.lo, set.inc_lo, inc_hi]
elsif valid?(set.lo, oset.lo, set.inc_lo, !oset.inc_lo)
work << Set[set.lo, set.lo, true, true]
end
if oset.hi < set.hi
inc_lo = (oset.hi==set.lo and !set.inc_lo) ? false : !oset.inc_hi
work << Set[oset.hi, set.hi, inc_lo, set.inc_hi]
elsif valid?(oset.hi, set.hi, !oset.inc_hi, set.inc_hi)
work << Set[set.hi, set.hi, true, true]
end
end
end
sets = work
end
new_Rset(sets)
end
alias - difference
# symmetric difference
def ^(other)
(self - other) | (other - self)
end
def ==(other)
self.class == other.class and @sets == other.sets
end
def length
@sets.inject(0){|len, set| len + set.length}
end
def to_s
"#{self.class}#{@sets.join}"
end
alias inspect to_s
protected
attr_accessor :sets
private
def new_Rset(sets)
rset = self.class.new # empty set
rset.sets = sets
rset
end
def valid?(lo, hi, inc_lo, inc_hi)
lo < hi or (lo==hi and inc_lo and inc_hi)
end
end
def Rset(lo, hi, inc_hi=false)
Rset.new(lo, hi, false, inc_hi)
end
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#Go
|
Go
|
package main
import "fmt"
func NumsFromBy(from int, by int, ch chan<- int) {
for i := from; ; i+=by {
ch <- i
}
}
func Filter(in <-chan int, out chan<- int, prime int) {
for {
i := <-in
if i%prime != 0 { // here is the trial division
out <- i
}
}
}
func Sieve(out chan<- int) {
out <- 3
q := 9
ps := make(chan int)
go Sieve(ps) // separate primes supply
p := <-ps
nums := make(chan int)
go NumsFromBy(5,2,nums) // end of setup
for i := 0; ; i++ {
n := <-nums
if n < q {
out <- n // n is prime
} else {
ch1 := make(chan int) // n == q == p*p
go Filter(nums, ch1, p) // creation of a filter by p, at p*p
nums = ch1
p = <-ps // next prime
q = p*p // and its square
}
}
}
func primes (c chan<- int) {
c <- 2
go Sieve(c)
}
func main() {
ch := make(chan int)
go primes(ch)
fmt.Print("First twenty:")
for i := 0; i < 20; i++ {
fmt.Print(" ", <-ch)
}
fmt.Println()
}
|
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.
|
#Elixir
|
Elixir
|
f = fn n -> n + trunc(0.5 + :math.sqrt(n)) end
IO.inspect for n <- 1..22, do: f.(n)
n = 1_000_000
non_squares = for i <- 1..n, do: f.(i)
m = :math.sqrt(f.(n)) |> Float.ceil |> trunc
squares = for i <- 1..m, do: i*i
case Enum.find_value(squares, fn i -> i in non_squares end) do
nil -> IO.puts "No squares found below #{n}"
val -> IO.puts "Error: number is a square: #{val}"
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.
|
#Erlang
|
Erlang
|
% Implemented by Arjun Sunel
-module(non_squares).
-export([main/0]).
main() ->
lists:foreach(fun(X) -> io:format("~p~n",[non_square(X)] ) end, lists:seq(1,22)), % First 22 non-squares.
lists:foreach(fun(X) -> io:format("~p~n",[non_square(X)] ) end, lists:seq(1,1000000)). % First 1 million non-squares.
non_square(N) ->
N+trunc(1/2+ math:sqrt(N)).
|
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
|
#Delphi
|
Delphi
|
program Set_task;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Generics.Collection;
begin
var s1 := TSet<Integer>.Create([1, 2, 3, 4, 5, 6]);
var s2 := TSet<Integer>.Create([2, 5, 6, 3, 4, 8]);
var s3 := TSet<Integer>.Create([1, 2, 5]);
Writeln('S1 ', s1.ToString);
Writeln('S2 ', s2.ToString);
Writeln('S3 ', s3.ToString, #10);
Writeln('4 is in S1? ', s1.Has(4));
Writeln('S1 union S2 ', (s1 + S2).ToString);
Writeln('S1 intersection S2 ', (s1 * S2).ToString);
Writeln('S1 difference S2 ', (s1 - S2).ToString);
Writeln('S3 is subset S2 ', s1.IsSubSet(s3));
Writeln('S1 equality S2? ', s1 = s2);
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
|
#BASIC
|
BASIC
|
DIM n AS Integer, k AS Integer, limit AS Integer
INPUT "Enter number to search to: "; limit
DIM flags(limit) AS Integer
FOR n = 2 TO SQR(limit)
IF flags(n) = 0 THEN
FOR k = n*n TO limit STEP n
flags(k) = 1
NEXT k
END IF
NEXT n
' Display the primes
FOR n = 2 TO limit
IF flags(n) = 0 THEN PRINT n; ", ";
NEXT n
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Sidef
|
Sidef
|
func consolidate() { [] }
func consolidate(this, *those) {
gather {
consolidate(those...).each { |that|
if (this & that) { this |= that }
else { take that }
}
take this;
}
}
enum |A="A", B, C, D, _E, F, G, H, I, _J, K|;
func format(ss) {
ss.map{ '(' + .join(' ') + ')' }.join(' ')
}
[
[[A,B], [C,D]],
[[A,B], [B,D]],
[[A,B], [C,D], [D,B]],
[[H,I,K], [A,B], [C,D], [D,B], [F,G,H]]
].each { |ss|
say (format(ss), "\n\t==> ", format(consolidate(ss...)));
}
|
http://rosettacode.org/wiki/Show_ASCII_table
|
Show ASCII table
|
Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
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
|
#QB64
|
QB64
|
DIM s AS STRING
FOR i% = 32 TO 47
FOR j% = i% TO i% + 80 STEP 16
SELECT CASE j%
CASE 32
s$ = "Spc"
CASE 127
s$ = "Del"
CASE ELSE
s$ = CHR$(j%)
END SELECT
PRINT USING "###: \ \"; j%; s$;
NEXT j%
PRINT
NEXT i%
|
http://rosettacode.org/wiki/Sierpinski_triangle
|
Sierpinski triangle
|
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
|
#Swift
|
Swift
|
import Foundation
// Easy get/set of charAt
extension String {
subscript(index:Int) -> String {
get {
var array = Array(self)
var charAtIndex = array[index]
return String(charAtIndex)
}
set(newValue) {
var asChar = Character(newValue)
var array = Array(self)
array[index] = asChar
self = String(array)
}
}
}
func triangle(var n:Int) {
n = 1 << n
var line = ""
var t = ""
var u = ""
for (var i = 0; i <= 2 * n; i++) {
line += " "
}
line[n] = "*"
for (var i = 0; i < n; i++) {
println(line)
u = "*"
for (var j = n - i; j < n + i + 1; j++) {
t = line[j-1] == line[j + 1] ? " " : "*"
line[j - 1] = u
u = t
}
line[n + i] = t
line[n + i + 1] = "*"
}
}
|
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
|
#PureBasic
|
PureBasic
|
Procedure in_carpet(x,y)
While x>0 And y>0
If x%3=1 And y%3=1
ProcedureReturn #False
EndIf
y/3: x/3
Wend
ProcedureReturn #True
EndProcedure
Procedure carpet(n)
Define i, j, l=Pow(3,n)-1
For i=0 To l
For j=0 To l
If in_carpet(i,j)
Print("#")
Else
Print(" ")
EndIf
Next
PrintN("")
Next
EndProcedure
|
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
|
#Factor
|
Factor
|
USING: assocs combinators.short-circuit formatting
io.encodings.utf8 io.files kernel literals locals make
prettyprint random sequences ;
IN: rosetta-code.semordnilap
CONSTANT: words $[ "unixdict.txt" utf8 file-lines ]
: semordnilap? ( str1 str2 -- ? )
{ [ = not ] [ nip words member? ] } 2&& ;
[
[let
V{ } clone :> seen words
[
dup reverse 2dup
{ [ semordnilap? ] [ drop seen member? not ] } 2&&
[ 2dup [ seen push ] bi@ ,, ] [ 2drop ] if
] each
]
] H{ } make >alist
[ length "%d semordnilap pairs.\n" printf ] [ 5 sample . ] bi
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.