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.
|
#Bc
|
Bc
|
#! /usr/bin/bc
scale = 20
define ceil(x) {
auto intx
intx=int(x)
if (intx<x) intx+=1
return intx
}
define floor(x) {
return -ceil(-x)
}
define int(x) {
auto old_scale, ret
old_scale=scale
scale=0
ret=x/1
scale=old_scale
return ret
}
define round(x) {
if (x<0) x-=.5 else x+=.5
return int(x)
}
define nonsqr(n) {
return n + round(sqrt(n))
}
for(i=1; i < 23; i++) {
print nonsqr(i), "\n"
}
for(i=1; i < 1000000; i++) {
j = sqrt(nonsqr(i))
if ( j == floor(j) ) {
print i, " square in the seq\n"
}
}
quit
|
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
|
#BBC_BASIC
|
BBC BASIC
|
DIM list$(6)
list$() = "apple", "banana", "cherry", "date", "elderberry", "fig", "grape"
setA% = %1010101
PRINT "Set A: " FNlistset(list$(), setA%)
setB% = %0111110
PRINT "Set B: " FNlistset(list$(), setB%)
elementM% = %0000010
PRINT "Element M: " FNlistset(list$(), elementM%) '
IF elementM% AND setA% THEN
PRINT "M is an element of set A"
ELSE
PRINT "M is not an element of set A"
ENDIF
IF elementM% AND setB% THEN
PRINT "M is an element of set B"
ELSE
PRINT "M is not an element of set B"
ENDIF
PRINT '"The union of A and B is " FNlistset(list$(), setA% OR setB%)
PRINT "The intersection of A and B is " FNlistset(list$(), setA% AND setB%)
PRINT "The difference of A and B is " FNlistset(list$(), setA% AND NOT setB%)
IF (setA% AND setB%) = setA% THEN
PRINT '"Set A is a subset of set B"
ELSE
PRINT '"Set A is not a subset of set B"
ENDIF
IF setA% = setB% THEN
PRINT "Set A is equal to set B"
ELSE
PRINT "Set A is not equal to set B"
ENDIF
END
DEF FNlistset(list$(), set%)
LOCAL i%, o$
FOR i% = 0 TO 31
IF set% AND 1 << i% o$ += list$(i%) + ", "
NEXT
= LEFT$(LEFT$(o$))
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Python
|
Python
|
class Example(object):
def foo(self, x):
return 42 + x
name = "foo"
getattr(Example(), name)(5) # => 47
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Qi
|
Qi
|
(define foo -> 5)
(define execute-function
Name -> (eval [(INTERN Name)]))
(execute-function "foo")
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Racket
|
Racket
|
#lang racket
(define greeter
(new (class object% (super-new)
(define/public (hello name)
(displayln (~a "Hello " name "."))))))
; normal method call
(send greeter hello "World")
; sending an unknown method
(define unknown 'hello)
(dynamic-send greeter unknown "World")
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Raku
|
Raku
|
my $object = 42 but role { method add-me($x) { self + $x } }
my $name = 'add-me';
say $object."$name"(5); # 47
|
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
|
#ALGOL_68
|
ALGOL 68
|
BOOL prime = TRUE, non prime = FALSE;
PROC eratosthenes = (INT n)[]BOOL:
(
[n]BOOL sieve;
FOR i TO UPB sieve DO sieve[i] := prime OD;
INT m = ENTIER sqrt(n);
sieve[1] := non prime;
FOR i FROM 2 TO m DO
IF sieve[i] = prime THEN
FOR j FROM i*i BY i TO n DO
sieve[j] := non prime
OD
FI
OD;
sieve
);
print((eratosthenes(80),new line))
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Raku
|
Raku
|
constant @primes = |grep *.is-prime, 2..*;
constant @primorials = [\*] 1, @primes;
my @pp_indexes := |@primorials.pairs.map: {
.key if ( .value + any(1, -1) ).is-prime
};
say ~ @pp_indexes[ 0 ^.. 20 ]; # Skipping bogus first element.
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Ring
|
Ring
|
# Project : Sequence of primorial primes
max = 9999
primes = []
for n = 1 to max
if isprime(n) = 1
add(primes, n)
ok
next
for n = 1 to len(primes)
sum = 1
for m = 1 to n
sum = sum * primes[m]
next
if (isprime(sum+1) or isprime(sum-1)) = 1
see "" + n + " "
ok
next
func isprime(num)
if (num <= 1) return 0 ok
if (num % 2 = 0) and num != 2 return 0 ok
for i = 3 to floor(num / 2) -1 step 2
if (num % i = 0) return 0 ok
next
return 1
|
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
|
#OCaml
|
OCaml
|
let join a b =
List.fold_left (fun acc v ->
if List.mem v acc then acc else v::acc
) b a
let share a b = List.exists (fun x -> List.mem x b) a
let extract p lst =
let rec aux acc = function
| x::xs -> if p x then Some (x, List.rev_append acc xs) else aux (x::acc) xs
| [] -> None
in
aux [] lst
let consolidate sets =
let rec aux acc = function
| [] -> List.rev acc
| x::xs ->
match extract (share x) xs with
| Some (y, ys) -> aux acc ((join x y) :: ys)
| None -> aux (x::acc) xs
in
aux [] sets
let print_sets sets =
print_string "{ ";
List.iter (fun set ->
print_string "{";
print_string (String.concat " " set);
print_string "} "
) sets;
print_endline "}"
let () =
print_sets (consolidate [["A";"B"]; ["C";"D"]]);
print_sets (consolidate [["A";"B"]; ["B";"C"]]);
print_sets (consolidate [["A";"B"]; ["C";"D"]; ["D";"B"]]);
print_sets (consolidate [["H";"I";"K"]; ["A";"B"]; ["C";"D"]; ["D";"B"];
["F";"G";"H"]]);
;;
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Raku
|
Raku
|
sub div-count (\x) {
return 2 if x.is-prime;
+flat (1 .. x.sqrt.floor).map: -> \d {
unless x % d { my \y = x div d; y == d ?? y !! (y, d) }
}
}
my $limit = 15;
put "First $limit terms of OEIS:A005179";
put (1..$limit).map: -> $n { first { $n == .&div-count }, 1..Inf };
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#REXX
|
REXX
|
/*REXX program finds and displays the smallest number with exactly N divisors.*/
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/
say '──divisors── ──smallest number with N divisors──' /*display title for the numbers.*/
@.= /*the @ array is used for memoization*/
do i=1 for N; z= 1 + (i\==1) /*step through a number of divisors. */
do j=z by z /*now, search for a number that ≡ #divs*/
if @.j==. then iterate /*has this number already been found? */
d= #divs(j); if d\==i then iterate /*get # divisors; Is not equal? Skip.*/
say center(i, 12) right(j, 19) /*display the #divs and the smallest #.*/
@.j= . /*mark as having found #divs for this J*/
leave /*found a number, so now get the next I*/
end /*j*/
end /*i*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
#divs: procedure; parse arg x 1 y /*X and Y: both set from 1st argument.*/
if x<7 then do; if x<3 then return x /*handle special cases for one and two.*/
if x<5 then return x-1 /* " " " " three & four*/
if x==5 then return 2 /* " " " " five. */
if x==6 then return 4 /* " " " " six. */
end
odd= x // 2 /*check if X is odd or not. */
if odd then #= 1 /*Odd? Assume Pdivisors count of 1.*/
else do; #= 3; y= x%2; end /*Even? " " " " 3.*/
/* [↑] start with known num of Pdivs.*/
do k=3 for x%2-3 by 1+odd while k<y /*for odd numbers, skip evens.*/
if x//k==0 then do /*if no remainder, then found a divisor*/
#=#+2; y=x%k /*bump # Pdivs, calculate limit Y. */
if k>=y then do; #= #-1; leave; end /*limit?*/
end /* ___ */
else if k*k>x then leave /*only divide up to √ x */
end /*k*/ /* [↑] this form of DO loop is faster.*/
return #+1 /*bump "proper divisors" to "divisors".*/
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Ring
|
Ring
|
# Project: SHA-256
load "stdlib.ring"
str = "Rosetta code"
see "String: " + str + nl
see "SHA-256: "
see sha256(str) + nl
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Ruby
|
Ruby
|
require 'digest/sha2'
puts Digest::SHA256.hexdigest('Rosetta code')
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#XPL0
|
XPL0
|
func Divs(N); \Count divisors of N
int N, D, C;
[C:= 0;
if N > 1 then
[D:= 1;
repeat if rem(N/D) = 0 then C:= C+1;
D:= D+1;
until D >= N;
];
return C;
];
int An, N;
[An:= 1; N:= 0;
loop [if Divs(An) = N then
[IntOut(0, An); ChOut(0, ^ );
N:= N+1;
if N >= 15 then quit;
];
An:= An+1;
];
]
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#zkl
|
zkl
|
fcn countDivisors(n)
{ [1..(n).toFloat().sqrt()] .reduce('wrap(s,i){ s + (if(0==n%i) 1 + (i!=n/i)) },0) }
|
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.
|
#Ring
|
Ring
|
# Project : SHA-1
load "stdlib.ring"
str = "Rosetta Code"
see "String: " + str + nl
see "SHA-1: "
see sha1(str) + nl
|
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.
|
#Ruby
|
Ruby
|
require 'digest'
puts Digest::SHA1.hexdigest('Rosetta Code')
|
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
|
#MiniScript
|
MiniScript
|
// Prints ASCII table
// Note changing the values of startChar and endChar will print
// a flexible table in that range
startChar = 32
endChar = 127
characters = []
for i in range(startChar, endChar)
addString = char(i) + " "
if i == 32 then addString = "SPC"
if i == 127 then addString = "DEL"
characters.push addString
end for
for i in characters.indexes
iNum = i + startChar
iChar = " " + str(iNum)
characters[i] = iChar[-5:] + " : " + characters[i]
end for
columns = 6
line = ""
col = 0
for out in characters
col = col + 1
line = line + out
if col == columns then
print line
line = ""
col = 0
end if
end for
if line then print line // final check for odd incomplete line output
|
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
|
#Racket
|
Racket
|
#lang racket
(define (sierpinski n)
(if (zero? n)
'("*")
(let ([spaces (make-string (expt 2 (sub1 n)) #\space)]
[prev (sierpinski (sub1 n))])
(append (map (λ(x) (~a spaces x spaces)) prev)
(map (λ(x) (~a x " " x)) prev)))))
(for-each displayln (sierpinski 5))
|
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
|
#Pascal
|
Pascal
|
program SierpinskiCarpet;
uses
Math;
function In_carpet(a, b: longint): boolean;
var
x, y: longint;
begin
x := a;
y := b;
while true do
begin
if (x = 0) or (y = 0) then
begin
In_carpet := true;
break;
end
else if ((x mod 3) = 1) and ((y mod 3) = 1) then
begin
In_carpet := false;
break;
end;
x := x div 3;
y := y div 3;
end;
end;
procedure Carpet(n: integer);
var
i, j, limit: longint;
begin
{$IFDEF FPC}
limit := 3 * * n - 1;
{$ELSE}
limit := Trunc(IntPower(3, n) - 1);
{$ENDIF}
for i := 0 to limit do
begin
for j := 0 to limit do
if In_carpet(i, j) then
write('*')
else
write(' ');
writeln;
end;
end;
begin
Carpet(3);
{$IFNDEF UNIX} readln; {$ENDIF}
end.
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Bracmat
|
Bracmat
|
( get'("unixdict.txt",STR):?dict
& new$hash:?H
& 0:?p
& ( @( !dict
: ?
( [!p ?w \n [?p ?
& (H..insert)$(!w.rev$!w)
& ~
)
)
| 0:?N
& (H..forall)
$ (
=
. !arg:(?a.?b)
& !a:<!b
& (H..find)$!b
& !N+1:?N:<6
& out$(!a !b)
|
)
& out$(semordnilap !N dnuoF)
)
);
|
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
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <alloca.h> /* stdlib.h might not have obliged. */
#include <string.h>
static void reverse(char *s, int len)
{
int i, j;
char tmp;
for (i = 0, j = len - 1; i < len / 2; ++i, --j)
tmp = s[i], s[i] = s[j], s[j] = tmp;
}
/* Wrap strcmp() for qsort(). */
static int strsort(const void *s1, const void *s2)
{
return strcmp(*(char *const *) s1, *(char *const *) s2);
}
int main(void)
{
int i, c, ct = 0, len, sem = 0;
char **words, **drows, tmp[24];
FILE *dict = fopen("unixdict.txt", "r");
/* Determine word count. */
while ((c = fgetc(dict)) != EOF)
ct += c == '\n';
rewind(dict);
/* Using alloca() is generally discouraged, but we're not doing
* anything too fancy and the memory gains are significant. */
words = alloca(ct * sizeof words);
drows = alloca(ct * sizeof drows);
for (i = 0; fscanf(dict, "%s%n", tmp, &len) != EOF; ++i) {
/* Use just enough memory to store the next word. */
strcpy(words[i] = alloca(len), tmp);
/* Store it again, then reverse it. */
strcpy(drows[i] = alloca(len), tmp);
reverse(drows[i], len - 1);
}
fclose(dict);
qsort(drows, ct, sizeof drows, strsort);
/* Walk both sorted lists, checking only the words which could
* possibly be a semordnilap pair for the current reversed word. */
for (c = i = 0; i < ct; ++i) {
while (strcmp(drows[i], words[c]) > 0 && c < ct - 1)
c++;
/* We found a semordnilap. */
if (!strcmp(drows[i], words[c])) {
strcpy(tmp, drows[i]);
reverse(tmp, strlen(tmp));
/* Unless it was a palindrome. */
if (strcmp(drows[i], tmp) > 0 && sem++ < 5)
printf("%s\t%s\n", drows[i], tmp);
}
}
printf("Semordnilap pairs: %d\n", sem);
return 0;
}
|
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.
|
#Python
|
Python
|
>>> def a(answer):
print(" # Called function a(%r) -> %r" % (answer, answer))
return answer
>>> def b(answer):
print(" # Called function b(%r) -> %r" % (answer, answer))
return answer
>>> for i in (False, True):
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j)")
x = a(i) and b(j)
print ("Calculating: y = a(i) or b(j)")
y = a(i) or b(j)
Calculating: x = a(i) and b(j)
# Called function a(False) -> False
Calculating: y = a(i) or b(j)
# Called function a(False) -> False
# Called function b(False) -> False
Calculating: x = a(i) and b(j)
# Called function a(False) -> False
Calculating: y = a(i) or b(j)
# Called function a(False) -> False
# Called function b(True) -> True
Calculating: x = a(i) and b(j)
# Called function a(True) -> True
# Called function b(False) -> False
Calculating: y = a(i) or b(j)
# Called function a(True) -> True
Calculating: x = a(i) and b(j)
# Called function a(True) -> True
# Called function b(True) -> True
Calculating: y = a(i) or b(j)
# Called function a(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)
|
#Haskell
|
Haskell
|
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Network.Mail.SMTP
( Address(..)
, htmlPart
, plainTextPart
, sendMailWithLogin'
, simpleMail
)
main :: IO ()
main =
sendMailWithLogin' "smtp.example.com" 25 "user" "password" $
simpleMail
(Address (Just "From Example") "[email protected]")
[Address (Just "To Example") "[email protected]"]
[] -- CC
[] -- BCC
"Subject"
[ plainTextPart "This is plain text."
, htmlPart "<h1>Title</h1><p>This is HTML.</p>"
]
|
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)
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main(args)
mail := open("mailto:"||args[1], "m", "Subject : "||args[2],
"X-Note: automatically send by Unicon") |
stop("Cannot send mail to ",args[1])
every write(mail , !&input)
close (mail)
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.
|
#C.23
|
C#
|
static void Main(string[] args)
{
//test some numbers
for (int i = 0; i < 50; i++)
{
Console.WriteLine("{0}\t{1} ", i,isSemiPrime(i));
}
Console.ReadLine();
}
//returns true or false depending if input was considered semiprime
private static bool isSemiPrime(int c)
{
int a = 2, b = 0;
while (b < 3 && c != 1)
{
if ((c % a) == 0)
{
c /= a;
b++;
}
else
{
a++;
};
}
return b == 2;
}
|
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
|
#Action.21
|
Action!
|
INT FUNC SedolChecksum(CHAR ARRAY sedol)
BYTE ARRAY weights=[1 3 1 7 3 9]
INT i,sum
CHAR c
IF sedol(0)#6 THEN
RETURN (-1)
FI
sum=0
FOR i=1 TO sedol(0)
DO
c=sedol(i)
IF c>='0 AND c<='9 THEN
sum==+(c-'0)*weights(i-1)
ELSE
IF c>='a AND c<='z THEN
c==-'a-'A
FI
IF c='A OR c='E OR c='I OR c='O OR c='U THEN
RETURN (-1)
ELSEIF c>='A AND c<='Z THEN
sum==+(c-'A+10)*weights(i-1)
ELSE
RETURN (-1)
FI
FI
OD
sum=(10-(sum MOD 10)) MOD 10
RETURN (sum)
PROC Test(CHAR ARRAY sedol)
INT res
res=SedolChecksum(sedol)
Print(sedol) Print(" -> ")
IF res>=0 THEN
Print(sedol) PrintIE(res)
ELSE
PrintE("invalid input")
FI
RETURN
PROC Main()
Test("710889")
Test("B0YBKJ")
Test("406566")
Test("B0YBLH")
Test("228276")
Test("B0YBKL")
Test("557910")
Test("B0YBKR")
Test("585284")
Test("B0YBKT")
Test("B00030")
Test("12345A")
Test("12345")
Test("1234567")
RETURN
|
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
|
#AWK
|
AWK
|
# syntax: GAWK -f SELF-DESCRIBING_NUMBERS.AWK
BEGIN {
for (n=1; n<=100000000; n++) {
if (is_self_describing(n)) {
print(n)
}
}
exit(0)
}
function is_self_describing(n, i) {
for (i=1; i<=length(n); i++) {
if (substr(n,i,1) != gsub(i-1,"&",n)) {
return(0)
}
}
return(1)
}
|
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
|
#BASIC
|
BASIC
|
DIM x, r, b, c, n, m AS INTEGER
DIM a, d AS STRING
DIM v(10), w(10) AS INTEGER
CLS
FOR x = 1 TO 5000000
a$ = LTRIM$(STR$(x))
b = LEN(a$)
FOR c = 1 TO b
d$ = MID$(a$, c, 1)
v(VAL(d$)) = v(VAL(d$)) + 1
w(c - 1) = VAL(d$)
NEXT c
r = 0
FOR n = 0 TO 10
IF v(n) = w(n) THEN r = r + 1
v(n) = 0
w(n) = 0
NEXT n
IF r = 11 THEN PRINT x; " Yes,is autodescriptive number"
NEXT x
PRINT
PRINT "End"
SLEEP
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
|
#C.23
|
C#
|
using System;
using static System.Console;
class Program {
const int mc = 103 * 1000 * 10000 + 11 * 9 + 1;
static bool[] sv = new bool[mc + 1];
static void sieve() { int[] dS = new int[10000];
for (int a = 9, i = 9999; a >= 0; a--)
for (int b = 9; b >= 0; b--)
for (int c = 9, s = a + b; c >= 0; c--)
for (int d = 9, t = s + c; d >= 0; d--)
dS[i--] = t + d;
for (int a = 0, n = 0; a < 103; a++)
for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000)
for (int c = 0, s = d + dS[b] + n; c < 10000; c++)
sv[dS[c] + s++] = true; }
static void Main() { DateTime st = DateTime.Now; sieve();
WriteLine("Sieving took {0}s", (DateTime.Now - st).TotalSeconds);
WriteLine("\nThe first 50 self numbers are:");
for (int i = 0, count = 0; count <= 50; i++) if (!sv[i]) {
count++; if (count <= 50) Write("{0} ", i);
else WriteLine("\n\n Index Self number"); }
for (int i = 0, limit = 1, count = 0; i < mc; i++)
if (!sv[i]) if (++count == limit) {
WriteLine("{0,12:n0} {1,13:n0}", count, i);
if (limit == 1e9) break; limit *= 10; }
WriteLine("\nOverall took {0}s", (DateTime.Now - st). TotalSeconds);
}
}
|
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.
|
#JavaScript
|
JavaScript
|
function realSet(set1, set2, op, values) {
const makeSet=(set0)=>{
let res = []
if(set0.rangeType===0){
for(let i=set0.low;i<=set0.high;i++)
res.push(i);
} else if (set0.rangeType===1) {
for(let i=set0.low+1;i<set0.high;i++)
res.push(i);
} else if(set0.rangeType===2){
for(let i=set0.low+1;i<=set0.high;i++)
res.push(i);
} else {
for(let i=set0.low;i<set0.high;i++)
res.push(i);
}
return res;
}
let res = [],finalSet=[];
set1 = makeSet(set1);
set2 = makeSet(set2);
if(op==="union")
finalSet = [...new Set([...set1,...set2])];
else if(op==="intersect") {
for(let i=0;i<set1.length;i++)
if(set1.indexOf(set2[i])!==-1)
finalSet.push(set2[i]);
} else {
for(let i=0;i<set2.length;i++)
if(set1.indexOf(set2[i])===-1)
finalSet.push(set2[i]);
for(let i=0;i<set1.length;i++)
if(set2.indexOf(set1[i])===-1)
finalSet.push(set1[i]);
}
for(let i=0;i<values.length;i++){
if(finalSet.indexOf(values[i])!==-1)
res.push(true);
else
res.push(false);
}
return res;
}
|
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
|
#Clojure
|
Clojure
|
(ns test-p.core
(:require [clojure.math.numeric-tower :as math]))
(defn prime? [a]
" Uses trial division to determine if number is prime "
(or (= a 2)
(and (> a 2)
(> (mod a 2) 0)
(not (some #(= 0 (mod a %))
(range 3 (inc (int (Math/ceil (math/sqrt a)))) 2))))))
; 3 to sqrt(a) stepping by 2
(defn primes-below [n]
" Finds primes below number n "
(for [a (range 2 (inc n))
:when (prime? a)]
a))
(println (primes-below 100))
|
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.
|
#Burlesque
|
Burlesque
|
1 22r@{?s0.5?+av?+}[m
|
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
|
#BQN
|
BQN
|
Union ← ⍷∾
Inter ← ∊/⊣
Diff ← ¬∘∊/⊣
Subset ← ∧´∊
Eq ← ≡○∧
CreateSet ← ⍷
•Show 2‿4‿6‿8 Union 2‿3‿5‿7
•Show 2‿4‿6‿8 Inter 2‿3‿5‿7
•Show 2‿4‿6‿8 Diff 2‿3‿5‿7
•Show 2‿4‿6‿8 Subset 2‿3‿5‿7
•Show 2‿4‿6‿8 Eq 2‿3‿5‿7
•Show CreateSet 2‿2‿3‿5‿7‿2
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Ruby
|
Ruby
|
class Example
def foo
42
end
def bar(arg1, arg2, &block)
block.call arg1, arg2
end
end
symbol = :foo
Example.new.send symbol # => 42
Example.new.send( :bar, 1, 2 ) { |x,y| x+y } # => 3
args = [1, 2]
Example.new.send( "bar", *args ) { |x,y| x+y } # => 3
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Scala
|
Scala
|
class Example {
def foo(x: Int): Int = 42 + x
}
object Main extends App {
val example = new Example
val meth = example.getClass.getMethod("foo", classOf[Int])
assert(meth.invoke(example, 5.asInstanceOf[AnyRef]) == 47.asInstanceOf[AnyRef], "Not confirm expectation.")
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Sidef
|
Sidef
|
class Example {
method foo(x) {
42 + x
}
}
var name = 'foo'
var obj = Example()
say obj.(name)(5) # prints: 47
say obj.method(name)(5) # =//=
|
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
|
#ALGOL_W
|
ALGOL W
|
begin
% implements the sieve of Eratosthenes %
% s(i) is set to true if i is prime, false otherwise %
% algol W doesn't have a upb operator, so we pass the size of the %
% array in n %
procedure sieve( logical array s ( * ); integer value n ) ;
begin
% start with everything flagged as prime %
for i := 1 until n do s( i ) := true;
% sieve out the non-primes %
s( 1 ) := false;
for i := 2 until truncate( sqrt( n ) )
do begin
if s( i )
then begin
for p := i * i step i until n do s( p ) := false
end if_s_i
end for_i ;
end sieve ;
% test the sieve procedure %
integer sieveMax;
sieveMax := 100;
begin
logical array s ( 1 :: sieveMax );
i_w := 2; % set output field width %
s_w := 1; % and output separator width %
% find and display the primes %
sieve( s, sieveMax );
for i := 1 until sieveMax do if s( i ) then writeon( i );
end
end.
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Ruby
|
Ruby
|
# Sequence of primorial primes
require 'prime' # for creating prime_array
require 'openssl' # for using fast Miller–Rabin primality test (just need 10.14 seconds to complete)
i, urutan, primorial_number = 1, 1, OpenSSL::BN.new(1)
start = Time.now
prime_array = Prime.first (500)
until urutan > 20
primorial_number *= prime_array[i-1]
if (primorial_number - 1).prime_fasttest? || (primorial_number + 1).prime_fasttest?
puts "#{Time.now - start} \tPrimorial prime #{urutan}: #{i}"
urutan += 1
end
i += 1
end
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Sidef
|
Sidef
|
func primorial_primes(n) {
var k = 1
var p = 2
var P = 2
var seq = []
for (var i = 0; i < n; ++k) {
if (is_prime(P-1) || is_prime(P+1)) {
seq << k
++i
}
p.next_prime!
P *= p
}
return seq
}
say primorial_primes(20)
|
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
|
#ooRexx
|
ooRexx
|
/* REXX ***************************************************************
* 04.08.2013 Walter Pachl using ooRexx features
* (maybe not in the best way -improvements welcome!)
* but trying to demonstrate the algorithm
**********************************************************************/
s.1=.array~of(.set~of('A','B'),.set~of('C','D'))
s.2=.array~of(.set~of('A','B'),.set~of('B','D'))
s.3=.array~of(.set~of('A','B'),.set~of('C','D'),.set~of('D','B'))
s.4=.array~of(.set~of('H','I','K'),.set~of('A','B'),.set~of('C','D'),,
.set~of('B','D'),.set~of('F','G','H'))
s.5=.array~of(.set~of('snow','ice','slush','frost','fog'),,
.set~of('iceburgs','icecubes'),,
.set~of('rain','fog','sleet'))
s.6=.array~of('one')
s.7=.array~new
s.8=.array~of('')
Do si=1 To 8 /* loop through the test data */
na=s.si /* an array of sets */
head='Output(s):'
Say left('Input' si,10) list_as(na) /* show the input */
Do While na~items()>0 /* while the array ain't empty*/
na=cons(na) /* consolidate and get back */
/* array of remaining sets */
head=' '
End
Say '====' /* separator line */
End
Exit
cons: Procedure Expose head
/**********************************************************************
* consolidate the sets in the given array
**********************************************************************/
Use Arg a
w=a /* work on a copy */
n=w~items() /* number of sets in the array*/
Select
When n=0 Then /* no set in array */
Return .array~new /* retuns an empty array */
When n=1 Then Do /* one set in array */
Say head list(w[1]) /* show its contents */
Return .array~new /* retuns an empty array */
End
Otherwise Do /* at least two sets are there*/
b=.array~new /* use for remaining sets */
r=w[n] /* start with last set */
try=1
Do until changed=0 /* loop until result is stable*/
changed=0
new=0
n=w~items() /* number of sets */
Do i=1 To n-try /* loop first through n-1 sets*/
try=0 /* then through all of them */
is=r~intersection(w[i])
If is~items>0 Then Do /* any elements in common */
r=r~union(w[i]) /* result is the union */
Changed=1 /* and result is now larger */
End
Else Do /* no elemen in common */
new=new+1 /* add the set to the array */
b[new]=w[i] /* of remaining sets */
End
End
If b~items()=0 Then Do /* no remaining sets */
w=.array~new
Leave /* we are done */
End
w=b /* repeat with remaining sets */
b=.array~new /* prepare for next iteration */
End
End
Say head list(r) /* show one consolidated set */
End
Return w /* return array of remaining */
list: Procedure
/**********************************************************************
* list elements of given set
**********************************************************************/
Call trace ?O
Use Arg set
arr=set~makeArray
arr~sort()
ol='('
Do i=1 To arr~items()
If i=1 Then
ol=ol||arr[i]
Else
ol=ol||','arr[i]
End
Return ol')'
list_as: Procedure
/**********************************************************************
* List an array of sets
**********************************************************************/
Call trace ?O
Use Arg a
n=a~items()
If n=0 Then
ol='no element in array'
Else Do
ol=''
Do i=1 To n
ol=ol '('
arr=a[i]~makeArray
Do j=1 To arr~items()
If j=1 Then
ol=ol||arr[j]
Else
ol=ol','arr[j]
End
ol=ol') '
End
End
Return strip(ol)
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Ring
|
Ring
|
load "stdlib.ring"
see "working..." + nl
see "the first 15 terms of the sequence are:" + nl
for n = 1 to 15
for m = 1 to 4100
pnum = 0
for p = 1 to 4100
if (m % p = 0)
pnum = pnum + 1
ok
next
if pnum = n
see "" + m + " "
exit
ok
next
next
see nl + "done..." + nl
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Ruby
|
Ruby
|
require 'prime'
def num_divisors(n)
n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) }
end
def first_with_num_divs(n)
(1..).detect{|i| num_divisors(i) == n }
end
p (1..15).map{|n| first_with_num_divs(n) }
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Rust
|
Rust
|
use sha2::{Digest, Sha256};
fn hex_string(input: &[u8]) -> String {
input.as_ref().iter().map(|b| format!("{:x}", b)).collect()
}
fn main() {
// create a Sha256 object
let mut hasher = Sha256::new();
// write input message
hasher.update(b"Rosetta code");
// read hash digest and consume hasher
let result = hasher.finalize();
let hex = hex_string(&result);
assert_eq!(
hex,
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
);
println!("{}", hex);
}
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Scala
|
Scala
|
object RosettaSHA256 extends App {
def MD5(s: String): String = {
// Besides "MD5", "SHA-256", and other hashes are available
val m = java.security.MessageDigest.getInstance("SHA-256").digest(s.getBytes("UTF-8"))
m.map("%02x".format(_)).mkString
}
assert(MD5("Rosetta code") == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")
println("Successfully completed without errors.")
}
|
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.
|
#Rust
|
Rust
|
use sha1::Sha1;
fn main() {
let mut hash_msg = Sha1::new();
hash_msg.update(b"Rosetta Code");
println!("{}", hash_msg.digest().to_string());
}
|
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.
|
#S-lang
|
S-lang
|
require("chksum");
print(sha1sum("Rosetta Code"));
|
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
|
#Nanoquery
|
Nanoquery
|
k = ""
for i in range(0, 15)
for j in range(32 + i, 127, 16)
if j = 32
k = "Spc"
else if j = 127
k = "Del"
else
k = chr(j)
end
print format("%3d : %-3s ", j, k)
end
println
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
|
#Nim
|
Nim
|
import strformat
for i in 0..15:
for j in countup(32 + i, 127, step = 16):
let k = case j
of 32: "Spc"
of 127: "Del"
else: $chr(j)
write(stdout, fmt"{j:3d} : {k:<6s}")
write(stdout, "\n")
|
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
|
#Raku
|
Raku
|
sub sierpinski ($n) {
my @down = '*';
my $space = ' ';
for ^$n {
@down = |("$space$_$space" for @down), |("$_ $_" for @down);
$space x= 2;
}
return @down;
}
.say for sierpinski 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
|
#Perl
|
Perl
|
my @c = '##';
@c = (map($_ x 3, @c), map($_.(' ' x length).$_, @c), map($_ x 3, @c))
for 1 .. 3;
print join("\n", @c), "\n";
|
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
|
#C.23
|
C#
|
using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.IO;
public class Semordnilap
{
public static void Main() {
var results = FindSemordnilaps("http://www.puzzlers.org/pub/wordlists/unixdict.txt").ToList();
Console.WriteLine(results.Count);
var random = new Random();
Console.WriteLine("5 random results:");
foreach (string s in results.OrderBy(_ => random.Next()).Distinct().Take(5)) Console.WriteLine(s + " " + Reversed(s));
}
private static IEnumerable<string> FindSemordnilaps(string url) {
var found = new HashSet<string>();
foreach (string line in GetLines(url)) {
string reversed = Reversed(line);
//Not taking advantage of the fact the input file is sorted
if (line.CompareTo(reversed) != 0) {
if (found.Remove(reversed)) yield return reversed;
else found.Add(line);
}
}
}
private static IEnumerable<string> GetLines(string url) {
WebRequest request = WebRequest.Create(url);
using (var reader = new StreamReader(request.GetResponse().GetResponseStream(), true)) {
while (!reader.EndOfStream) {
yield return reader.ReadLine();
}
}
}
private static string Reversed(string value) => new string(value.Reverse().ToArray());
}
|
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.
|
#R
|
R
|
a <- function(x) {cat("a called\n"); x}
b <- function(x) {cat("b called\n"); x}
tests <- expand.grid(op=list(quote(`||`), quote(`&&`)), x=c(1,0), y=c(1,0))
invisible(apply(tests, 1, function(row) {
call <- substitute(op(a(x),b(y)), row)
cat(deparse(call), "->", eval(call), "\n\n")
}))
|
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.
|
#Racket
|
Racket
|
#lang racket
(define (a x)
(display (~a "a:" x " "))
x)
(define (b x)
(display (~a "b:" x " "))
x)
(for* ([x '(#t #f)]
[y '(#t #f)])
(displayln `(and (a ,x) (b ,y)))
(and (a x) (b y))
(newline)
(displayln `(or (a ,x) (b ,y)))
(or (a x) (b y))
(newline))
|
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)
|
#Java
|
Java
|
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* Mail
*/
public class Mail
{
/**
* Session
*/
protected Session session;
/**
* Mail constructor.
*
* @param host Host
*/
public Mail(String host)
{
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
session = Session.getDefaultInstance(properties);
}
/**
* Send email message.
*
* @param from From
* @param tos Recipients
* @param ccs CC Recipients
* @param subject Subject
* @param text Text
* @throws MessagingException
*/
public void send(String from, String tos[], String ccs[], String subject,
String text)
throws MessagingException
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
for (String to : tos)
message.addRecipient(RecipientType.TO, new InternetAddress(to));
for (String cc : ccs)
message.addRecipient(RecipientType.TO, new InternetAddress(cc));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
}
}
|
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.
|
#C.2B.2B
|
C++
|
#include <iostream>
bool isSemiPrime( int c )
{
int a = 2, b = 0;
while( b < 3 && c != 1 )
{
if( !( c % a ) )
{ c /= a; b++; }
else a++;
}
return b == 2;
}
int main( int argc, char* argv[] )
{
for( int x = 2; x < 100; x++ )
if( isSemiPrime( x ) )
std::cout << x << " ";
return 0;
}
|
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
|
#ActionScript
|
ActionScript
|
//Return the code corresponding to a given character.
//ActionScript does not have a character type, so 1-digit strings
//are used instead
function toSEDOLCode(char:String):uint {
//Make sure only a single character was sent.
if(char.length != 1)
throw new Error("toSEDOL expected string length of 1, got " + char.length);
//Character is uppercase
if (char >= "A" && char <= "Z") {
return SEDOL.charCodeAt() + 10 - "A".charCodeAt();
}
//Character is numeric
else if (char >= "0" && char <= "9"){
return uint(char);
}
//Error: character is neither numeric nor uppercase
else{
throw new Error("toSEDOLCode expected numeric or uppercase character, recieved " + char);
}
}
//Calculate the weighted sum for the SEDOL.
function toSum(str:String):uint {
if(str.length != 6)
throw new Error("toSum expected length 6, recieved " + str.length);
var sum:uint=0;
for (var i:uint = 0; i < str.length; i++)
sum+=toSEDOLCode(str.charAt(i))*[1,3,1,7,3,9][i];
return sum;
}
//Calculate the check digit from the weighted sum.
function toCheck(num:int):uint
{
return (10 -(num % 10)) % 10;
}
//Print the SEDOL with the check digit added.
function printWithCheck(SEDOL:String):void
{
trace(SEDOL + toCheck(toSum(SEDOL)));
}
printWithCheck("710889");
printWithCheck("B0YBKJ");
printWithCheck("406566");
printWithCheck("B0YBLH");
printWithCheck("228276");
printWithCheck("B0YBKL");
printWithCheck("557910");
printWithCheck("B0YBKR");
printWithCheck("585284");
printWithCheck("B0YBKT");
printWithCheck("B00030");
|
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
|
#BBC_BASIC
|
BBC BASIC
|
FOR N = 1 TO 5E7
IF FNselfdescribing(N) PRINT N
NEXT
END
DEF FNselfdescribing(N%)
LOCAL D%(), I%, L%, O%
DIM D%(9)
O% = N%
L% = LOG(N%)
WHILE N%
I% = N% MOD 10
D%(I%) += 10^(L%-I%)
N% DIV=10
ENDWHILE
= O% = SUM(D%())
|
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
|
#Befunge
|
Befunge
|
>1+9:0>\#06#:p#-:#1_$v
?v6:%+55:\+1\<<<\0:::<
#>g1+\6p55+/:#^_001p\v
^_@#!`<<v\+g6g10*+55\<
>:*:*:*^>>:01g1+:01p`|
^_\#\:#+.#5\#5,#$:<-$<
|
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
|
#Elixir
|
Elixir
|
defmodule SelfNums do
def digAndSum(number) when is_number(number) do
Integer.digits(number) |>
Enum.reduce( 0, fn(num, acc) -> num + acc end ) |>
(fn(x) -> x + number end).()
end
def selfFilter(list, firstNth) do
numRange = Enum.to_list 1..firstNth
numRange -- list
end
end
defmodule SelfTest do
import SelfNums
stop = 1000
Enum.to_list 1..stop |>
Enum.map(&digAndSum/1) |>
SelfNums.selfFilter(stop) |>
Enum.take(50) |>
IO.inspect
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
|
#F.23
|
F#
|
// Self numbers. Nigel Galloway: October 6th., 2020
let fN g=let rec fG n g=match n/10 with 0->n+g |i->fG i (g+(n%10)) in fG g g
let Self=let rec Self n i g=seq{let g=g@([n..i]|>List.map fN) in yield! List.except g [n..i]; yield! Self (n+100) (i+100) (List.filter(fun n->n>i) g)} in Self 0 99 []
Self |> Seq.take 50 |> Seq.iter(printf "%d "); printfn ""
printfn "\n%d" (Seq.item 99999999 Self)
|
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.
|
#Julia
|
Julia
|
"""
struct ConvexRealSet
Convex real set (similar to a line segment).
Parameters: lower bound, upper bound: floating point numbers
includelower, includeupper: boolean true or false to indicate whether
the set has a closed boundary (set to true) or open (set to false).
"""
mutable struct ConvexRealSet
lower::Float64
includelower::Bool
upper::Float64
includeupper::Bool
function ConvexRealSet(lo, up, incllo, inclup)
this = new()
this.upper = Float64(up)
this.lower = Float64(lo)
this.includelower = incllo
this.includeupper = inclup
this
end
end
function ∈(s, xelem)
x = Float64(xelem)
if(x == s.lower)
if(s.includelower)
return true
else
return false
end
elseif(x == s.upper)
if(s.includeupper)
return true
else
return false
end
end
s.lower < x && x < s.upper
end
⋃(aset, bset, x) = (∈(aset, x) || ∈(bset, x))
⋂(aset, bset, x) = (∈(aset, x) && ∈(bset, x))
-(aset, bset, x) = (∈(aset, x) && !∈(bset, x))
isempty(s::ConvexRealSet) = (s.lower > s.upper) ||
((s.lower == s.upper) && !s.includeupper && !s.includelower)
const s1 = ConvexRealSet(0.0, 1.0, false, true)
const s2 = ConvexRealSet(0.0, 2.0, true, false)
const s3 = ConvexRealSet(1.0, 2.0, false, true)
const s4 = ConvexRealSet(0.0, 3.0, true, false)
const s5 = ConvexRealSet(0.0, 1.0, false, false)
const s6 = ConvexRealSet(0.0, 1.0, true, true)
const sempty = ConvexRealSet(0.0, -1.0, true, true)
const testlist = [0, 1, 2]
function testconvexrealset()
for i in testlist
println("Testing with x = $i.\nResults:")
println(" (0, 1] ∪ [0, 2): $(⋃(s1, s2, i))")
println(" [0, 2) ∩ (1, 2]: $(⋂(s2, s3, i))")
println(" [0, 3) − (0, 1): $(-(s4, s5, i))")
println(" [0, 3) − [0, 1]: $(-(s4, s6, i))\n")
end
print("The set sempty is ")
println(isempty(sempty) ? "empty." : "not empty.")
end
testconvexrealset()
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.1.4-3
typealias RealPredicate = (Double) -> Boolean
enum class RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }
class RealSet(val low: Double, val high: Double, val predicate: RealPredicate) {
constructor (start: Double, end: Double, rangeType: RangeType): this(start, end,
when (rangeType) {
RangeType.CLOSED -> fun(d: Double) = d in start..end
RangeType.BOTH_OPEN -> fun(d: Double) = start < d && d < end
RangeType.LEFT_OPEN -> fun(d: Double) = start < d && d <= end
RangeType.RIGHT_OPEN -> fun(d: Double) = start <= d && d < end
}
)
fun contains(d: Double) = predicate(d)
infix fun union(other: RealSet): RealSet {
val low2 = minOf(low, other.low)
val high2 = maxOf(high, other.high)
return RealSet(low2, high2) { predicate(it) || other.predicate(it) }
}
infix fun intersect(other: RealSet): RealSet {
val low2 = maxOf(low, other.low)
val high2 = minOf(high, other.high)
return RealSet(low2, high2) { predicate(it) && other.predicate(it) }
}
infix fun subtract(other: RealSet) = RealSet(low, high) { predicate(it) && !other.predicate(it) }
var interval = 0.00001
val length: Double get() {
if (!low.isFinite() || !high.isFinite()) return -1.0 // error value
if (high <= low) return 0.0
var p = low
var count = 0
do {
if (predicate(p)) count++
p += interval
}
while (p < high)
return count * interval
}
fun isEmpty() = if (high == low) !predicate(low) else length == 0.0
}
fun main(args: Array<String>) {
val a = RealSet(0.0, 1.0, RangeType.LEFT_OPEN)
val b = RealSet(0.0, 2.0, RangeType.RIGHT_OPEN)
val c = RealSet(1.0, 2.0, RangeType.LEFT_OPEN)
val d = RealSet(0.0, 3.0, RangeType.RIGHT_OPEN)
val e = RealSet(0.0, 1.0, RangeType.BOTH_OPEN)
val f = RealSet(0.0, 1.0, RangeType.CLOSED)
val g = RealSet(0.0, 0.0, RangeType.CLOSED)
for (i in 0..2) {
val dd = i.toDouble()
println("(0, 1] ∪ [0, 2) contains $i is ${(a union b).contains(dd)}")
println("[0, 2) ∩ (1, 2] contains $i is ${(b intersect c).contains(dd)}")
println("[0, 3) − (0, 1) contains $i is ${(d subtract e).contains(dd)}")
println("[0, 3) − [0, 1] contains $i is ${(d subtract f).contains(dd)}\n")
}
println("[0, 0] is empty is ${g.isEmpty()}\n")
val aa = RealSet(0.0, 10.0) { x -> (0.0 < x && x < 10.0) &&
Math.abs(Math.sin(Math.PI * x * x)) > 0.5 }
val bb = RealSet(0.0, 10.0) { x -> (0.0 < x && x < 10.0) &&
Math.abs(Math.sin(Math.PI * x)) > 0.5 }
val cc = aa subtract bb
println("Approx length of A - B is ${cc.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
|
#Common_Lisp
|
Common Lisp
|
(defun primes-up-to (max-number)
"Compute all primes up to MAX-NUMBER using trial division"
(loop for n from 2 upto max-number
when (notany (evenly-divides n) primes)
collect n into primes
finally (return primes)))
(defun evenly-divides (n)
"Create a function that checks whether its input divides N evenly"
(lambda (x) (integerp (/ n x))))
(print (primes-up-to 100))
|
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
|
#Crystal
|
Crystal
|
See https://rosettacode.org/wiki/Primality_by_trial_division#Crystal
|
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.
|
#C
|
C
|
#include <math.h>
#include <stdio.h>
#include <assert.h>
int nonsqr(int n) {
return n + (int)(0.5 + sqrt(n));
/* return n + (int)round(sqrt(n)); in C99 */
}
int main() {
int i;
/* first 22 values (as a list) has no squares: */
for (i = 1; i < 23; i++)
printf("%d ", nonsqr(i));
printf("\n");
/* The following check shows no squares up to one million: */
for (i = 1; i < 1000000; i++) {
double j = sqrt(nonsqr(i));
assert(j != floor(j));
}
return 0;
}
|
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
|
#C
|
C
|
#include <stdio.h>
typedef unsigned int set_t; /* probably 32 bits; change according to need */
void show_set(set_t x, const char *name)
{
int i;
printf("%s is:", name);
for (i = 0; (1U << i) <= x; i++)
if (x & (1U << i))
printf(" %d", i);
putchar('\n');
}
int main(void)
{
int i;
set_t a, b, c;
a = 0; /* empty set */
for (i = 0; i < 10; i += 3) /* add 0 3 6 9 to set a */
a |= (1U << i);
show_set(a, "a");
for (i = 0; i < 5; i++)
printf("\t%d%s in set a\n", i, (a & (1U << i)) ? "":" not");
b = a;
b |= (1U << 5); b |= (1U << 10); /* b is a plus 5, 10 */
b &= ~(1U << 0); /* sans 0 */
show_set(b, "b");
show_set(a | b, "union(a, b)");
show_set(c = a & b, "c = common(a, b)");
show_set(a & ~b, "a - b"); /* diff, not arithmetic minus */
show_set(b & ~a, "b - a");
printf("b is%s a subset of a\n", !(b & ~a) ? "" : " not");
printf("c is%s a subset of a\n", !(c & ~a) ? "" : " not");
printf("union(a, b) - common(a, b) %s union(a - b, b - a)\n",
((a | b) & ~(a & b)) == ((a & ~b) | (b & ~a))
? "equals" : "does not equal");
return 0;
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Smalltalk
|
Smalltalk
|
Object subclass: #Example.
Example extend [
foo: x [
^ 42 + x ] ].
symbol := 'foo:' asSymbol. " same as symbol := #foo: "
Example new perform: symbol with: 5. " returns 47 "
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Swift
|
Swift
|
import Foundation
class MyUglyClass: NSObject {
@objc
func myUglyFunction() {
print("called myUglyFunction")
}
}
let someObject: NSObject = MyUglyClass()
someObject.perform(NSSelectorFromString("myUglyFunction"))
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Tcl
|
Tcl
|
package require Tcl 8.6
oo::class create Example {
method foo {} {return 42}
method 1 {s} {puts "fee$s"}
method 2 {s} {puts "fie$s"}
method 3 {s} {puts "foe$s"}
method 4 {s} {puts "fum$s"}
}
set eg [Example new]
set mthd [format "%c%c%c" 102 111 111]; # A "foo" by any other means would smell as sweet
puts [$eg $mthd]
for {set i 1} {$i <= 4} {incr i} {
$eg $i ...
}
|
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
|
#ALGOL-M
|
ALGOL-M
|
BEGIN
COMMENT
FIND PRIMES UP TO THE SPECIFIED LIMIT (HERE 1,000) USING
CLASSIC SIEVE OF ERATOSTHENES;
% CALCULATE INTEGER SQUARE ROOT %
INTEGER FUNCTION ISQRT(N);
INTEGER N;
BEGIN
INTEGER R1, R2;
R1 := N;
R2 := 1;
WHILE R1 > R2 DO
BEGIN
R1 := (R1+R2) / 2;
R2 := N / R1;
END;
ISQRT := R1;
END;
INTEGER LIMIT, I, J, FALSE, TRUE, COL, COUNT;
INTEGER ARRAY FLAGS[1:1000];
LIMIT := 1000;
FALSE := 0;
TRUE := 1;
WRITE("FINDING PRIMES FROM 2 TO",LIMIT);
% INITIALIZE TABLE %
WRITE("INITIALIZING ... ");
FOR I := 1 STEP 1 UNTIL LIMIT DO
FLAGS[I] := TRUE;
% SIEVE FOR PRIMES %
WRITEON("SIEVING ... ");
FOR I := 2 STEP 1 UNTIL ISQRT(LIMIT) DO
BEGIN
IF FLAGS[I] = TRUE THEN
FOR J := (I * I) STEP I UNTIL LIMIT DO
FLAGS[J] := FALSE;
END;
% WRITE OUT THE PRIMES TEN PER LINE %
WRITEON("PRINTING");
COUNT := 0;
COL := 1;
WRITE("");
FOR I := 2 STEP 1 UNTIL LIMIT DO
BEGIN
IF FLAGS[I] = TRUE THEN
BEGIN
WRITEON(I);
COUNT := COUNT + 1;
COL := COL + 1;
IF COL > 10 THEN
BEGIN
WRITE("");
COL := 1;
END;
END;
END;
WRITE("");
WRITE(COUNT, " PRIMES WERE FOUND.");
END
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Swift
|
Swift
|
import BigInt
import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) where self % i == 0 {
return false
}
return true
}
}
let limit = 20
var primorial = 1
var count = 1
var p = 3
var prod = BigInt(2)
print(1, terminator: " ")
while true {
defer {
p += 2
}
guard p.isPrime else {
continue
}
prod *= BigInt(p)
primorial += 1
if (prod + 1).isPrime() || (prod - 1).isPrime() {
print(primorial, terminator: " ")
count += 1
fflush(stdout)
if count == limit {
break
}
}
}
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Wren
|
Wren
|
import "/big" for BigInt
import "/math" for Int
import "io" for Stdout
var primes = Int.primeSieve(4000) // more than enough for this task
System.print("The indices of the first 15 primorial numbers, p, where p + 1 or p - 1 is prime are:")
var count = 0
var prod = BigInt.two
for (i in 1...primes.count) {
if ((prod-1).isProbablePrime(5) || (prod+1).isProbablePrime(5)) {
count = count + 1
System.write("%(i) ")
Stdout.flush()
if (count == 15) break
}
prod = prod * primes[i]
}
System.print()
|
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
|
#PARI.2FGP
|
PARI/GP
|
cons(V)={
my(v,u,s);
for(i=1,#V,
v=V[i];
for(j=i+1,#V,
u=V[j];
if(#setintersect(u,v),V[i]=v=vecsort(setunion(u,v));V[j]=[];s++)
)
);
V=select(v->#v,V);
if(s,cons(V),V)
};
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Rust
|
Rust
|
use itertools::Itertools;
const PRIMES: [u64; 15] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47];
const MAX_DIVISOR: usize = 64;
struct DivisorSeq {
max_number_of_divisors: u64,
index: u64,
}
impl DivisorSeq {
fn new(max_number_of_divisors: u64) -> DivisorSeq {
DivisorSeq {
max_number_of_divisors,
index: 1,
}
}
}
impl Iterator for DivisorSeq {
type Item = u64;
fn next(&mut self) -> Option<u64> {
if self.max_number_of_divisors < self.index {
return None;
}
#[allow(unused_mut)]
let mut result: u64;
let divisors_of_divisor = get_divisors(self.index);
match divisors_of_divisor.len() {
1 | 2 => {
// when # divisors is a prime
result = 2_u64.pow(self.index as u32 - 1);
self.index += 1;
}
3 => {
// when # divisors is a prime square
result = 6_u64.pow(divisors_of_divisor[1] as u32 - 1);
self.index += 1;
}
4 => {
// when # divisors is a prime * non-prime
result = 2_u64.pow(divisors_of_divisor[2] as u32 - 1)
* 3_u64.pow(divisors_of_divisor[1] as u32 - 1);
self.index += 1;
}
8 if divisors_of_divisor
.iter()
.filter(|x| PRIMES.contains(x))
.count()
== 3 =>
{
// sphenic numbers, aka p*m*q, where, p, m and q are prime
let first_primes = divisors_of_divisor
.iter()
.filter(|x| PRIMES.contains(x))
.collect::<Vec<_>>();
result = 2_u64.pow(*first_primes[2] as u32 - 1)
* 3_u64.pow(*first_primes[1] as u32 - 1)
* 5_u64.pow(*first_primes[0] as u32 - 1);
self.index += 1;
}
_ => {
// brute force and slow: iterates over the numbers to find
// one with the appropriate number of divisors
let mut x: u64 = 1;
loop {
if get_divisors(x).len() as u64 == self.index {
break;
}
x += 1;
}
result = x;
self.index += 1;
}
}
Some(result)
}
}
/// Gets all divisors of a number
fn get_divisors(n: u64) -> Vec<u64> {
let mut results = Vec::new();
for i in 1..(n / 2 + 1) {
if n % i == 0 {
results.push(i);
}
}
results.push(n);
results
}
fn main() {
// simple version using factorizing numbers
// with rules applied from A005179 so speed up
// but as such it is slow in some cases, e.g for 52
let seq_iter = DivisorSeq::new(64);
println!("Simple method with rules");
println!("# divisors Smallest number");
for (i, x) in seq_iter.enumerate() {
println!("{:>10}{:20}", i + 1, x);
}
// more advanced version using calculations based on number of
// prime factors and their exponent
// load initial result table with an initial value of 2**n for each item
let mut min_numbers = vec![0_u64; MAX_DIVISOR];
(0_usize..MAX_DIVISOR).for_each(|n| min_numbers[n] = 2_u64.pow(n as u32));
let prime_list = (1..15).map(|i| PRIMES[0..=i].to_vec()).collect::<Vec<_>>();
for pl in prime_list.iter() {
// calculate the max exponent a prime can get in a given prime-list
// to be able to produce the desired number of divisors
let max_exponent = 1 + MAX_DIVISOR as u32 / 2_u32.pow(pl.len() as u32 - 1);
// create a combination of exponents using cartesian product
let exponents = (1_usize..=pl.len())
.map(|_| 1_u32..=max_exponent)
.multi_cartesian_product()
.filter(|elt| {
let mut prev = None::<&u32>;
elt.iter().all(|x| match prev {
Some(n) if x > n => false,
_ => {
prev = Some(x);
true
}
})
});
// iterate throught he exponent combinations
for exp in exponents {
// calculate the number of divisors using the formula
// given primes of p, q, r
// and exponents of a1, a2, a3
// the # divisors is (a1+1)* (a2+1) *(a3+1)
let num_of_divisors = exp.iter().map(|x| x + 1).product::<u32>() as usize;
// and calculate the number with those primes and the given exponent set
let num = pl.iter().zip(exp.iter()).fold(1_u64, |mut acc, (p, e)| {
// check for overflow if numbers won't fit into u64
acc = match acc.checked_mul(p.pow(*e)) {
Some(z) => z,
_ => 0,
};
acc
});
// finally, if the number is less than what we have so far in the result table
// replace the result table with the smaller number
if num > 0
&& min_numbers.len() >= num_of_divisors
&& min_numbers[num_of_divisors - 1] > num
{
min_numbers[num_of_divisors - 1] = num;
}
}
}
println!("Advanced method");
println!("# divisors Smallest number");
for (i, x) in min_numbers.iter().enumerate() {
println!("{:>10}{:20}", i + 1, x);
}
}
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Sidef
|
Sidef
|
func n_divisors(n) {
1..Inf -> first_by { .sigma0 == n }
}
say 15.of { n_divisors(_+1) }
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "msgdigest.s7i";
const proc: main is func
begin
writeln(hex(sha256("Rosetta code")));
end func;
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Sidef
|
Sidef
|
var sha = frequire('Digest::SHA');
say sha.sha256_hex('Rosetta code');
|
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.
|
#Scala
|
Scala
|
import java.nio._
case class Hash(message: List[Byte]) {
val defaultHashes = List(0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0)
val hash = {
val padded = generatePadding(message)
val chunks: List[List[Byte]] = messageToChunks(padded)
toHashForm(hashesFromChunks(chunks))
}
def generatePadding(message: List[Byte]): List[Byte] = {
val finalPadding = BigInt(message.length * 8).toByteArray match {
case x => List.fill(8 - x.length)(0.toByte) ++ x
}
val padding = (message.length + 1) % 64 match {
case l if l < 56 =>
message ::: 0x80.toByte :: List.fill(56 - l)(0.toByte)
case l =>
message ::: 0x80.toByte :: List.fill((64 - l) + 56 + 1)(0.toByte)
}
padding ::: finalPadding
}
def toBigEndian(bytes: List[Byte]) =
ByteBuffer.wrap(bytes.toArray).getInt
def messageToChunks(message: List[Byte]) =
message.grouped(64).toList
def chunkToWords(chunk: List[Byte]) =
chunk.grouped(4).map(toBigEndian).toList
def extendWords(words: List[Int]): List[Int] = words.length match {
case i if i < 80 => extendWords(words :+ Integer.rotateLeft(
(words(i - 3) ^ words(i - 8) ^ words(i - 14) ^ words(i - 16)), 1))
case _ => words
}
def generateFK(i: Int, b: Int, c: Int, d: Int) = i match {
case i if i < 20 => (b & c | ~b & d, 0x5A827999)
case i if i < 40 => (b ^ c ^ d, 0x6ED9EBA1)
case i if i < 60 => (b & c | b & d | c & d, 0x8F1BBCDC)
case i if i < 80 => (b ^ c ^ d, 0xCA62C1D6)
}
def generateHash(words: List[Int], prevHash: List[Int]): List[Int] = {
def generateHash(i: Int, currentHashes: List[Int]): List[Int] = i match {
case i if i < 80 => currentHashes match {
case a :: b :: c :: d :: e :: Nil => {
val (f, k) = generateFK(i, b, c, d)
val x = Integer.rotateLeft(a, 5) + f + e + k + words(i)
val t = Integer.rotateLeft(b, 30)
generateHash(i + 1, x :: a :: t :: c :: d :: Nil)
}
}
case _ => currentHashes
}
addHashes(prevHash, generateHash(0, prevHash))
}
def addHashes(xs: List[Int], ys: List[Int]) = (xs, ys).zipped.map(_ + _)
def hashesFromChunks(chunks: List[List[Byte]],
remainingHash: List[Int] = defaultHashes): List[Int] =
chunks match {
case Nil => remainingHash
case x :: xs => {
val words = extendWords(chunkToWords(x))
val newHash = generateHash(words, remainingHash)
hashesFromChunks(xs, newHash)
}
}
def toHashForm(hashes: List[Int]) =
hashes.map(b => ByteBuffer.allocate(4)
.order(ByteOrder.BIG_ENDIAN).putInt(b).array.toList)
.map(bytesToHex).mkString
def bytesToHex(bytes: List[Byte]) =
(for (byte <- bytes) yield (Character.forDigit((byte >> 4) & 0xF, 16) ::
Character.forDigit((byte & 0xF), 16) :: Nil).mkString).mkString
}
object Hash extends App {
def hash(message: String) = new Hash(message.getBytes.toList).hash
println(hash("Rosetta Code"))
}
|
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
|
#Objeck
|
Objeck
|
class AsciiTable {
function : Main(args : String[]) ~ Nil {
for(i := 32; i <= 127 ; i += 1;) {
if(i = 32 | i = 127) {
s := i = 32 ? "Spc" : "Del";
"{$i}:\t{$s}\t"->Print();
}
else {
c := i->ToChar();
"{$i}:\t{$c}\t"->Print();
};
if((i-1) % 6 = 0 ) {
"\n"->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
|
#REXX
|
REXX
|
/*REXX program constructs and displays a Sierpinski triangle of up to around order 10k.*/
parse arg n mark . /*get the order of Sierpinski triangle.*/
if n=='' | n=="," then n=4 /*Not specified? Then use the default.*/
if mark=='' then mark= "*" /*MARK was specified as a character. */
if length(mark)==2 then mark=x2c(mark) /* " " " in hexadecimal. */
if length(mark)==3 then mark=d2c(mark) /* " " " " decimal. */
numeric digits 12000 /*this should handle the biggy numbers.*/
/* [↓] the blood-'n-guts of the pgm. */
do j=0 for n*4; !=1; z=left('', n*4 -1-j) /*indent the line to be displayed. */
do k=0 for j+1 /*construct the line with J+1 parts. */
if !//2==0 then z=z' ' /*it's either a blank, or ··· */
else z=z mark /* ··· it's one of 'em thar characters.*/
!=! * (j-k) % (k+1) /*calculate handy-dandy thing-a-ma-jig.*/
end /*k*/ /* [↑] finished constructing a line. */
say z /*display a line of the triangle. */
end /*j*/ /* [↑] finished showing triangle. */
/*stick a fork in it, we're all done. */
|
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
|
#Phix
|
Phix
|
constant order = 4
function InCarpet(atom x, atom y)
while x!=0 and y!=0 do
if floor(mod(x,3))=1 and floor(mod(y,3))=1 then
return ' '
end if
x /= 3
y /= 3
end while
return '#'
end function
for i=0 to power(3,order)-1 do
for j=0 to power(3,order)-1 do
puts(1,InCarpet(i,j))
end for
puts(1,'\n')
end for
|
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
|
#C.2B.2B
|
C++
|
#include <fstream>
#include <iostream>
#include <set>
#include <string>
int main() {
std::ifstream input("unixdict.txt");
if (input) {
std::set<std::string> words; // previous words
std::string word; // current word
size_t count = 0; // pair count
while (input >> word) {
std::string drow(word.rbegin(), word.rend()); // reverse
if (words.find(drow) == words.end()) {
// pair not found
words.insert(word);
} else {
// pair found
if (count++ < 5)
std::cout << word << ' ' << drow << '\n';
}
}
std::cout << "\nSemordnilap pairs: " << count << '\n';
return 0;
} else
return 1; // couldn't open input file
}
|
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.
|
#Raku
|
Raku
|
use MONKEY-SEE-NO-EVAL;
sub a ($p) { print 'a'; $p }
sub b ($p) { print 'b'; $p }
for 1, 0 X 1, 0 -> ($p, $q) {
for '&&', '||' -> $op {
my $s = "a($p) $op b($q)";
print "$s: ";
EVAL $s;
print "\n";
}
}
|
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.
|
#REXX
|
REXX
|
/*REXX programs demonstrates short─circuit evaluation testing (in an IF statement).*/
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= -2 /*Not specified? Then use the default.*/
if HI=='' | HI=="," then HI= 2 /* " " " " " " */
do j=LO to HI /*process from the low to the high.*/
x=a(j) & b(j) /*compute function A and function B */
y=a(j) | b(j) /* " " " or " " */
if \y then y=b(j) /* " " B (for negation).*/
say copies('═', 30) ' x=' || x ' y='y ' j='j
say
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
a: say ' A entered with:' arg(1); return abs( arg(1) // 2) /*1=odd, 0=even */
b: say ' B entered with:' arg(1); return arg(1) < 0 /*1=neg, 0=if not*/
|
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)
|
#Julia
|
Julia
|
using SMTPClient
addbrackets(s) = replace(s, r"^\s*([^\<\>]+)\s*$", s"<\1>")
function wrapRFC5322(from, to, subject, msg)
timestr = Libc.strftime("%a, %d %b %Y %H:%M:%S %z", time())
IOBuffer("Date: $timestr\nTo: $to\nFrom: $from\nSubject: $subject\n\n$msg")
end
function sendemail(from, to, subject, messagebody, serverandport;
cc=[], user="", password="", isSSL=true, blocking=true)
opt = SendOptions(blocking=blocking, isSSL=isSSL, username=user, passwd=password)
send(serverandport, map(s -> addbrackets(s), vcat(to, cc)), addbrackets(from),
wrapRFC5322(addbrackets(from), addbrackets(to), subject, messagebody), opt)
end
sendemail("[email protected]", "[email protected]", "TEST", "hello there test message text here", "smtps://smtp.gmail.com",
user="[email protected]", password="example.com")
|
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)
|
#Kotlin
|
Kotlin
|
// version 1.1.4-3
import java.util.Properties
import javax.mail.Authenticator
import javax.mail.PasswordAuthentication
import javax.mail.Session
import javax.mail.internet.MimeMessage
import javax.mail.internet.InternetAddress
import javax.mail.Message.RecipientType
import javax.mail.Transport
fun sendEmail(user: String, tos: Array<String>, ccs: Array<String>, title: String,
body: String, password: String) {
val props = Properties()
val host = "smtp.gmail.com"
with (props) {
put("mail.smtp.host", host)
put("mail.smtp.port", "587") // for TLS
put("mail.smtp.auth", "true")
put("mail.smtp.starttls.enable", "true")
}
val auth = object: Authenticator() {
protected override fun getPasswordAuthentication() =
PasswordAuthentication(user, password)
}
val session = Session.getInstance(props, auth)
val message = MimeMessage(session)
with (message) {
setFrom(InternetAddress(user))
for (to in tos) addRecipient(RecipientType.TO, InternetAddress(to))
for (cc in ccs) addRecipient(RecipientType.TO, InternetAddress(cc))
setSubject(title)
setText(body)
}
val transport = session.getTransport("smtp")
with (transport) {
connect(host, user, password)
sendMessage(message, message.allRecipients)
close()
}
}
fun main(args: Array<String>) {
val user = "[email protected]"
val tos = arrayOf("[email protected]")
val ccs = arrayOf<String>()
val title = "Rosetta Code Example"
val body = "This is just a test email"
val password = "secret"
sendEmail(user, tos, ccs, title, body, password)
}
|
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.
|
#Clojure
|
Clojure
|
(ns example
(:gen-class))
(defn semi-prime? [n]
(loop [a 2
b 0
c n]
(cond
(> b 2) false
(<= c 1) (= b 2)
(= 0 (rem c a)) (recur a (inc b) (int (/ c a)))
:else (recur (inc a) b c))))
(println (filter semi-prime? (range 1 100)))
|
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
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_SEDOL is
subtype SEDOL_String is String (1..6);
type SEDOL_Sum is range 0..9;
function Check (SEDOL : SEDOL_String) return SEDOL_Sum is
Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9);
Sum : Integer := 0;
Item : Integer;
begin
for Index in SEDOL'Range loop
Item := Character'Pos (SEDOL (Index));
case Item is
when Character'Pos ('0')..Character'Pos ('9') =>
Item := Item - Character'Pos ('0');
when Character'Pos ('B')..Character'Pos ('D') |
Character'Pos ('F')..Character'Pos ('H') |
Character'Pos ('J')..Character'Pos ('N') |
Character'Pos ('P')..Character'Pos ('T') |
Character'Pos ('V')..Character'Pos ('Z') =>
Item := Item - Character'Pos ('A') + 10;
when others =>
raise Constraint_Error;
end case;
Sum := Sum + Item * Weight (Index);
end loop;
return SEDOL_Sum ((-Sum) mod 10);
end Check;
Test : constant array (1..10) of SEDOL_String :=
( "710889", "B0YBKJ", "406566", "B0YBLH", "228276",
"B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT"
);
begin
for Index in Test'Range loop
Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index))));
end loop;
end Test_SEDOL;
|
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
|
#C
|
C
|
#include <stdio.h>
inline int self_desc(unsigned long long xx)
{
register unsigned int d, x;
unsigned char cnt[10] = {0}, dig[10] = {0};
for (d = 0; xx > ~0U; xx /= 10)
cnt[ dig[d++] = xx % 10 ]++;
for (x = xx; x; x /= 10)
cnt[ dig[d++] = x % 10 ]++;
while(d-- && dig[x++] == cnt[d]);
return d == -1;
}
int main()
{
int i;
for (i = 1; i < 100000000; i++) /* don't handle 0 */
if (self_desc(i)) printf("%d\n", i);
return 0;
}
|
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
|
#FreeBASIC
|
FreeBASIC
|
Print "The first 50 self numbers are:"
Dim As Boolean flag
Dim As Ulong m, p, sum, number(), sum2
Dim As Ulong n = 0
Dim As Ulong num = 0
Dim As Ulong limit = 51
Dim As Ulong limit2 = 100000000
Dim As String strnum
Do
n += 1
For m = 1 To n
flag = True
sum = 0
strnum = Str(m)
For p = 1 To Len(strnum)
sum += Val(Mid(strnum,p,1))
Next p
sum2 = m + sum
If sum2 = n Then
flag = False
Exit For
Else
flag = True
End If
Next m
If flag = True Then
num += 1
If num < limit Then Print ""; num; ". "; n
If num >= limit2 Then
Print "The "; limit2; "th self number is: "; n
Exit Do
End If
End If
Loop
Sleep
|
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.
|
#Lua
|
Lua
|
function createSet(low,high,rt)
local l,h = tonumber(low), tonumber(high)
if l and h then
local t = {low=l, high=h}
if type(rt) == "string" then
if rt == "open" then
t.contains = function(d) return low< d and d< high end
elseif rt == "closed" then
t.contains = function(d) return low<=d and d<=high end
elseif rt == "left" then
t.contains = function(d) return low< d and d<=high end
elseif rt == "right" then
t.contains = function(d) return low<=d and d< high end
else
error("Unknown range type: "..rt)
end
elseif type(rt) == "function" then
t.contains = rt
else
error("Unable to find a range type or predicate")
end
t.union = function(o)
local l2 = math.min(l, o.low)
local h2 = math.min(h, o.high)
local p = function(d) return t.contains(d) or o.contains(d) end
return createSet(l2, h2, p)
end
t.intersect = function(o)
local l2 = math.min(l, o.low)
local h2 = math.min(h, o.high)
local p = function(d) return t.contains(d) and o.contains(d) end
return createSet(l2, h2, p)
end
t.subtract = function(o)
local l2 = math.min(l, o.low)
local h2 = math.min(h, o.high)
local p = function(d) return t.contains(d) and not o.contains(d) end
return createSet(l2, h2, p)
end
t.length = function()
if h <= l then return 0.0 end
local p = l
local count = 0
local interval = 0.00001
repeat
if t.contains(p) then count = count + 1 end
p = p + interval
until p>=high
return count * interval
end
t.empty = function()
if l == h then
return not t.contains(low)
end
return t.length() == 0.0
end
return t
else
error("Either '"..low.."' or '"..high.."' is not a number")
end
end
local a = createSet(0.0, 1.0, "left")
local b = createSet(0.0, 2.0, "right")
local c = createSet(1.0, 2.0, "left")
local d = createSet(0.0, 3.0, "right")
local e = createSet(0.0, 1.0, "open")
local f = createSet(0.0, 1.0, "closed")
local g = createSet(0.0, 0.0, "closed")
for i=0,2 do
print("(0, 1] union [0, 2) contains "..i.." is "..tostring(a.union(b).contains(i)))
print("[0, 2) intersect (1, 2] contains "..i.." is "..tostring(b.intersect(c).contains(i)))
print("[0, 3) - (0, 1) contains "..i.." is "..tostring(d.subtract(e).contains(i)))
print("[0, 3) - [0, 1] contains "..i.." is "..tostring(d.subtract(f).contains(i)))
print()
end
print("[0, 0] is empty is "..tostring(g.empty()))
print()
local aa = createSet(
0.0, 10.0,
function(x) return (0.0<x and x<10.0) and math.abs(math.sin(math.pi * x * x)) > 0.5 end
)
local bb = createSet(
0.0, 10.0,
function(x) return (0.0<x and x<10.0) and math.abs(math.sin(math.pi * x)) > 0.5 end
)
local cc = aa.subtract(bb)
print("Approx length of A - B is "..cc.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
|
#D
|
D
|
import std.stdio, std.range, std.algorithm, std.traits,
std.numeric, std.concurrency;
Generator!(ForeachType!R) nubBy(alias pred, R)(R items) {
return new typeof(return)({
ForeachType!R[] seen;
OUTER: foreach (x; items) {
foreach (y; seen)
if (pred(x, y))
continue OUTER;
yield(x);
seen ~= x;
}
});
}
void main() /*@safe*/ {
sequence!q{n + 2}
.nubBy!((x, y) => gcd(x, y) > 1)
.take(20)
.writeln;
}
|
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.
|
#C.23
|
C#
|
using System;
using System.Diagnostics;
namespace sons
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i < 23; i++)
Console.WriteLine(nonsqr(i));
for (int i = 1; i < 1000000; i++)
{
double j = Math.Sqrt(nonsqr(i));
Debug.Assert(j != Math.Floor(j),"Square");
}
}
static int nonsqr(int i)
{
return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));
}
}
}
|
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
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void PrintCollection(IEnumerable<int> x)
{
Console.WriteLine(string.Join(" ", x));
}
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Set creation");
var A = new HashSet<int> { 4, 12, 14, 17, 18, 19, 20 };
var B = new HashSet<int> { 2, 5, 8, 11, 12, 13, 17, 18, 20 };
PrintCollection(A);
PrintCollection(B);
Console.WriteLine("Test m ∈ S -- \"m is an element in set S\"");
Console.WriteLine("14 is an element in set A: {0}", A.Contains(14));
Console.WriteLine("15 is an element in set A: {0}", A.Contains(15));
Console.WriteLine("A ∪ B -- union; a set of all elements either in set A or in set B.");
var aUb = A.Union(B);
PrintCollection(aUb);
Console.WriteLine("A ∖ B -- difference; a set of all elements in set A, except those in set B.");
var aDb = A.Except(B);
PrintCollection(aDb);
Console.WriteLine("A ⊆ B -- subset; true if every element in set A is also in set B.");
Console.WriteLine(A.IsSubsetOf(B));
var C = new HashSet<int> { 14, 17, 18 };
Console.WriteLine(C.IsSubsetOf(A));
Console.WriteLine("A = B -- equality; true if every element of set A is in set B and vice versa.");
Console.WriteLine(A.SetEquals(B));
var D = new HashSet<int> { 4, 12, 14, 17, 18, 19, 20 };
Console.WriteLine(A.SetEquals(D));
Console.WriteLine("If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B");
Console.WriteLine(A.IsProperSubsetOf(B));
Console.WriteLine(C.IsProperSubsetOf(A));
Console.WriteLine("Modify a mutable set. (Add 10 to A; remove 12 from B).");
A.Add(10);
B.Remove(12);
PrintCollection(A);
PrintCollection(B);
Console.ReadKey();
}
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Wren
|
Wren
|
import "meta" for Meta
class Test {
construct new() {}
foo() { System.print("Foo called.") }
bar() { System.print("Bar called.") }
}
var test = Test.new()
for (method in ["foo", "bar"]) {
Meta.eval("test.%(method)()")
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#zkl
|
zkl
|
name:="len"; "this is a test".resolve(name)() //-->14
|
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
|
#APL
|
APL
|
sieve2←{
b←⍵⍴1
b[⍳2⌊⍵]←0
2≥⍵:b
p←{⍵/⍳⍴⍵}∇⌈⍵*0.5
m←1+⌊(⍵-1+p×p)÷p
b ⊣ p {b[⍺×⍺+⍳⍵]←0}¨ m
}
primes2←{⍵/⍳⍴⍵}∘sieve2
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#zkl
|
zkl
|
var [const] BN=Import("zklBigNum"); // libGMP
p,s,i,n:=BN(1),BN(1), 0,0;
do{ n+=1;
s.nextPrime(); // in place, probabilistic
p.mul(s); // in place
if((p+1).probablyPrime() or (p-1).probablyPrime()){
println("%3d %5d digits".fmt(n,p.len()));
i+=1;
}
}while(i<20);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.