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_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
|
#Prolog
|
Prolog
|
wheel235(L) :-
W = [6, 4, 2, 4, 2, 4, 6, 2 | W],
lazy_list(accumulate, 1/W, L).
accumulate(M/[A|As], N/As, N) :- N is M + A.
roll235wheel(Limit, A) :-
wheel235(W),
append(A, [N|_], W),
N > Limit, !.
prime235(N) :- % N is prime excepting multiples of 2, 3, 5.
wheel235(W),
wheel_prime(N, W).
wheel_prime(N, [D|_]) :- D*D > N, !.
wheel_prime(N, [D|Ds]) :- N mod D =\= 0, wheel_prime(N, Ds).
primes(Limit, [2, 3, 5 | Primes]) :-
roll235wheel(Limit, Candidates),
include(prime235, Candidates, Primes).
|
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.
|
#JavaScript
|
JavaScript
|
var a = [];
for (var i = 1; i < 23; i++) a[i] = i + Math.floor(1/2 + Math.sqrt(i));
console.log(a);
for (i = 1; i < 1000000; i++) if (Number.isInteger(i + Math.floor(1/2 + Math.sqrt(i))) === false) {
console.log("The ",i,"th element of the sequence is a square");
}
|
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.
|
#jq
|
jq
|
def A000037: . + (0.5 + sqrt | floor);
def is_square: sqrt | . == floor;
"For n up to and including 22:",
(range(1;23) | A000037),
"Check for squares for n up to 1e6:",
(range(1;1e6+1) | A000037 | select( is_square ))
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Groovy
|
Groovy
|
def s1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as Set
def m1 = 6
def m2 = 7
def s2 = [0, 2, 4, 6, 8] as Set
assert m1 in s1 : 'member'
assert ! (m2 in s2) : 'not a member'
def su = s1 + s2
assert su == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as Set : 'union'
def si = s1.intersect(s2)
assert si == [8, 6, 4, 2] as Set : 'intersection'
def sd = s1 - s2
assert sd == [1, 3, 5, 7, 9, 10] as Set : 'difference'
assert s1.containsAll(si) : 'subset'
assert ! s1.containsAll(s2) : 'not a subset'
assert (si + sd) == s1 : 'equality'
assert (s2 + sd) != s1 : 'inequality'
assert s1 != su && su.containsAll(s1) : 'proper subset'
s1 << 0
assert s1 == su : 'added element 0 to s1'
|
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
|
#CLU
|
CLU
|
% Sieve of Eratosthenes
eratosthenes = proc (n: int) returns (array[bool])
prime: array[bool] := array[bool]$fill(1, n, true)
prime[1] := false
for p: int in int$from_to(2, n/2) do
if prime[p] then
for c: int in int$from_to_by(p*p, n, p) do
prime[c] := false
end
end
end
return(prime)
end eratosthenes
% Print primes up to 1000 using the sieve
start_up = proc ()
po: stream := stream$primary_output()
prime: array[bool] := eratosthenes(1000)
col: int := 0
for i: int in array[bool]$indexes(prime) do
if prime[i] then
col := col + 1
stream$putright(po, int$unparse(i), 5)
if col = 10 then
col := 0
stream$putc(po, '\n')
end
end
end
end start_up
|
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
|
#Spin
|
Spin
|
con
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial"
pub main | i, j
ser.start(31, 30, 0, 115200)
repeat i from 0 to 15
repeat j from i + 32 to 127 step 16
if j < 100
ser.tx(32)
ser.dec(j)
ser.str(string(": "))
case j
32:
ser.str(string("SPC"))
127:
ser.str(string("DEL"))
other:
ser.tx(j)
ser.str(string(" "))
ser.str(string(" "))
ser.str(string(13, 10))
waitcnt(_clkfreq + cnt)
ser.stop
|
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
|
#Standard_ML
|
Standard ML
|
fun Table n 127 = " 127: 'DEL'\n"
| Table 0 x = "\n" ^ (Table 10 x)
| Table n x = (StringCvt.padLeft #" " 4 (Int.toString x)) ^ ": '" ^ (str (chr x)) ^ "' " ^ ( Table (n-1) (x+1)) ;
print (Table 10 32) ;
|
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
|
#Yabasic
|
Yabasic
|
sub rep$(n, c$)
local i, s$
for i = 1 to n
s$ = s$ + c$
next
return s$
end sub
sub sierpinski(n)
local lim, y, x
lim = 2**n - 1
for y = lim to 0 step -1
print rep$(y, " ");
for x = 0 to lim-y
if and(x, y) then print " "; else print "* "; end if
next
print
next
end sub
for i = 1 to 5
sierpinski(i)
next
|
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
|
#Scala
|
Scala
|
def nextCarpet(carpet: List[String]): List[String] = (
carpet.map(x => x + x + x) :::
carpet.map(x => x + x.replace('#', ' ') + x) :::
carpet.map(x => x + x + x))
def sierpinskiCarpets(n: Int) = (Iterator.iterate(List("#"))(nextCarpet) drop n next) foreach println
|
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
|
#Liberty_BASIC
|
Liberty BASIC
|
print "Loading dictionary."
open "unixdict.txt" for input as #1
while not(eof(#1))
line input #1, a$
dict$=dict$+" "+a$
wend
close #1
print "Dictionary loaded."
print "Seaching for semordnilaps."
semo$=" " 'string to hold words with semordnilaps
do
i=i+1
w$=word$(dict$,i)
p$=reverseString$(w$)
if w$<>p$ then
p$=" "+p$+" "
if instr(semo$,p$) = 0 then
if instr(dict$,p$) then
pairs=pairs+1
print w$+" /"+p$
semo$=semo$+w$+p$
end if
end if
end if
scan
loop until w$=""
print "Total number of unique semordnilap pairs is ";pairs
wait
Function isPalindrome(string$)
string$ = Lower$(string$)
reverseString$ = reverseString$(string$)
If string$ = reverseString$ Then isPalindrome = 1
End Function
Function reverseString$(string$)
For i = Len(string$) To 1 Step -1
reverseString$ = reverseString$ + Mid$(string$, i, 1)
Next i
End Function
|
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.
|
#PicoLisp
|
PicoLisp
|
(de factor (N)
(make
(let
(D 2
L (1 2 2 . (4 2 4 2 4 6 2 6 .))
M (sqrt N) )
(while (>= M D)
(if (=0 (% N D))
(setq M
(sqrt (setq N (/ N (link D)))) )
(inc 'D (pop 'L)) ) )
(link N) ) ) )
(println
(filter
'((X)
(let L (factor X)
(and (cdr L) (not (cddr L))) ) )
(conc (range 1 100) (range 1675 1680)) ) )
(bye)
|
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.
|
#PL.2FI
|
PL/I
|
*process source attributes xref nest or(!);
/*--------------------------------------------------------------------
* 22.02.2014 Walter Pachl using the is_prime code from
* PL/I 'prime decomposition'
* 23.02. WP start test for second prime with 2 or first prime found
*-------------------------------------------------------------------*/
spb: Proc options(main);
Dcl a(10) Bin Fixed(31)
Init(900660121,2,4,1679,1234567,32768,99,9876543,100,5040);
Dcl (x,n,nf,i,j) Bin Fixed(31) Init(0);
Dcl f(3) Bin Fixed(31);
Dcl txt Char(30) Var;
Dcl bit Bit(1);
Do i=1 To hbound(a);
bit=is_semiprime(a(i));
Select(nf);
When(0,1) txt=' is prime';
When(2) txt=' is semiprime '!!factors(a(i));
Otherwise txt=' is NOT semiprime '!!factors(a(i));
End;
Put Edit(a(i),bit,txt)(Skip,f(10),x(1),b(1),a);
End;
is_semiprime: Proc(x) Returns(bit(1));
/*--------------------------------------------------------------------
* Returns '1'b if x is semiprime, '0'b otherwise
* in addition
* it sets f(1) and f(2) to the first (or only) prime factor(s)
*-------------------------------------------------------------------*/
Dcl x Bin Fixed(31);
nf=0;
f=0;
x=a(i);
n=x;
f(1)=2;
loop:
Do While(nf<=2 & n>1);
If is_prime(n) Then Do;
Call mem(n);
Leave loop;
End;
Else Do;
loop2:
Do j=f(1) By 1 While(j*j<=n);
If is_prime(j)&mod(n,j)=0 Then Do;
Call mem(j);
n=n/j;
Leave loop2;
End;
End;
End;
End;
Return(nf=2);
End;
is_prime: Proc(n) Returns(bit(1));
Dcl n Bin Fixed(31);
Dcl i Bin Fixed(31);
If n < 2 Then Return('0'b);
If n = 2 Then Return('1'b);
If mod(n,2)=0 Then Return('0'b);
Do i = 3 by 2 While(i*i<=n);
If mod(n,i)=0 Then Return('0'b);
End;
Return('1'b);
End is_prime;
mem: Proc(x);
Dcl x Bin Fixed(31);
nf+=1;
f(nf)=x;
End;
factors: Proc(x) Returns(Char(150) Var);
Dcl x Bin Fixed(31);
Dcl (res,net) Char(150) Var Init('');
Dcl (i,f3) Bin Fixed(31);
res=f(1)!!'*'!!f(2);
f3=x/(f(1)*f(2));
If f3>1 Then
res=res!!'*'!!f3;
Do i=1 To length(res);
If substr(res,i,1)>' ' Then
net=net!!substr(res,i,1);
End;
Return(net);
End;
End spb;
|
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
|
#Forth
|
Forth
|
create weight 1 , 3 , 1 , 7 , 3 , 9 ,
: char>num ( '0-9A-Z' -- 0..35 )
dup [char] 9 > 7 and - [char] 0 - ;
: check+ ( sedol -- sedol' )
6 <> abort" wrong SEDOL length"
0 ( sum )
6 0 do
over I + c@ char>num
weight I cells + @ *
+
loop
10 mod 10 swap - 10 mod [char] 0 +
over 6 + c! 7 ;
: sedol" [char] " parse check+ type ;
sedol" 710889" 7108899 ok
sedol" B0YBKJ" B0YBKJ7 ok
sedol" 406566" 4065663 ok
sedol" B0YBLH" B0YBLH2 ok
sedol" 228276" 2282765 ok
sedol" B0YBKL" B0YBKL9 ok
sedol" 557910" 5579107 ok
sedol" B0YBKR" B0YBKR5 ok
sedol" 585284" 5852842 ok
sedol" B0YBKT" B0YBKT7 ok
|
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
|
#PHP
|
PHP
|
<?php
function is_describing($number) {
foreach (str_split((int) $number) as $place => $value) {
if (substr_count($number, $place) != $value) {
return false;
}
}
return true;
}
for ($i = 0; $i <= 50000000; $i += 10) {
if (is_describing($i)) {
echo $i . PHP_EOL;
}
}
?>
|
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
|
#PureBasic
|
PureBasic
|
EnableExplicit
#SPC=Chr(32)
#TB=~"\t"
#TBLF=~"\t\n"
Define.i a,b,l,n,count=0
Define *count.Integer=@count
Procedure.i AddCount(*c.Integer) ; *counter: by Ref
*c\i+1
ProcedureReturn *c\i
EndProcedure
Procedure.s FormatStr(tx$,l.i)
Shared *count
If AddCount(*count)%10=0
ProcedureReturn RSet(tx$,l,#SPC)+#TBLF
Else
ProcedureReturn RSet(tx$,l,#SPC)+#TB
EndIf
EndProcedure
Procedure.b Trial(n.i)
Define.i i
For i=3 To Int(Sqr(n)) Step 2
If n%i=0 : ProcedureReturn #False : EndIf
Next
ProcedureReturn #True
EndProcedure
Procedure.b isPrime(n.i)
If (n>1 And n%2<>0 And Trial(n)) Or n=2 : ProcedureReturn #True : EndIf
ProcedureReturn #False
EndProcedure
OpenConsole("Sequence of primes by Trial Division")
PrintN("Input (n1<n2 & n1>0)")
Print("n1 : ") : a=Int(Val(Input()))
Print("n2 : ") : b=Int(Val(Input()))
l=Len(Str(b))
If a<b And a>0
PrintN(~"\nPrime numbers between "+Str(a)+" and "+Str(b))
For n=a To b
If isPrime(n)
Print(FormatStr(Str(n),l))
EndIf
Next
Print(~"\nPrimes= "+Str(*count\i))
Input()
EndIf
|
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.
|
#Julia
|
Julia
|
nonsquare(n::Real) = n + floor(typeof(n), 0.5 + sqrt(n))
@show nonsquare.(1:1_000_000) ∩ collect(1:1000) .^ 2
|
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.
|
#K
|
K
|
nonsquare:{x+_.5+%x}
nonsquare[1_!23]
|
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
|
#Haskell
|
Haskell
|
Prelude> import Data.Set
Prelude Data.Set> empty :: Set Integer -- Empty set
fromList []
Prelude Data.Set> let s1 = fromList [1,2,3,4,3] -- Convert list into set
Prelude Data.Set> s1
fromList [1,2,3,4]
Prelude Data.Set> let s2 = fromList [3,4,5,6]
Prelude Data.Set> union s1 s2 -- Union
fromList [1,2,3,4,5,6]
Prelude Data.Set> intersection s1 s2 -- Intersection
fromList [3,4]
Prelude Data.Set> s1 \\ s2 -- Difference
fromList [1,2]
Prelude Data.Set> s1 `isSubsetOf` s1 -- Subset
True
Prelude Data.Set> fromList [3,1] `isSubsetOf` s1
True
Prelude Data.Set> s1 `isProperSubsetOf` s1 -- Proper subset
False
Prelude Data.Set> fromList [3,1] `isProperSubsetOf` s1
True
Prelude Data.Set> fromList [3,2,4,1] == s1 -- Equality
True
Prelude Data.Set> s1 == s2
False
Prelude Data.Set> 2 `member` s1 -- Membership
True
Prelude Data.Set> 10 `notMember` s1
True
Prelude Data.Set> size s1 -- Cardinality
4
Prelude Data.Set> insert 99 s1 -- Create a new set by inserting
fromList [1,2,3,4,99]
Prelude Data.Set> delete 3 s1 -- Create a new set by deleting
fromList [1,2,4]
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#CMake
|
CMake
|
function(eratosthenes var limit)
# Check for integer overflow. With CMake using 32-bit signed integer,
# this check fails when limit > 46340.
if(NOT limit EQUAL 0) # Avoid division by zero.
math(EXPR i "(${limit} * ${limit}) / ${limit}")
if(NOT limit EQUAL ${i})
message(FATAL_ERROR "limit is too large, would cause integer overflow")
endif()
endif()
# Use local variables prime_2, prime_3, ..., prime_${limit} as array.
# Initialize array to y => yes it is prime.
foreach(i RANGE 2 ${limit})
set(prime_${i} y)
endforeach(i)
# Gather a list of prime numbers.
set(list)
foreach(i RANGE 2 ${limit})
if(prime_${i})
# Append this prime to list.
list(APPEND list ${i})
# For each multiple of i, set n => no it is not prime.
# Optimization: start at i squared.
math(EXPR square "${i} * ${i}")
if(NOT square GREATER ${limit}) # Avoid fatal error.
foreach(m RANGE ${square} ${limit} ${i})
set(prime_${m} n)
endforeach(m)
endif()
endif(prime_${i})
endforeach(i)
set(${var} ${list} PARENT_SCOPE)
endfunction(eratosthenes)
|
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
|
#Tcl
|
Tcl
|
for {set i 0} {$i < 16} {incr i} {
for {set j $i} {$j < 128} {incr j 16} {
if {$j <= 31} {
continue ;# don't show values 0 - 31
} elseif {$j == 32} { set x "SP"
} elseif {$j == 127} { set x "DEL"
} else { set x [format %c $j] }
puts -nonewline [format "%3d: %-5s" $j $x]
}
puts ""
}
|
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
|
#zkl
|
zkl
|
level,d := 3,T("*");
foreach n in (level + 1){
sp:=" "*(2).pow(n);
d=d.apply('wrap(a){ String(sp,a,sp) }).extend(
d.apply(fcn(a){ String(a," ",a) }));
}
d.concat("\n").println();
|
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
|
#Scheme
|
Scheme
|
(define (carpet n)
(define (in-carpet? x y)
(cond ((or (zero? x) (zero? y))
#t)
((and (= 1 (remainder x 3)) (= 1 (remainder y 3)))
#f)
(else
(in-carpet? (quotient x 3) (quotient y 3)))))
(do ((i 0 (+ i 1))) ((not (< i (expt 3 n))))
(do ((j 0 (+ j 1))) ((not (< j (expt 3 n))))
(display (if (in-carpet? i j)
#\*
#\space)))
(newline)))
|
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
|
#Lua
|
Lua
|
#!/usr/bin/env lua
-- allow dictionary file and sample size to be specified on command line
local dictfile = arg[1] or "unixdict.txt"
local sample_size = arg[2] or 5;
-- read dictionary
local f = assert(io.open(dictfile, "r"))
local dict = {}
for line in f:lines() do
dict[line] = line:reverse()
end
f:close()
-- find the semordnilaps
local semordnilaps = {}
for fwd, rev in pairs(dict) do
if dict[rev] and fwd < rev then
table.insert(semordnilaps, {fwd,rev})
end
end
-- print the report
print("There are " .. #semordnilaps .. " semordnilaps in " .. dictfile .. ". Here are " .. sample_size .. ":")
math.randomseed( os.time() )
for i = 1, sample_size do
local j
repeat
j = math.random(1,#semordnilaps)
until semordnilaps[j]
local f, r = unpack(semordnilaps[j])
semordnilaps[j] = nil
print(f .. " -> " .. r)
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.
|
#PowerShell
|
PowerShell
|
function isPrime ($n) {
if ($n -le 1) {$false}
elseif (($n -eq 2) -or ($n -eq 3)) {$true}
else{
$m = [Math]::Floor([Math]::Sqrt($n))
(@(2..$m | where {($_ -lt $n) -and ($n % $_ -eq 0) }).Count -eq 0)
}
}
function semiprime ($n) {
if($n -gt 3) {
$lim = [Math]::Floor($n/2)+1
$i = 2
while(($i -lt $lim) -and ($n%$i -ne 0)){ $i += 1}
if($i -eq $lim){@()}
elseif(-not (isPrime ($n/$i))){@()}
else{@($i,($n/$i))}
} else {@()}
}
$OFS = " x "
"1679: $(semiprime 1679)"
"87: $(semiprime 87)"
"25: $(semiprime 25)"
"12: $(semiprime 12)"
"6: $(semiprime 6)"
$OFS = " "
"semiprime form 1 to 100: $(1..100 | where {semiprime $_})"
|
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
|
#Fortran
|
Fortran
|
MODULE SEDOL_CHECK
IMPLICIT NONE
CONTAINS
FUNCTION Checkdigit(c)
CHARACTER :: Checkdigit
CHARACTER(6), INTENT(IN) :: c
CHARACTER(36) :: alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
INTEGER, DIMENSION(6) :: weights = (/ 1, 3, 1, 7, 3, 9 /), temp
INTEGER :: i, n
DO i = 1, 6
temp(i) = INDEX(alpha, c(i:i)) - 1
END DO
temp = temp * weights
n = MOD(10 - (MOD(SUM(temp), 10)), 10)
Checkdigit = ACHAR(n + 48)
END FUNCTION Checkdigit
END MODULE SEDOL_CHECK
PROGRAM SEDOLTEST
USE SEDOL_CHECK
IMPLICIT NONE
CHARACTER(31) :: valid = "0123456789BCDFGHJKLMNPQRSTVWXYZ"
CHARACTER(6) :: codes(10) = (/ "710889", "B0YBKJ", "406566", "B0YBLH", "228276" , &
"B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" /)
CHARACTER(7) :: sedol
INTEGER :: i, invalid
DO i = 1, 10
invalid = VERIFY(codes(i), valid)
IF (invalid == 0) THEN
sedol = codes(i)
sedol(7:7) = Checkdigit(codes(i))
ELSE
sedol = "INVALID"
END IF
WRITE(*, "(2A9)") codes(i), sedol
END DO
END PROGRAM SEDOLTEST
|
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
|
#Picat
|
Picat
|
self_desc(Num,L) =>
L = [ I.to_integer() : I in Num.to_string()],
Len = L.len,
if sum(L) != Len then fail end,
foreach(J in L)
% cannot be a digit larger than the length of Num
if J >= Len then fail end
end,
foreach(I in 0..Len-1)
if sum([1 : J in L, I==J]) != L[I+1] then
fail
end
end.
|
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
|
#PicoLisp
|
PicoLisp
|
(de selfDescribing (N)
(fully '((D I) (= D (cnt = N (circ I))))
(setq N (mapcar format (chop N)))
(range 0 (length N)) ) )
|
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
|
#Python
|
Python
|
def prime(a):
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
def primes_below(n):
return [i for i in range(n) if prime(i)]
|
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
|
#Quackery
|
Quackery
|
[ [] swap times
[ i^ isprime if
[ i^ join ] ] ] is primes< ( n --> [ )
100 primes< echo
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.1
fun f(n: Int) = n + Math.floor(0.5 + Math.sqrt(n.toDouble())).toInt()
fun main(args: Array<String>) {
println(" n f")
val squares = mutableListOf<Int>()
for (n in 1 until 1000000) {
val v1 = f(n)
val v2 = Math.sqrt(v1.toDouble()).toInt()
if (v1 == v2 * v2) squares.add(n)
if (n < 23) println("${"%2d".format(n)} : $v1")
}
println()
if (squares.size == 0) println("There are no squares for n less than one million")
else println("Squares are generated for the following values of n: $squares")
}
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure display_set (s)
writes ("[")
every writes (!s || " ")
write ("]")
end
# fail unless s1 and s2 contain the same elements
procedure set_equals (s1, s2)
return subset(s1, s2) & subset(s2, s1)
end
# fail if every element in s2 is not contained in s1
procedure subset (s1, s2)
every (a := !s2) do {
if not(member(s1,a)) then fail
}
return s2
end
procedure main ()
a := set(1, 1, 2, 3, 4)
b := set(2, 3, 5)
writes ("a: ")
display_set (a)
writes ("b: ")
display_set (b)
# basic set operations
writes ("Intersection: ")
display_set (a ** b)
writes ("Union: ")
display_set (a ++ b)
writes ("Difference: ")
display_set (a -- b)
# membership
if member(a, 2) then
write ("2 is a member of a")
else
write ("2 is not a member of a")
if member(a, 5) then
write ("5 is a member of a")
else
write ("5 is not a member of a")
# equality
if set_equals(a, set(1,2,3,4,4)) then
write ("a equals set(1,2,3,4,4)")
else
write ("a does not equal set(1,2,3,4,4)")
if set_equals(a, b) then
write ("a equals b")
else
write ("a does not equal b")
# subset
if subset(a, set(1,2)) then
write ("(1,2) is included in a")
else
write ("(1,2) is not included in a")
if subset(a, set(1,2,5)) then
write ("(1,2,5) is included in a")
else
write ("(1,2,5) is not included in a")
end
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#COBOL
|
COBOL
|
*> Please ignore the asterisks in the first column of the next comments,
*> which are kludges to get syntax highlighting to work.
IDENTIFICATION DIVISION.
PROGRAM-ID. Sieve-Of-Eratosthenes.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Max-Number USAGE UNSIGNED-INT.
01 Max-Prime USAGE UNSIGNED-INT.
01 Num-Group.
03 Num-Table PIC X VALUE "P"
OCCURS 1 TO 10000000 TIMES DEPENDING ON Max-Number
INDEXED BY Num-Index.
88 Is-Prime VALUE "P" FALSE "N".
01 Current-Prime USAGE UNSIGNED-INT.
01 I USAGE UNSIGNED-INT.
PROCEDURE DIVISION.
DISPLAY "Enter the limit: " WITH NO ADVANCING
ACCEPT Max-Number
DIVIDE Max-Number BY 2 GIVING Max-Prime
* *> Set Is-Prime of all non-prime numbers to false.
SET Is-Prime (1) TO FALSE
PERFORM UNTIL Max-Prime < Current-Prime
* *> Set current-prime to next prime.
ADD 1 TO Current-Prime
PERFORM VARYING Num-Index FROM Current-Prime BY 1
UNTIL Is-Prime (Num-Index)
END-PERFORM
MOVE Num-Index TO Current-Prime
* *> Set Is-Prime of all multiples of current-prime to
* *> false, starting from current-prime sqaured.
COMPUTE Num-Index = Current-Prime ** 2
PERFORM UNTIL Max-Number < Num-Index
SET Is-Prime (Num-Index) TO FALSE
SET Num-Index UP BY Current-Prime
END-PERFORM
END-PERFORM
* *> Display the prime numbers.
PERFORM VARYING Num-Index FROM 1 BY 1
UNTIL Max-Number < Num-Index
IF Is-Prime (Num-Index)
DISPLAY Num-Index
END-IF
END-PERFORM
GOBACK
.
|
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
|
#VBA
|
VBA
|
Public Sub ascii()
Dim s As String, i As Integer, j As Integer
For i = 0 To 15
For j = 32 + i To 127 Step 16
Select Case j
Case 32: s = "Spc"
Case 127: s = "Del"
Case Else: s = Chr(j)
End Select
Debug.Print Tab(10 * (j - 32 - i) / 16); Spc(3 - Len(CStr(j))); j & ": " & s;
Next j
Debug.Print vbCrLf
Next i
End Sub
|
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
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const func boolean: inCarpet (in var integer: x, in var integer: y) is func
result
var boolean: result is TRUE;
begin
while result and x <> 0 and y <> 0 do
if x rem 3 = 1 and y rem 3 = 1 then
result := FALSE;
else
x := x div 3;
y := y div 3;
end if;
end while;
end func;
const proc: carpet (in integer: n) is func
local
var integer: i is 0;
var integer: j is 0;
begin
for i range 0 to pred(3 ** n) do
for j range 0 to pred(3 ** n) do
if inCarpet(i, j) then
write("#");
else
write(" ");
end if;
end for;
writeln;
end for;
end func;
const proc: main is func
begin
carpet(3);
end func;
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module semordnilaps {
Document d$
Load.Doc d$, "unixdict.txt"
Inventory MyDict, Result
Function s$(a$) {
m$=a$:k=Len(a$):for i=1 to k {insert i, 1 m$=mid$(a$, k, 1):k--} : =m$
}
L=Doc.Par(d$)
m=Paragraph(d$, 0)
If not Forward(d$,m) then exit
i=1
While m {
word$=Paragraph$(d$,(m))
Print Over $(0, 10), str$(i/L,"##0.00%"), Len(Result) : i++
If Exist(MyDict, word$) then { if Exist(Result, word$) Then exit
Append Result, word$
} Else.if len(word$)>1 Then p$=s$(word$):if p$<>word$ Then Append MyDict, p$
}
Print
Print "Semordnilap pairs: ";Len(Result)
For i=0 to len(Result)-1 step len(Result) div 5 {
p$=Eval$(Result, i)
Print s$(p$);"/";p$
}
}
semordnilaps
|
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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
data = Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"];
result = DeleteDuplicates[ Select[data, MemberQ[data, StringReverse[#]]
&& # =!= StringReverse[#] &], (# ===StringReverse[#2]) &];
Print[Length[result], Take[result, 5]]
|
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.
|
#Python
|
Python
|
from prime_decomposition import decompose
def semiprime(n):
d = decompose(n)
try:
return next(d) * next(d) == n
except StopIteration:
return False
|
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.
|
#Quackery
|
Quackery
|
[ factors size dup 3 4 clamp = ] is semiprime ( n --> b )
say "Semiprimes less than 100:" cr
100 times [ i^ semiprime if [ i^ echo sp ] ]
|
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
|
#FreeBASIC
|
FreeBASIC
|
' version 05-07-2015
' compile with: fbc -s console
Function check_sedol(input_nr As String) As Integer
input_nr = Trim(input_nr)
Dim As Integer i, j, x, nr_begin, sum
Dim As String ch, legal = "AEIOU0123456789BCDFGHJKLMNPQRSTVWXYZ"
Dim As Integer weight(0 To ...) = { 1, 3, 1, 7, 3, 9, 1}
x = Len(input_nr)
If x < 6 Or x > 7 Then
Return -99 ' to long or to short
End If
For i = 0 To 5
ch = Chr(input_nr[i])
j = InStr(legal,ch)
If j < 6 Then
Return -90+j ' not a legal char. or a vowel
End If
j = ch[0] - Asc("0")
If j > 9 Then j = j + (Asc("0") + 10- Asc("A"))
If i = 0 AndAlso j < 10 Then nr_begin = 1
If nr_begin = 1 AndAlso i > 0 Then
If j > 9 Then Return -97 ' first is number then all be numbers
End If
sum = sum + j * weight(i)
Next
sum= ((10 - (sum Mod 10)) Mod 10)
If x = 7 Then
j=input_nr[6] - Asc("0") ' checksum digit is only number
If j = sum Then
Return 100+sum ' correct
Else
Return -98 ' wrong
End If
End If
Return sum ' checksum digit
End Function
Sub sedol(in As String)
Dim As Integer checksum = check_sedol(in)
Print(in);
Select Case checksum
Case -99
Print " Illegal SEDOL: wrong length"
Case -98
Print " Illegal SEDOL: checksum digits do not match"
Case -97
Print " Illegal SEDOL: starts with number, may only contain numbers"
Case -90
Print " Illegal SEDOL: illegal character"
Case -89 To -85
Print " Illegal SEDOL: No vowels allowed"
Case Is > 99
Print " Valid SEDOL: checksums match"
Case Else
Print " checksum calculated : ";in;Str(checksum)
End Select
End Sub
' ------=< MAIN >=------
Dim As Integer k,checksum
Dim As String in(1 To ...) = {"710889", "B0YBKJ", "406566", "B0YBLH",_
"228276", "B0YBKL", "557910", "B0YBKR",_
"585284", "B0YBKT", "B00030"}
Print "Calculated checksum"
For k = 1 To UBound(in) : sedol(in(k)) : Next
Print : Print "Check checksum"
Dim As String in1(1 To ...) = {"7108899", "B0YBKJ7", "4065663", "B0YBLH2",_
"2282765", "B0YBKL9","5579107", "B0YBKR5",_
"5852842", "B0YBKT7", "B000300"}
For k = 1 To UBound(in1) : sedol(in1(k)) : Next
Print : Print "Error test"
Dim As String errors(1 To ...) = {"12", "1234567890", "1B0000", "123 45",_
"A00000", "B000301"}
For k = 1 To UBound(errors) : sedol(errors(k)) : Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
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
|
#PowerShell
|
PowerShell
|
function Test-SelfDescribing ([int]$Number)
{
[int[]]$digits = $Number.ToString().ToCharArray() | ForEach-Object {[Char]::GetNumericValue($_)}
[int]$sum = 0
for ($i = 0; $i -lt $digits.Count; $i++)
{
$sum += $i * $digits[$i]
}
$sum -eq $digits.Count
}
|
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
|
#Prolog
|
Prolog
|
:- use_module(library(clpfd)).
self_describling :-
forall(between(1, 10, I),
(findall(N, self_describling(I,N), L),
format('Len ~w, Numbers ~w~n', [I, L]))).
% search of the self_describling numbers of a given len
self_describling(Len, N) :-
length(L, Len),
Len1 is Len - 1,
L = [H|T],
% the first figure is greater than 0
H in 1..Len1,
% there is a least to figures so the number of these figures
% is at most Len - 2
Len2 is Len - 2,
T ins 0..Len2,
% the sum of the figures is equal to the len of the number
sum(L, #=, Len),
% There is at least one figure corresponding to the number of zeros
H1 #= H+1,
element(H1, L, V),
V #> 0,
% create the list
label(L),
% test the list
msort(L, LNS),
packList(LNS,LNP),
numlist(0, Len1, NumList),
verif(LNP,NumList, L),
% list is OK, create the number
maplist(atom_number, LA, L),
number_chars(N, LA).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% testing a number (not use in this program)
self_describling(N) :-
number_chars(N, L),
maplist(atom_number, L, LN),
msort(LN, LNS),
packList(LNS,LNP), !,
length(L, Len),
Len1 is Len - 1,
numlist(0, Len1, NumList),
verif(LNP,NumList, LN).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% verif(PackList, Order_of_Numeral, Numeral_of_the_nuber_to_test)
% Packlist is of the form [[Number_of_Numeral, Order_of_Numeral]|_]
% Test succeed when
% All lists are empty
verif([], [], []).
% Packlist is empty and all lasting numerals are 0
verif([], [_N|S], [0|T]) :-
verif([], S, T).
% Number of numerals N is V
verif([[V, N]|R], [N|S], [V|T]) :-
verif(R, S, T).
% Number of numerals N is 0
verif([[V, N1]|R], [N|S], [0|T]) :-
N #< N1,
verif([[V,N1]|R], S, T).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ?- packList([a,a,a,b,c,c,c,d,d,e], L).
% L = [[3,a],[1,b],[3,c],[2,d],[1,e]] .
% ?- packList(R, [[3,a],[1,b],[3,c],[2,d],[1,e]]).
% R = [a,a,a,b,c,c,c,d,d,e] .
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
packList([],[]).
packList([X],[[1,X]]) :- !.
packList([X|Rest],[XRun|Packed]):-
run(X,Rest, XRun,RRest),
packList(RRest,Packed).
run(Var,[],[1, Var],[]).
run(Var,[Var|LRest],[N1, Var],RRest):-
N #> 0,
N1 #= N + 1,
run(Var,LRest,[N, Var],RRest).
run(Var,[Other|RRest], [1, Var],[Other|RRest]):-
dif(Var,Other).
|
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
|
#Racket
|
Racket
|
#lang lazy
(define nats (cons 1 (map add1 nats)))
(define (sift n l) (filter (λ(x) (not (zero? (modulo x n)))) l))
(define (sieve l) (cons (first l) (sieve (sift (first l) (rest l)))))
(define primes (sieve (rest nats)))
(!! (take 25 primes))
|
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
|
#Raku
|
Raku
|
constant @primes = 2, 3, { first * %% none(@_), (@_[* - 1], * + 2 ... *) } ... *;
say @primes[^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.
|
#Lambdatalk
|
Lambdatalk
|
{def nosquare {lambda {:n} {+ :n {floor {+ 0.5 {sqrt :n}}}}}}
-> nosquare
{def issquare {lambda {:n} {= {sqrt :n} {round {sqrt :n}}}}}
-> issquare
{S.map nosquare {S.serie 1 22}}
-> 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
{S.replace false by in
{S.map issquare _
{S.map nosquare
{S.serie 1 1000000}}}}
-> true
|
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
|
#J
|
J
|
union=: ~.@,
intersection=: [ -. -.
difference=: -.
subset=: *./@e.
equality=: -:&(/:~)
|
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
|
#Comal
|
Comal
|
// Sieve of Eratosthenes
input "Limit? ": limit
dim sieve(1:limit)
sqrlimit:=sqr(limit)
sieve(1):=1
p:=2
while p<=sqrlimit do
while sieve(p) and p<sqrlimit do
p:=p+1
endwhile
if p>sqrlimit then goto done
for i:=p*p to limit step p do
sieve(i):=1
endfor i
p:=p+1
endwhile
done:
print 2,
for i:=3 to limit do
if sieve(i)=0 then
print ", ",i,
endif
endfor i
print
|
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
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Console
Imports System.Linq.Enumerable
Module Program
Sub Main()
Dim Text = Function(index As Integer) If(index = 32, "Sp", If(index = 127, "Del", ChrW(index) & ""))
Dim start = 32
Do
WriteLine(String.Concat(Range(0, 6).Select(Function(i) $"{start + 16 * i, -3} : {Text(start + 16 * i), -6}")))
start += 1
Loop While start + 16 * 5 < 128
End Sub
End Module
|
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
|
#Sidef
|
Sidef
|
var c = ['##']
3.times {
c = (c.map{|x| x * 3 } +
c.map{|x| x + ' '*x.len + x } +
c.map{|x| x * 3 })
}
say c.join("\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
|
#Nanoquery
|
Nanoquery
|
import Nanoquery.IO
def reverse_str(string)
ret = ""
for char in list(string).reverse()
ret += char
end
return ret
end
lst = split(new(File).open("rosetta-code/unixdict.txt").readAll(), "\n")
seen = list()
count = 0
for w in lst
w = lower(w)
r = reverse_str(w)
if r in seen
count += 1
if count <= 5
print format("%-10s %-10s\n", w, r)
end
else
seen.append(w)
end
end
println "\nSemordnilap pairs found: " + count
|
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
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref symbols nobinary
/* REXX ***************************************************************
* 07.09.2012 Walter Pachl
**********************************************************************/
fid = 'unixdict.txt' /* the test dictionary */
ifi = File(fid)
ifr = BufferedReader(FileReader(ifi))
have = '' /* words encountered */
pi = 0 /* number of palindromes */
loop label j_ forever /* as long there is input */
line = ifr.readLine /* read a line (String) */
if line = null then leave j_ /* NULL indicates EOF */
w = Rexx(line) /* each line contains 1 word */
If w > '' Then Do /* not a blank line */
r = w.reverse /* reverse it */
If have[r] > '' Then Do /* was already encountered */
pi = pi + 1 /* increment number of pal's */
If pi <= 5 Then /* the first 5 are listed */
Say have[r] w
End
have[w] = w /* remember the word */
End
end j_
ifr.close
Say pi 'words in' fid 'have a palindrome' /* total number found */
return
|
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.
|
#Racket
|
Racket
|
#lang racket
(require math)
(define (pair-factorize n)
"Return all two-number factorizations of a number"
(let ([up-limit (integer-sqrt n)])
(map (λ (x) (list x (/ n x)))
(filter (λ (x) (<= x up-limit)) (divisors n)))))
(define (semiprime n)
"Determine if a number is semiprime i.e. a product of two primes.
Check if any pair of complete factors consists of primes."
(for/or ((pair (pair-factorize n)))
(for/and ((el pair))
(prime? el))))
|
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.
|
#Raku
|
Raku
|
sub is-semiprime (Int $n --> Bool) {
not $n.is-prime and
.is-prime given
$n div first $n %% *, flat grep &is-prime, 2 .. *;
}
use Test;
my @primes = flat grep &is-prime, 2 .. 100;
for ^5 {
nok is-semiprime([*] my @f1 = @primes.roll(1)), ~@f1;
ok is-semiprime([*] my @f2 = @primes.roll(2)), ~@f2;
nok is-semiprime([*] my @f3 = @primes.roll(3)), ~@f3;
nok is-semiprime([*] my @f4 = @primes.roll(4)), ~@f4;
}
|
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
|
#Gambas
|
Gambas
|
Public Sub Main()
Dim byWeight As Byte[] = [1, 3, 1, 7, 3, 9, 1]
Dim byCount, byCompute As Byte
Dim siTotal As Short
Dim sWork As New String[]
Dim sToProcess As String[] = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
"557910", "B0YBKR", "585284", "B0YBKT", "B00030"]
For byCompute = 0 To sToProcess.Max
For byCount = 1 To 6
If IsLetter(Mid(sToProcess[byCompute], byCount, 1)) Then
sWork.Add(Str(Asc(Mid(sToProcess[byCompute], byCount, 1)) - 55) * byWeight[byCount - 1])
Else
sWork.Add(Val(Mid(sToProcess[byCompute], byCount, 1)) * byWeight[byCount - 1])
End If
Next
For byCount = 0 To 5
siTotal += Val(sWork[byCount])
Next
siTotal = (10 - (siTotal Mod 10)) Mod 10
Print sToProcess[byCompute] & " = " & sToProcess[byCompute] & siTotal
sWork.Clear()
siTotal = 0
Next
End
|
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
|
#PureBasic
|
PureBasic
|
Procedure isSelfDescribing(x.q)
;returns 1 if number is self-describing, otherwise it returns 0
Protected digitCount, digit, i, digitSum
Dim digitTally(10)
Dim digitprediction(10)
If x <= 0
ProcedureReturn 0 ;number must be positive and non-zero
EndIf
While x > 0 And i < 10
digit = x % 10
digitSum + digit
If digitSum > 10
ProcedureReturn 0 ;sum of digits' values exceeds maximum possible
EndIf
digitprediction(i) = digit
digitTally(digit) + 1
x / 10
i + 1
Wend
digitCount = i - 1
If digitSum < digitCount Or x > 0
ProcedureReturn 0 ;sum of digits' values is too small or number has more than 10 digits
EndIf
For i = 0 To digitCount
If digitTally(i) <> digitprediction(digitCount - i)
ProcedureReturn 0 ;number is not self-describing
EndIf
Next
ProcedureReturn 1 ;number is self-describing
EndProcedure
Procedure displayAll()
Protected i, j, t
PrintN("Starting search for all self-describing numbers..." + #CRLF$)
For j = 0 To 9
PrintN(#CRLF$ + "Searching possibilites " + Str(j * 1000000000) + " -> " + Str((j + 1) * 1000000000 - 1)+ "...")
t = ElapsedMilliseconds()
For i = 0 To 999999999
If isSelfDescribing(j * 1000000000 + i)
PrintN(Str(j * 1000000000 + i))
EndIf
Next
PrintN("Time to search this range of possibilities: " + Str((ElapsedMilliseconds() - t) / 1000) + "s.")
Next
PrintN(#CRLF$ + "Search complete.")
EndProcedure
If OpenConsole()
DataSection
Data.q 1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000, 3214314
EndDataSection
Define i, x.q
For i = 1 To 8
Read.q x
Print(Str(x) + " is ")
If Not isSelfDescribing(x)
Print("not ")
EndIf
PrintN("selfdescribing.")
Next
PrintN(#CRLF$)
displayAll()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
|
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
|
#REXX
|
REXX
|
/*REXX program lists a sequence of primes by testing primality by trial division. */
parse arg n . /*get optional number of primes to find*/
if n=='' | n=="," then n= 26 /*Not specified? Then use the default.*/
tell= (n>0); n= abs(n) /*Is N negative? Then don't display.*/
@.1=2; if tell then say right(@.1, 9) /*display 2 as a special prime case. */
#=1 /*# is number of primes found (so far)*/
/* [↑] N: default lists up to 101 #s.*/
do j=3 by 2 while #<n /*start with the first odd prime. */
/* [↓] divide by the primes. ___ */
do k=2 to # while !.k<=j /*divide J with all primes ≤ √ J */
if j//@.k==0 then iterate j /*÷ by prev. prime? ¬prime ___ */
end /*j*/ /* [↑] only divide up to √ J */
#= #+1 /*bump the count of number of primes. */
@.#= j; !.#= j*j /*define this prime; define its square.*/
if tell then say right(j, 9) /*maybe display this prime ──► terminal*/
end /*j*/ /* [↑] only display N number of primes*/
/* [↓] display number of primes found.*/
say # ' primes found.' /*stick a fork in it, we're all done. */
|
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
|
#Ring
|
Ring
|
for i = 1 to 100
if isPrime(i) see "" + i + " " ok
next
see nl
func isPrime n
if n < 2 return false ok
if n < 4 return true ok
if n % 2 = 0 return false ok
for d = 3 to sqrt(n) step 2
if n % d = 0 return false ok
next
return true
|
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.
|
#Liberty_BASIC
|
Liberty BASIC
|
for i = 1 to 22
print nonsqr( i); " ";
next i
print
found = 0
for i = 1 to 1000000
j = ( nonsqr( i))^0.5
if j = int( j) then
found = 1
print "Found square: "; i
exit for
end if
next i
if found =0 then print "No squares found"
end
function nonsqr( n)
nonsqr = n +int( 0.5 +n^0.5)
end function
|
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.
|
#Logo
|
Logo
|
repeat 22 [print sum # round sqrt #]
|
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
|
#Java
|
Java
|
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
public class Sets {
public static void main(String[] args){
Set<Integer> a = new TreeSet<>();
//TreeSet sorts on natural ordering (or an optional comparator)
//other options: HashSet (hashcode)
// LinkedHashSet (insertion order)
// EnumSet (optimized for enum values)
//others at: http://download.oracle.com/javase/7/docs/api/java/util/Set.html
Set<Integer> b = new TreeSet<>();
Set<Integer> c = new TreeSet<>();
Set<Integer> d = new TreeSet<>();
a.addAll(Arrays.asList(1, 2, 3, 4, 5));
b.addAll(Arrays.asList(2, 3, 4, 5, 6, 8));
c.addAll(Arrays.asList(2, 3, 4));
d.addAll(Arrays.asList(2, 3, 4));
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("c: " + c);
System.out.println("d: " + d);
System.out.println("2 in a: " + a.contains(2));
System.out.println("6 in a: " + a.contains(6));
Set<Integer> ab = new TreeSet<>();
ab.addAll(a);
ab.addAll(b);
System.out.println("a union b: " + ab);
Set<Integer> a_b = new TreeSet<>();
a_b.addAll(a);
a_b.removeAll(b);
System.out.println("a - b: " + a_b);
System.out.println("c subset of a: " + a.containsAll(c));
//use a.conatins() for single elements
System.out.println("c = d: " + c.equals(d));
System.out.println("d = c: " + d.equals(c));
Set<Integer> aib = new TreeSet<>();
aib.addAll(a);
aib.retainAll(b);
System.out.println("a intersect b: " + aib);
System.out.println("add 7 to a: " + a.add(7));
System.out.println("add 2 to a again: " + a.add(2));
//other noteworthy things related to sets:
Set<Integer> empty = Collections.EMPTY_SET; //immutable empty set
//empty.add(2); would fail
empty.isEmpty(); //test if a set is empty
empty.size();
Collections.disjoint(a, b); //returns true if the sets have no common elems (based on their .equals() methods)
Collections.unmodifiableSet(a); //returns an immutable copy of a
}
}
|
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
|
#Common_Lisp
|
Common Lisp
|
(defun sieve-of-eratosthenes (maximum)
(loop
with sieve = (make-array (1+ maximum)
:element-type 'bit
:initial-element 0)
for candidate from 2 to maximum
when (zerop (bit sieve candidate))
collect candidate
and do (loop for composite from (expt candidate 2)
to maximum by candidate
do (setf (bit sieve composite) 1))))
|
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
|
#Vlang
|
Vlang
|
fn main() {
for i in 0..16{
for j := 32 + i; j < 128; j += 16 {
mut k := u8(j).ascii_str()
match j {
32 {
k = "Spc"
}
127 {
k = "Del"
} else {
}
}
print("${j:3} : ${k:-3} ")
}
println('')
}
}
|
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
|
#Sinclair_ZX81_BASIC
|
Sinclair ZX81 BASIC
|
10 LET O=3
20 LET S=3**O
30 FOR I=0 TO S-1
40 FOR J=0 TO S-1
50 LET X=J
60 LET Y=I
70 GOSUB 120
80 IF C THEN PLOT J,I
90 NEXT J
100 NEXT I
110 GOTO 190
120 LET C=0
130 IF X-INT (X/3)*3=1 AND Y-INT (Y/3)*3=1 THEN RETURN
140 LET X=INT (X/3)
150 LET Y=INT (Y/3)
160 IF X>0 OR Y>0 THEN GOTO 130
170 LET C=1
180 RETURN
|
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
|
#NewLisp
|
NewLisp
|
;;; Get the words as a list, splitting at newline
(setq data
(parse (get-url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
"\n"))
;
;;; destructive reverse wrapped into a function
(define (get-reverse x) (reverse x))
;
;;; stack of the results
(setq res '())
;
;;; Find the semordlinap and put them on the stack
(dolist (x data)
(let (y (get-reverse x))
(if (and
(member y data) ; reverse is a dictionary word
(!= x y) ; but not a palindrome
(not (member y res))) ; not already stacked
(push x res -1))))
;
;;; Count results
(println "Found " (length res) " pairs.")
(println)
;;; Show the longest ones
(dolist (x res)
(if (> (length x) 4) (println x " -- " (get-reverse x))))
|
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.
|
#REXX
|
REXX
|
/* REXX ---------------------------------------------------------------
* 20.02.2014 Walter Pachl relying on 'prime decomposition'
* 21.02.2014 WP Clarification: I copied the algorithm created by
* Gerard Schildberger under the task referred to above
* 21.02.2014 WP Make sure that factr is not called illegally
*--------------------------------------------------------------------*/
Call test 4
Call test 9
Call test 10
Call test 12
Call test 1679
Exit
test:
Parse Arg z
If is_semiprime(z) Then Say z 'is semiprime' fl
Else Say z 'is NOT semiprime' fl
Return
is_semiprime:
Parse Arg z
If z<1 | datatype(z,'W')=0 Then Do
Say 'Argument ('z') must be a natural number (1, 2, 3, ...)'
fl=''
End
Else
fl=factr(z)
Return words(fl)=2
/*----------------------------------FACTR subroutine-----------------*/
factr: procedure; parse arg x 1 z,list /*sets X&Z to arg1, LIST=''. */
if x==1 then return '' /*handle the special case of X=1.*/
j=2; call .factr /*factor for the only even prime.*/
j=3; call .factr /*factor for the 1st odd prime.*/
j=5; call .factr /*factor for the 2nd odd prime.*/
j=7; call .factr /*factor for the 3rd odd prime.*/
j=11; call .factr /*factor for the 4th odd prime.*/
j=13; call .factr /*factor for the 5th odd prime.*/
j=17; call .factr /*factor for the 6th odd prime.*/
/* [?] could be optimized more.*/
/* [?] J in loop starts at 17+2*/
do y=0 by 2; j=j+2+y//4 /*insure J isn't divisible by 3. */
if right(j,1)==5 then iterate /*fast check for divisible by 5. */
if j*j>z then leave /*are we higher than the v of Z ?*/
if j>Z then leave /*are we higher than value of Z ?*/
call .factr /*invoke .FACTR for some factors.*/
end /*y*/ /* [?] only tests up to the v X.*/
/* [?] LIST has a leading blank.*/
if z==1 then return list /*if residual=unity, don't append*/
return list z /*return list, append residual. */
/*-------------------------------.FACTR internal subroutine----------*/
.factr: do while z//j==0 /*keep dividing until we can't. */
list=list j /*add number to the list (J). */
z=z%j /*% (percent) is integer divide.*/
end /*while z··· */ /* // ?---remainder integer ÷.*/
return /*finished, now return to invoker*/
|
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
|
#Go
|
Go
|
package main
import (
"fmt"
"strings"
"strconv"
)
const input = `710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
B
B0003
B000300
A00030
E00030
I00030
O00030
U00030
β00030
β0003`
var weight = [...]int{1,3,1,7,3,9}
func csd(code string) string {
switch len(code) {
case 6:
case 0:
return "No data"
default:
return "Invalid length"
}
sum := 0
for i, c := range code {
n, err := strconv.ParseInt(string(c), 36, 0)
if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' {
return "Invalid character"
}
sum += int(n)*weight[i]
}
return strconv.Itoa(9-(sum-1)%10)
}
func main() {
for _, s := range strings.Split(input, "\n") {
d := csd(s)
if len(d) > 1 {
fmt.Printf(":%s: %s\n", s, d)
} else {
fmt.Println(s + 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
|
#Python
|
Python
|
>>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
|
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
|
#Ruby
|
Ruby
|
require "prime"
pg = Prime::TrialDivisionGenerator.new
p pg.take(10) # => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
p pg.next # => 31
|
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
|
#Rust
|
Rust
|
fn is_prime(number: u32) -> bool {
#[allow(clippy::cast_precision_loss)]
let limit = (number as f32).sqrt() as u32 + 1;
// We test if the number is divisible by any number up to the limit
!(number < 2 || (2..limit).any(|x| number % x == 0))
}
fn main() {
println!(
"Primes below 100:\n{:?}",
(0_u32..100).fold(vec![], |mut acc, number| {
if is_prime(number) {
acc.push(number)
};
acc
})
);
}
|
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
|
#S-BASIC
|
S-BASIC
|
comment
Prime number generator in S-BASIC. Only odd numbers are
checked, and only the prime numbers previously found (up
to the square root of the number currently under examination)
are tested as divisors. Memory is conserved by saving only the
first 50 primes as potential divisors, since that is sufficient
to test all numbers up to 32767, which is the highest integer
value supported by S-BASIC
end
$lines
$constant false = 0
$constant true = 0FFFFH
var i, k, m, n, s, nprimes, divisible = integer
dim integer p(50)
rem compute p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
input "How many primes do you want to generate",nprimes
rem initialize p with first prime and display it
p(1) = 2
print using "##### "; p(1);
rem now check odd numbers until nprimes are found
i = 1 rem count of primes found so far
k = 1 rem index of largest prime <= sqrt of n
n = 3 rem current number being checked
while i < nprimes do
begin
s = p(k) * p(k)
if s <= n then k = k + 1
divisible = false
m = 1 rem index into primes previously found
while (m <= k) and (divisible = false) do
begin
if mod(n, p(m)) = 0 then divisible = true
m = m + 1
end
if divisible = false then
begin
i = i + 1
if i <= 50 then p(i) = n
print using "##### ";n;
if pos(0) > 60 then print rem wrap long lines
end
n = n + 2
end
print "All done. Goodbye"
end
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#Lua
|
Lua
|
function nonSquare (n)
return n + math.floor(1/2 + math.sqrt(n))
end
for n = 1, 22 do
io.write(nonSquare(n) .. " ")
end
print()
local sr
for n = 1, 10^6 do
sr = math.sqrt(nonSquare(n))
if sr == math.floor(sr) then
print("Result for n = " .. n .. " is square!")
os.exit()
end
end
print("No squares found")
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#MAD
|
MAD
|
NORMAL MODE IS INTEGER
BOOLEAN FOUND
FOUND = 0B
R SEQUENCE OF NON-SQUARES FORMULA
R FLOOR IS AUTOMATIC DUE TO INTEGER MATH
INTERNAL FUNCTION NONSQR.(N) = N+(.5+SQRT.(N))
R PRINT VALUES FOR 1..N..22
THROUGH SHOW, FOR N=1, 1, N.G.22
SHOW PRINT FORMAT OUTFMT,N,NONSQR.(N)
VECTOR VALUES OUTFMT = $I2,2H: ,I2*$
R CHECK FOR NO SQUARES UP TO ONE MILLION
THROUGH CHECK, FOR N=1, 1, N.GE.1000000
X=NONSQR.(N)
Y=SQRT.(X)
WHENEVER Y*Y.E.X
PRINT FORMAT FINDSQ,N,X
FOUND = 1B
CHECK END OF CONDITIONAL
WHENEVER .NOT. FOUND, PRINT FORMAT NOSQ
VECTOR VALUES FINDSQ = $5HELEM ,I5,2H, ,I5,11H, IS SQUARE*$
VECTOR VALUES NOSQ = $16HNO SQUARES FOUND*$
END OF PROGRAM
|
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
|
#JavaScript
|
JavaScript
|
var set = new Set();
set.add(0);
set.add(1);
set.add('two');
set.add('three');
set.has(0); //=> true
set.has(3); //=> false
set.has('two'); // true
set.has(Math.sqrt(4)); //=> false
set.has('TWO'.toLowerCase()); //=> true
set.size; //=> 4
set.delete('two');
set.has('two'); //==> false
set.size; //=> 3
//iterating set using ES6 for..of
//Set order is preserved in order items are added.
for (var item of set) {
console.log('item is ' + item);
}
|
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
|
#Cowgol
|
Cowgol
|
include "cowgol.coh";
# To change the maximum prime, change the size of this array
# Everything else is automatically filled in at compile time
var sieve: uint8[5000];
# Make sure all elements of the sieve are set to zero
MemZero(&sieve as [uint8], @bytesof sieve);
# Generate the sieve
var prime: @indexof sieve := 2;
while prime < @sizeof sieve loop
if sieve[prime] == 0 then
var comp: @indexof sieve := prime * prime;
while comp < @sizeof sieve loop
sieve[comp] := 1;
comp := comp + prime;
end loop;
end if;
prime := prime + 1;
end loop;
# Print all primes
var cand: @indexof sieve := 2;
while cand < @sizeof sieve loop
if sieve[cand] == 0 then
print_i16(cand as uint16);
print_nl();
end if;
cand := cand + 1;
end loop;
|
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
|
#Wren
|
Wren
|
import "/fmt" for Fmt
for (i in 0...16) {
var j = 32 + i
while (j < 128) {
var k = "%(String.fromByte(j))"
if (j == 32) {
k = "Spc"
} else if (j == 127) {
k = "Del"
}
System.write("%(Fmt.d(3, j)) : %(Fmt.s(-3, k)) ")
j = j + 16
}
System.print()
}
|
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
|
#Swift
|
Swift
|
import Foundation
func sierpinski_carpet(n:Int) -> String {
func middle(str:String) -> String {
let spacer = str.stringByReplacingOccurrencesOfString("#", withString:" ", options:nil, range:nil)
return str + spacer + str
}
var carpet = ["#"]
for i in 1...n {
let a = carpet.map{$0 + $0 + $0}
let b = carpet.map(middle)
carpet = a + b + a
}
return "\n".join(carpet)
}
println(sierpinski_carpet(3))
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Nim
|
Nim
|
import strutils, sequtils, sets, algorithm
proc reversed(s: string): string =
result = newString(s.len)
for i, c in s:
result[s.high - i] = c
let
words = readFile("unixdict.txt").strip().splitLines()
wordset = words.toHashSet
revs = words.map(reversed)
var pairs = zip(words, revs).filterIt(it[0] < it[1] and it[1] in wordset)
echo "Total number of semordnilaps: ", pairs.len
pairs = pairs.sortedByIt(it[0].len)
echo pairs[^5..^1]
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#OCaml
|
OCaml
|
module StrSet = Set.Make(String)
let str_rev s =
let len = String.length s in
let r = Bytes.create len in
for i = 0 to len - 1 do
Bytes.set r i s.[len - 1 - i]
done;
Bytes.to_string r
let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> close_in ic; None
let () =
let ic = open_in "unixdict.txt" in
let rec aux set acc =
match input_line_opt ic with
| Some word ->
let rev = str_rev word in
if StrSet.mem rev set
then aux set ((word, rev) :: acc)
else aux (StrSet.add word set) acc
| None ->
(acc)
in
let pairs = aux StrSet.empty [] in
let len = List.length pairs in
Printf.printf "Semordnilap pairs: %d\n" len;
Random.self_init ();
for i = 1 to 5 do
let (word, rev) = List.nth pairs (Random.int len) in
Printf.printf " %s %s\n" word rev
done
|
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.
|
#Ring
|
Ring
|
prime = 1679
decomp(prime)
func decomp nr
x = ""
sum = 0
for i = 1 to nr
if isPrime(i) and nr % i = 0
sum = sum + 1
x = x + string(i) + " * " ok
if i = nr and sum = 2
x2 = substr(x,1,(len(x)-2))
see string(nr) + " = " + x2 + "is semiprime" + nl
but i = nr and sum != 2 see string(nr) + " is not semiprime" + nl ok
next
func isPrime n
if n < 2 return false ok
if n < 4 return true ok
if n % 2 = 0 and n != 2 return false ok
for d = 3 to sqrt(n) step 2
if n % d = 0 return false ok
next
return true
|
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.
|
#Ruby
|
Ruby
|
require 'prime'
# 75.prime_division # Returns the factorization.75 divides by 3 once and by 5 twice => [[3, 1], [5, 2]]
class Integer
def semi_prime?
prime_division.sum(&:last) == 2
end
end
p 1679.semi_prime? # true
p ( 1..100 ).select( &:semi_prime? )
# [4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95]
|
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
|
#Groovy
|
Groovy
|
def checksum(text) {
assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/) : "Invalid SEDOL text: $text"
def sum = 0
(0..5).each { index ->
sum += Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index]
}
text + (10 - (sum % 10)) % 10
}
String.metaClass.sedol = { this.&checksum(delegate) }
|
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
|
#Quackery
|
Quackery
|
[ tuck over peek
1+ unrot poke ] is item++ ( n [ --> [ )
[ [] 10 times [ 0 join ]
swap
[ 10 /mod rot item++
swap dup 0 = until ]
drop ] is digitcount ( n --> [ )
[ 0 swap witheach + ] is sum ( [ --> n )
[ 0 swap
witheach
[ swap 10 * + ] ] is digits->n ( [ --> n )
[ dup digitcount
dup sum split drop
digits->n = ] is self-desc ( n --> b )
4000000 times
[ i^ self-desc if
[ i^ echo cr ] ]
|
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
|
#Racket
|
Racket
|
#lang racket
(define (get-digits number (lst null))
(if (zero? number)
lst
(get-digits (quotient number 10) (cons (remainder number 10) lst))))
(define (self-describing? number)
(if (= number 0) #f
(let ((digits (get-digits number)))
(for/fold ((bool #t))
((i (in-range (length digits))))
(and bool
(= (count (lambda (x) (= x i)) digits)
(list-ref digits i)))))))
|
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
|
#Scala
|
Scala
|
def sieve(nums: Stream[Int]): Stream[Int] =
Stream.cons(nums.head, sieve((nums.tail).filter(_ % nums.head != 0)))
val primes = 2 #:: sieve(Stream.from(3, 2))
println(primes take 10 toList) // //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
println(primes takeWhile (_ < 30) toList) //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
|
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
|
#Sidef
|
Sidef
|
func prime_seq(amount, callback) {
var (counter, number) = (0, 0);
while (counter < amount) {
if (is_prime(number)) {
callback(number);
++counter;
}
++number;
}
}
prime_seq(100, {|p| say p}); # prints the first 100 primes
|
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.
|
#Maple
|
Maple
|
with(NumberTheory):
nonSquareSequence := proc(n::integer)
return n + floor(1 / 2 + sqrt(n));
end proc:
seq(nonSquareSequence(i), i = 1..22);
for number from 1 to 10^6 while not issqr(nonSquareSequence(number)) do end;
number;
|
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
nonsq = (# + Floor[0.5 + Sqrt[#]]) &;
nonsq@Range[22]
If[! Or @@ (IntegerQ /@ Sqrt /@ nonsq@Range[10^6]),
Print["No squares for n <= ", 10^6]
]
|
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
|
#jq
|
jq
|
{"a":true, "b":true } == {"b":true, "a":true}.
{"a":true} + {"b":true } == { "a":true, "b":true}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Crystal
|
Crystal
|
# compile with `--release --no-debug` for speed...
require "bit_array"
alias Prime = UInt64
class SoE
include Iterator(Prime)
@bits : BitArray; @bitndx : Int32 = 2
def initialize(range : Prime)
if range < 2
@bits = BitArray.new 0
else
@bits = BitArray.new((range + 1).to_i32)
end
ba = @bits; ndx = 2
while true
wi = ndx * ndx
break if wi >= ba.size
if ba[ndx]
ndx += 1; next
end
while wi < ba.size
ba[wi] = true; wi += ndx
end
ndx += 1
end
end
def next
while @bitndx < @bits.size
if @bits[@bitndx]
@bitndx += 1; next
end
rslt = @bitndx.to_u64; @bitndx += 1; return rslt
end
stop
end
end
print "Primes up to a hundred: "
SoE.new(100).each { |p| print " ", p }; puts
print "Number of primes to a million: "
puts SoE.new(1_000_000).each.size
print "Number of primes to a billion: "
start_time = Time.monotonic
print SoE.new(1_000_000_000).each.size
elpsd = (Time.monotonic - start_time).total_milliseconds
puts " in #{elpsd} milliseconds."
|
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
|
#XPL0
|
XPL0
|
int Hi, Lo;
[SetHexDigits(2);
Text(0, " ");
for Hi:= 2 to 7 do
[HexOut(0, Hi*16); Text(0, " ")];
CrLf(0);
for Lo:= 0 to $F do
[HexOut(0, Lo); Text(0, " ");
for Hi:= 2 to 7 do
[ChOut(0, Hi*16+Lo); Text(0, " ")];
CrLf(0);
];
]
|
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
|
#Tcl
|
Tcl
|
package require Tcl 8.5
proc map {lambda list} {
foreach elem $list {
lappend result [apply $lambda $elem]
}
return $result
}
proc sierpinski_carpet n {
set carpet [list "#"]
for {set i 1} {$i <= $n} {incr i} {
set carpet [concat \
[map {x {subst {$x$x$x}}} $carpet] \
[map {x {subst {$x[string map {"#" " "} $x]$x}}} $carpet] \
[map {x {subst {$x$x$x}}} $carpet] \
]
}
return [join $carpet \n]
}
puts [sierpinski_carpet 3]
|
http://rosettacode.org/wiki/Semordnilap
|
Semordnilap
|
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as lager and regal, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Octave
|
Octave
|
a = strsplit(fileread("unixdict.txt"), "\n");
a = intersect(a, cellfun(@fliplr, a, "UniformOutput", false));
a = a(arrayfun(@(i) ismember(fliplr(a{i}), a(i+1:length(a))), 1:length(a)));
length(a)
arrayfun(@(i) printf("%s %s\n", a{i}, fliplr(a{i})), 1:5)
|
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.
|
#Rust
|
Rust
|
extern crate primal;
fn isqrt(n: usize) -> usize {
(n as f64).sqrt() as usize
}
fn is_semiprime(mut n: usize) -> bool {
let root = isqrt(n) + 1;
let primes1 = primal::Sieve::new(root);
let mut count = 0;
for i in primes1.primes_from(2).take_while(|&x| x < root) {
while n % i == 0 {
n /= i;
count += 1;
}
if n == 1 {
break;
}
}
if n != 1 {
count += 1;
}
count == 2
}
#[test]
fn test1() {
assert_eq!((2..10).filter(|&n| is_semiprime(n)).count(), 3);
}
#[test]
fn test2() {
assert_eq!((2..100).filter(|&n| is_semiprime(n)).count(), 34);
}
#[test]
fn test3() {
assert_eq!((2..1_000).filter(|&n| is_semiprime(n)).count(), 299);
}
#[test]
fn test4() {
assert_eq!((2..10_000).filter(|&n| is_semiprime(n)).count(), 2_625);
}
#[test]
fn test5() {
assert_eq!((2..100_000).filter(|&n| is_semiprime(n)).count(), 23_378);
}
#[test]
fn test6() {
assert_eq!((2..1_000_000).filter(|&n| is_semiprime(n)).count(), 210_035);
}
|
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.
|
#Scala
|
Scala
|
object Semiprime extends App {
def isSP(n: Int): Boolean = {
var nf: Int = 0
var l = n
for (i <- 2 to l/2) {
while (l % i == 0) {
if (nf == 2) return false
nf +=1
l /= i
}
}
nf == 2
}
(2 to 100) filter {isSP(_) == true} foreach {i => print("%d ".format(i))}
println
1675 to 1681 foreach {i => println(i+" -> "+isSP(i))}
}
|
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
|
#Haskell
|
Haskell
|
import Data.Char (isAsciiUpper, isDigit, ord)
-------------------------- SEDOLS ------------------------
checkSum :: String -> String
checkSum x =
case traverse sedolValue x of
Right xs -> (show . checkSumFromSedolValues) xs
Left annotated -> annotated
checkSumFromSedolValues :: [Int] -> Int
checkSumFromSedolValues xs =
rem
( 10
- rem
( sum $
zipWith
(*)
[1, 3, 1, 7, 3, 9]
xs
)
10
)
10
sedolValue :: Char -> Either String Int
sedolValue c
| c `elem` "AEIOU" = Left " ← Unexpected vowel."
| isDigit c = Right (ord c - ord '0')
| isAsciiUpper c = Right (ord c - ord 'A' + 10)
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
(putStrLn . ((<>) <*> checkSum))
[ "710889",
"B0YBKJ",
"406566",
"B0YBLH",
"228276",
"B0YBKL",
"557910",
"B0YBKR",
"585284",
"B0YBKT",
"BOYBKT", -- Ill formed test case - illegal vowel.
"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
|
#Raku
|
Raku
|
my @values = <1210 2020 21200 3211000
42101000 521001000 6210001000 27 115508>;
for @values -> $test {
say "$test is {sdn($test) ?? '' !! 'NOT ' }a self describing number.";
}
sub sdn($n) {
my $s = $n.Str;
my $chars = $s.chars;
my @a = +«$s.comb;
my @b;
for @a -> $i {
return False if $i >= $chars;
++@b[$i];
}
@b[$_] //= 0 for ^$chars;
@a eqv @b;
}
.say if .&sdn for ^9999999;
|
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
|
#Spin
|
Spin
|
con
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial"
pub main | d, n
ser.start(31, 30, 0, 115200)
repeat n from 2 to 100
repeat d from 2 to n-1
if n // d == 0
quit
if d == n
ser.dec(n)
ser.tx(32)
waitcnt(_clkfreq + cnt)
ser.stop
|
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
|
#Swift
|
Swift
|
import Foundation
extension SequenceType {
func takeWhile(include: Generator.Element -> Bool) -> AnyGenerator<Generator.Element> {
var g = self.generate()
return anyGenerator { g.next().flatMap{include($0) ? $0 : nil }}
}
}
var pastPrimes = [2]
var primes = anyGenerator {
_ -> Int? in
defer {
pastPrimes.append(pastPrimes.last!)
let c = pastPrimes.count - 1
for p in anyGenerator({++pastPrimes[c]}) {
let lim = Int(sqrt(Double(p)))
if (!pastPrimes.takeWhile{$0 <= lim}.contains{p % $0 == 0}) { break }
}
}
return pastPrimes.last
}
|
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
|
#Tailspin
|
Tailspin
|
templates ifPrime
def n: $;
[2..~$n -> $n ~/ $ * $] -> \(<~[<=$n>]> $n ! \)!
end ifPrime
templates primes
[2..$ -> ifPrime] !
end primes
100 -> primes -> '$;
' -> !OUT::write
|
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.
|
#MATLAB
|
MATLAB
|
function nonSquares(i)
for n = (1:i)
generatedNumber = n + floor(1/2 + sqrt(n));
if mod(sqrt(generatedNumber),1)==0 %Check to see if the sqrt of the generated number is an integer
fprintf('\n%d generates a square number: %d\n', [n,generatedNumber]);
return
else %If it isn't then the generated number is a square number
if n<=22
fprintf('%d ',generatedNumber);
end
end
end
fprintf('\nNo square numbers were generated for n <= %d\n',i);
end
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#Maxima
|
Maxima
|
nonsquare(n) := n + quotient(isqrt(100 * n) + 5, 10);
makelist(nonsquare(n), n, 1, 20);
[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24]
not_square(n) := isqrt(n)^2 # n$
m: 10^6$
u: makelist(i, i, 1, m)$
is(sublist(u, not_square) = sublist(map(nonsquare, u), lambda([x], x <= m)));
true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.