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/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
|
#Action.21
|
Action!
|
SET EndProg=*
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Bracmat
|
Bracmat
|
(task=
( oracle
= (predicate="is made of green cheese")
(generateTruth=.str$(!arg " " !(its.predicate) "."))
(generateLie=.str$(!arg " " !(its.predicate) "!"))
)
& new$oracle:?SourceOfKnowledge
& put
$ "You may ask the Source of Eternal Wisdom ONE thing.
Enter \"Truth\" or \"Lie\" on the next line and press the <Enter> key.
"
& whl
' ( get':?trueorlie:~Truth:~Lie
& put$"Try again\n"
)
& put$(str$("You want a " !trueorlie ". About what?" \n))
& get'(,STR):?something
& (SourceOfKnowledge..str$(generate !trueorlie))$!something
);
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#C.23
|
C#
|
using System;
class Example
{
public int foo(int x)
{
return 42 + x;
}
}
class Program
{
static void Main(string[] args)
{
var example = new Example();
var method = "foo";
var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });
Console.WriteLine("{0}(5) = {1}", method, result);
}
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Cach.C3.A9_ObjectScript
|
Caché ObjectScript
|
Class Unknown.Example Extends %RegisteredObject
{
Method Foo()
{
Write "This is foo", !
}
Method Bar()
{
Write "This is bar", !
}
}
|
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
|
#AArch64_Assembly
|
AArch64 Assembly
|
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program cribleEras64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
.equ MAXI, 100
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Prime : @ \n"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
TablePrime: .skip 8 * MAXI
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x4,qAdrTablePrime // address prime table
mov x0,#2 // prime 2
bl displayPrime
mov x1,#2
mov x2,#1
1: // loop for multiple of 2
str x2,[x4,x1,lsl #3] // mark multiple of 2
add x1,x1,#2
cmp x1,#MAXI // end ?
ble 1b // no loop
mov x1,#3 // begin indice
mov x3,#1
2:
ldr x2,[x4,x1,lsl #3] // load table élément
cmp x2,#1 // is prime ?
beq 4f
mov x0,x1 // yes -> display
bl displayPrime
mov x2,x1
3: // and loop to mark multiples of this prime
str x3,[x4,x2,lsl #3]
add x2,x2,x1 // add the prime
cmp x2,#MAXI // end ?
ble 3b // no -> loop
4:
add x1,x1,2 // other prime in table
cmp x1,MAXI // end table ?
ble 2b // no -> loop
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTablePrime: .quad TablePrime
/******************************************************************/
/* Display prime table elements */
/******************************************************************/
/* x0 contains the prime */
displayPrime:
stp x1,lr,[sp,-16]! // save registers
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#FreeBASIC
|
FreeBASIC
|
' version 23-10-2016
' compile with: fbc -s console
#Define max 9999 ' max number for the sieve
#Include Once "gmp.bi"
Dim As mpz_ptr p, p1
p = Allocate(Len(__mpz_struct)) : Mpz_init_set_ui(p, 1)
p1 = Allocate(Len(__mpz_struct)) : Mpz_init(p1)
Dim As UInteger i, n, x
Dim As Byte prime(max)
' Sieve of Eratosthenes
For i = 4 To max Step 2
prime(i) = 1
Next
For i = 3 To Sqr(max) Step 2
If prime(i) = 1 Then Continue For
For n = i * i To max Step i * 2
prime(n) = 1
Next
Next
n = 0 : x = 0
For i = 2 To max
If prime(i) = 1 Then Continue For
x = x + 1
mpz_mul_ui(p, p, i)
mpz_sub_ui(p1, p, 1)
If mpz_probab_prime_p(p1, 25) > 0 Then
Print Using "####"; x; : Print ",";
n += 1
If n >= 20 Then Exit For
Continue For
End If
mpz_add_ui(p1, p, 1)
If mpz_probab_prime_p(p1, 25) > 0 Then
Print Using "####"; x; : Print ",";
n += 1
If n >= 20 Then Exit For
End If
Next
Print
mpz_clear(p)
mpz_clear(p1)
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
|
Sequence: nth number with exactly n divisors
|
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
d = Table[
Length[Divisors[n]], {n,
200000}]; t = {}; n = 0; ok = True; While[ok, n++;
If[PrimeQ[n], AppendTo[t, Prime[n]^(n - 1)],
c = Flatten[Position[d, n, 1, n]];
If[Length[c] >= n, AppendTo[t, c[[n]]], ok = False]]];
t
|
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
|
Sequence: nth number with exactly n divisors
|
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors
|
#Nim
|
Nim
|
import math, strformat
import bignum
type Record = tuple[num, count: Natural]
template isOdd(n: Natural): bool =
(n and 1) != 0
func isPrime(n: int): bool =
let bi = newInt(n)
result = bi.probablyPrime(25) != 0
proc findPrimes(limit: Natural): seq[int] {.compileTime.} =
result = @[2]
var isComposite = newSeq[bool](limit + 1)
var p = 3
while true:
let p2 = p * p
if p2 > limit: break
for i in countup(p2, limit, 2 * p):
isComposite[i] = true
while true:
inc p, 2
if not isComposite[p]: break
for n in countup(3, limit, 2):
if not isComposite[n]:
result.add n
const Primes = findPrimes(22_000)
proc countDivisors(n: Natural): int =
result = 1
var n = n
for i, p in Primes:
if p * p > n: break
if n mod p != 0: continue
n = n div p
var count = 1
while n mod p == 0:
n = n div p
inc count
result *= count + 1
if n == 1: return
if n != 1: result *= 2
const Max = 45
var records: array[0..Max, Record]
echo &"The first {Max} terms in the sequence are:"
for n in 1..Max:
if n.isPrime:
var z = newInt(Primes[n - 1])
z = pow(z, culong(n - 1))
echo &"{n:2}: {z}"
else:
var count = records[n].count
if count == n:
echo &"{n:2}: {records[n].num}"
continue
let odd = n.isOdd
let d = if odd or n == 2 or n == 10: 1 else: 2
var k = records[n].num
while true:
inc k, d
if odd:
let sq = sqrt(k.toFloat).int
if sq * sq != k: continue
let cd = k.countDivisors()
if cd == n:
inc count
if count == n:
echo &"{n:2}: {k}"
break
elif cd in (n + 1)..Max and records[cd].count < cd and
k > records[cd].num and (d == 1 or d == 2 and not cd.isOdd):
records[cd].num = k
inc records[cd].count
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#F.23
|
F#
|
let (|SeqNode|SeqEmpty|) s =
if Seq.isEmpty s then SeqEmpty
else SeqNode ((Seq.head s), Seq.skip 1 s)
let SetDisjunct x y = Set.isEmpty (Set.intersect x y)
let rec consolidate s = seq {
match s with
| SeqEmpty -> ()
| SeqNode (this, rest) ->
let consolidatedRest = consolidate rest
for that in consolidatedRest do
if (SetDisjunct this that) then yield that
yield Seq.fold (fun x y -> if not (SetDisjunct x y) then Set.union x y else x) this consolidatedRest
}
[<EntryPoint>]
let main args =
let makeSeqOfSet listOfList = List.map (fun x -> Set.ofList x) listOfList |> Seq.ofList
List.iter (fun x -> printfn "%A" (consolidate (makeSeqOfSet x))) [
[["A";"B"]; ["C";"D"]];
[["A";"B"]; ["B";"C"]];
[["A";"B"]; ["C";"D"]; ["D";"B"]];
[["H";"I";"K"]; ["A";"B"]; ["C";"D"]; ["D";"B"]; ["F";"G";"H"]]
]
0
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#J
|
J
|
sieve=: 3 :0
range=. <. + i.@:|@:-
tally=. y#0
for_i.#\tally do.
j=. }:^:(y<:{:)i * 1 range >: <. y % i
tally=. j >:@:{`[`]} tally
end.
/:~({./.~ {."1) tally,.i.#tally
)
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Java
|
Java
|
import java.util.Arrays;
public class OEIS_A005179 {
static int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
public static void main(String[] args) {
final int max = 15;
int[] seq = new int[max];
System.out.printf("The first %d terms of the sequence are:\n", max);
for (int i = 1, n = 0; n < max; ++i) {
int k = count_divisors(i);
if (k <= max && seq[k - 1] == 0) {
seq[k- 1] = i;
n++;
}
}
System.out.println(Arrays.toString(seq));
}
}
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Oberon-2
|
Oberon-2
|
MODULE SHA256;
IMPORT
Crypto:SHA256,
Crypto:Utils,
Strings,
Out;
VAR
h: SHA256.Hash;
str: ARRAY 128 OF CHAR;
BEGIN
h := SHA256.NewHash();
h.Initialize;
str := "Rosetta code";
h.Update(str,0,Strings.Length(str));
h.GetHash(str,0);
Out.String("SHA256: ");Utils.PrintHex(str,0,h.size);Out.Ln
END SHA256.
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Objeck
|
Objeck
|
class ShaHash {
function : Main(args : String[]) ~ Nil {
hash:= Encryption.Hash->SHA256("Rosetta code"->ToByteArray());
str := hash->ToHexString()->ToLower();
str->PrintLine();
str->Equals("764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")->PrintLine();
}
}
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#Perl
|
Perl
|
use strict;
use warnings;
use ntheory 'divisors';
print "First 15 terms of OEIS: A069654\n";
my $m = 0;
for my $n (1..15) {
my $l = $m;
while (++$l) {
print("$l "), $m = $l, last if $n == divisors($l);
}
}
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#Phix
|
Phix
|
with javascript_semantics
constant limit = 15
sequence res = repeat(0,limit)
integer next = 1
atom n = 1
while next<=limit do
integer k = length(factors(n,1))
if k=next then
res[k] = n
next += 1
if next>4 and is_prime(next) then
n := power(2,next-1)-1 -- (-1 for +=1 next)
end if
end if
n += 1
end while
printf(1,"The first %d terms are: %v\n",{limit,res})
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#Oberon-2
|
Oberon-2
|
MODULE SHA1;
IMPORT
Crypto:SHA1,
Crypto:Utils,
Strings,
Out;
VAR
h: SHA1.Hash;
str: ARRAY 128 OF CHAR;
BEGIN
h := SHA1.NewHash();
h.Initialize;
str := "Rosetta Code";
h.Update(str,0,Strings.Length(str));
h.GetHash(str,0);
Out.String("SHA1: ");Utils.PrintHex(str,0,h.size);Out.Ln
END SHA1.
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
|
Seven-sided dice from five-sided dice
|
Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
|
#Sidef
|
Sidef
|
func dice5 { 1 + 5.rand.int }
func dice7 {
loop {
var d7 = ((5*dice5() + dice5() - 6) % 8);
d7 && return d7;
}
}
var count7 = Hash.new;
var n = 1e6;
n.times { count7{dice7()} := 0 ++ }
count7.keys.sort.each { |k|
printf("%s: %5.2f%%\n", k, 100*(count7{k}/n * 7 - 1));
}
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
|
Seven-sided dice from five-sided dice
|
Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
|
#Tcl
|
Tcl
|
proc D5 {} {expr {1 + int(5 * rand())}}
proc D7 {} {
while 1 {
set d55 [expr {5 * [D5] + [D5] - 6}]
if {$d55 < 21} {
return [expr {$d55 % 7 + 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
|
#JavaScript
|
JavaScript
|
(() => {
"use strict";
// ------------------- ASCII TABLE -------------------
// asciiTable :: String
const asciiTable = () =>
transpose(
chunksOf(16)(
enumFromTo(32)(127)
.map(asciiEntry)
)
)
.map(
xs => xs.map(justifyLeft(12)(" "))
.join("")
)
.join("\n");
// asciiEntry :: Int -> String
const asciiEntry = n => {
const k = asciiName(n);
return "" === k ? (
""
) : `${justifyRight(4)(" ")(n.toString())} : ${k}`;
};
// asciiName :: Int -> String
const asciiName = n =>
32 > n || 127 < n ? (
""
) : 32 === n ? (
"Spc"
) : 127 === n ? (
"Del"
) : chr(n);
// ---------------- GENERIC FUNCTIONS ----------------
// chr :: Int -> Char
const chr = x =>
// The character at unix code-point x.
String.fromCodePoint(x);
// chunksOf :: Int -> [a] -> [[a]]
const chunksOf = n => {
// xs split into sublists of length n.
// The last sublist will be short if n
// does not evenly divide the length of xs .
const go = xs => {
const chunk = xs.slice(0, n);
return 0 < chunk.length ? (
[chunk].concat(
go(xs.slice(n))
)
) : [];
};
return go;
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// justifyLeft :: Int -> Char -> String -> String
const justifyLeft = n =>
// The string s, followed by enough padding (with
// the character c) to reach the string length n.
c => s => n > s.length ? (
s.padEnd(n, c)
) : s;
// justifyRight :: Int -> Char -> String -> String
const justifyRight = n =>
// The string s, preceded by enough padding (with
// the character c) to reach the string length n.
c => s => Boolean(s) ? (
s.padStart(n, c)
) : "";
// transpose :: [[a]] -> [[a]]
const transpose = rows =>
// The columns of the input transposed
// into new rows.
// This version assumes input rows of even length.
0 < rows.length ? rows[0].map(
(x, i) => rows.flatMap(
v => v[i]
)
) : [];
// MAIN ---
return asciiTable();
})();
|
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
|
#Pop11
|
Pop11
|
define triangle(n);
lvars k = 2**n, j, l, oline, nline;
initv(2*k+3) -> oline;
initv(2*k+3) -> nline;
for l from 1 to 2*k+3 do 0 -> oline(l) ; endfor;
1 -> oline(k+2);
0 -> nline(1);
0 -> nline(2*k+3);
for j from 1 to k do
for l from 1 to 2*k+3 do
printf(if oline(l) = 0 then ' ' else '*' endif);
endfor;
printf('\n');
for l from 2 to 2*k+2 do
(oline(l-1) + oline(l+1)) rem 2 -> nline(l);
endfor;
(oline, nline) -> (nline, oline);
endfor;
enddefine;
triangle(4);
|
http://rosettacode.org/wiki/Sierpinski_carpet
|
Sierpinski carpet
|
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
|
#Nascom_BASIC
|
Nascom BASIC
|
10 REM Sierpinski carpet
20 CLS
30 LET RDR=3
40 LET S=3^RDR
50 FOR I=0 TO S-1
60 FOR J=0 TO S-1
70 LET X=J
80 LET Y=I
90 GOSUB 300
100 IF C THEN SET(J,I)
110 NEXT J
120 NEXT I
130 REM ** Set up machine code INKEY$ command
140 IF PEEK(1)<>0 THEN RESTORE 410
150 DOKE 4100,3328:FOR A=3328 TO 3342 STEP 2
160 READ B:DOKE A,B:NEXT A
170 SCREEN 1,15
180 PRINT "Hit any key to exit.";
190 A=USR(0):IF A<0 THEN 190
200 CLS
210 END
290 REM ** Is (X,Y) in the carpet?
295 REM Returns C=0 (no) or C=1 (yes).
300 LET C=0
310 XD3=INT(X/3):YD3=INT(Y/3)
320 IF X-XD3*3=1 AND Y-YD3*3=1 THEN RETURN
330 LET X=XD3
340 LET Y=YD3
350 IF X>0 OR Y>0 THEN GOTO 310
360 LET C=1
370 RETURN
395 REM ** Data for machine code INKEY$
400 DATA 25055,1080,-53,536,-20665,3370,-5664,0
410 DATA 27085,14336,-13564,6399,18178,10927
420 DATA -8179,233
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#PARI.2FGP
|
PARI/GP
|
a(n)={
print(a"("n")");
a
};
b(n)={
print("b("n")");
n
};
or(A,B)={
a(A) || b(B)
};
and(A,B)={
a(A) && b(B)
};
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#AutoHotkey
|
AutoHotkey
|
sSubject:= "greeting"
sText := "hello"
sFrom := "ahk@rosettacode"
sTo := "whomitmayconcern"
sServer := "smtp.gmail.com" ; specify your SMTP server
nPort := 465 ; 25
bTLS := True ; False
inputbox, sUsername, Username
inputbox, sPassword, password
COM_Init()
pmsg := COM_CreateObject("CDO.Message")
pcfg := COM_Invoke(pmsg, "Configuration")
pfld := COM_Invoke(pcfg, "Fields")
COM_Invoke(pfld, "Item", "http://schemas.microsoft.com/cdo/configuration/sendusing", 2)
COM_Invoke(pfld, "Item", "http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout", 60)
COM_Invoke(pfld, "Item", "http://schemas.microsoft.com/cdo/configuration/smtpserver", sServer)
COM_Invoke(pfld, "Item", "http://schemas.microsoft.com/cdo/configuration/smtpserverport", nPort)
COM_Invoke(pfld, "Item", "http://schemas.microsoft.com/cdo/configuration/smtpusessl", bTLS)
COM_Invoke(pfld, "Item", "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1)
COM_Invoke(pfld, "Item", "http://schemas.microsoft.com/cdo/configuration/sendusername", sUsername)
COM_Invoke(pfld, "Item", "http://schemas.microsoft.com/cdo/configuration/sendpassword", sPassword)
COM_Invoke(pfld, "Update")
COM_Invoke(pmsg, "Subject", sSubject)
COM_Invoke(pmsg, "From", sFrom)
COM_Invoke(pmsg, "To", sTo)
COM_Invoke(pmsg, "TextBody", sText)
COM_Invoke(pmsg, "Send")
COM_Release(pfld)
COM_Release(pcfg)
COM_Release(pmsg)
COM_Term()
#Include COM.ahk
|
http://rosettacode.org/wiki/Set_of_real_numbers
|
Set of real numbers
|
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | a < x and x < b }
[a, b): {x | a ≤ x and x < b }
(a, b]: {x | a < x and x ≤ b }
Note that if a = b, of the four only [a, a] would be non-empty.
Task
Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
Provide methods for these common set operations (x is a real number; A and B are sets):
x ∈ A: determine if x is an element of A
example: 1 is in [1, 2), while 2, 3, ... are not.
A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B}
example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B}
example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B}
example: [0, 2) − (1, 3) = [0, 1]
Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
(0, 1] ∪ [0, 2)
[0, 2) ∩ (1, 2]
[0, 3) − (0, 1)
[0, 3) − [0, 1]
Implementation notes
'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
Optional work
Create a function to determine if a given set is empty (contains no element).
Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that
|sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
|
#D
|
D
|
struct Set(T) {
const pure nothrow bool delegate(in T) contains;
bool opIn_r(in T x) const pure nothrow {
return contains(x);
}
Set opBinary(string op)(in Set set)
const pure nothrow if (op == "+" || op == "-") {
static if (op == "+")
return Set(x => contains(x) || set.contains(x));
else
return Set(x => contains(x) && !set.contains(x));
}
Set intersection(in Set set) const pure nothrow {
return Set(x => contains(x) && set.contains(x));
}
}
unittest { // Test union.
alias DSet = Set!double;
const s = DSet(x => 0.0 < x && x <= 1.0) +
DSet(x => 0.0 <= x && x < 2.0);
assert(0.0 in s);
assert(1.0 in s);
assert(2.0 !in s);
}
unittest { // Test difference.
alias DSet = Set!double;
const s1 = DSet(x => 0.0 <= x && x < 3.0) -
DSet(x => 0.0 < x && x < 1.0);
assert(0.0 in s1);
assert(0.5 !in s1);
assert(1.0 in s1);
assert(2.0 in s1);
const s2 = DSet(x => 0.0 <= x && x < 3.0) -
DSet(x => 0.0 <= x && x <= 1.0);
assert(0.0 !in s2);
assert(1.0 !in s2);
assert(2.0 in s2);
const s3 = DSet(x => 0 <= x && x <= double.infinity) -
DSet(x => 1.0 <= x && x <= 2.0);
assert(0.0 in s3);
assert(1.5 !in s3);
assert(3.0 in s3);
}
unittest { // Test intersection.
alias DSet = Set!double;
const s = DSet(x => 0.0 <= x && x < 2.0).intersection(
DSet(x => 1.0 < x && x <= 2.0));
assert(0.0 !in s);
assert(1.0 !in s);
assert(2.0 !in s);
}
void main() {}
|
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
|
#11l
|
11l
|
F prime(a)
R !(a < 2 | any((2 .. Int(a ^ 0.5)).map(x -> @a % x == 0)))
F primes_below(n)
R (0 .< n).filter(i -> prime(i))
print(primes_below(100))
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#11l
|
11l
|
F non_square(Int n)
R n + Int(floor(1/2 + sqrt(n)))
print_elements((1..22).map(non_square))
F is_square(n)
R fract(sqrt(n)) == 0
L(i) 1 .< 10 ^ 6
I is_square(non_square(i))
print(‘Square found ’i)
L.break
L.was_no_break
print(‘No squares found’)
|
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
|
#Ada
|
Ada
|
with ada.containers.ordered_sets, ada.text_io;
use ada.text_io;
procedure set_demo is
package cs is new ada.containers.ordered_sets (character); use cs;
function "+" (s : string) return set is
(if s = "" then empty_set else Union(+ s(s'first..s'last - 1), To_Set (s(s'last))));
function "-" (s : Set) return string is
(if s = empty_set then "" else - (s - To_Set (s.last_element)) & s.last_element);
s1, s2 : set;
begin
loop
put ("s1= ");
s1 := + get_line;
exit when s1 = +"Quit!";
put ("s2= ");
s2 := + get_line;
Put_Line("Sets [" & (-s1) & "], [" & (-s2) & "] of size"
& S1.Length'img & " and" & s2.Length'img & ".");
Put_Line("Intersection: [" & (-(Intersection(S1, S2))) & "],");
Put_Line("Union: [" & (-(Union(s1, s2))) & "],");
Put_Line("Difference: [" & (-(Difference(s1, s2))) & "],");
Put_Line("Symmetric Diff: [" & (-(s1 xor s2)) & "],");
Put_Line("Subset: " & Boolean'Image(s1.Is_Subset(s2))
& ", Equal: " & Boolean'Image(s1 = s2) & ".");
end loop;
end set_demo;
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Clojure
|
Clojure
|
(import '[java.util Date])
(import '[clojure.lang Reflector])
(def date1 (Date.))
(def date2 (Date.))
(def method "equals")
;; Two ways of invoking method "equals" on object date1
;; using date2 as argument
;; Way 1 - Using Reflector class
;; NOTE: The argument date2 is passed inside an array
(Reflector/invokeMethod date1 method (object-array [date2]))
;; Way 2 - Using eval
;; Eval runs any piece of valid Clojure code
;; So first we construct a piece of code to do what we want (where method name is inserted dynamically),
;; then we run the code using eval
(eval `(. date1 ~(symbol method) date2))
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Common_Lisp
|
Common Lisp
|
(funcall (intern "SOME-METHOD") my-object a few arguments)
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
local :object { :add @+ }
local :method :add
!. object! method 1 2
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#E
|
E
|
for name in ["foo", "bar"] {
E.call(example, name, [])
}
|
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
|
#ABAP
|
ABAP
|
PARAMETERS: p_limit TYPE i OBLIGATORY DEFAULT 100.
AT SELECTION-SCREEN ON p_limit.
IF p_limit LE 1.
MESSAGE 'Limit must be higher then 1.' TYPE 'E'.
ENDIF.
START-OF-SELECTION.
FIELD-SYMBOLS: <fs_prime> TYPE flag.
DATA: gt_prime TYPE TABLE OF flag,
gv_prime TYPE flag,
gv_i TYPE i,
gv_j TYPE i.
DO p_limit TIMES.
IF sy-index > 1.
gv_prime = abap_true.
ELSE.
gv_prime = abap_false.
ENDIF.
APPEND gv_prime TO gt_prime.
ENDDO.
gv_i = 2.
WHILE ( gv_i <= trunc( sqrt( p_limit ) ) ).
IF ( gt_prime[ gv_i ] EQ abap_true ).
gv_j = gv_i ** 2.
WHILE ( gv_j <= p_limit ).
gt_prime[ gv_j ] = abap_false.
gv_j = ( gv_i ** 2 ) + ( sy-index * gv_i ).
ENDWHILE.
ENDIF.
gv_i = gv_i + 1.
ENDWHILE.
LOOP AT gt_prime INTO gv_prime.
IF gv_prime = abap_true.
WRITE: / sy-tabix.
ENDIF.
ENDLOOP.
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Go
|
Go
|
package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
pm := big.NewInt(1) // primorial
var px, nx int
var pb big.Int // a scratch value
primes(4000, func(p int64) bool {
pm.Mul(pm, pb.SetInt64(p))
px++
if pb.Add(pm, one).ProbablyPrime(0) ||
pb.Sub(pm, one).ProbablyPrime(0) {
fmt.Print(px, " ")
nx++
if nx == 20 {
fmt.Println()
return false
}
}
return true
})
}
// Code taken from task Sieve of Eratosthenes, and put into this function
// that calls callback function f for each prime < limit, but terminating
// if the callback returns false.
func primes(limit int, f func(int64) bool) {
c := make([]bool, limit)
c[0] = true
c[1] = true
lm := int64(limit)
p := int64(2)
for {
f(p)
p2 := p * p
if p2 >= lm {
break
}
for i := p2; i < lm; i += p {
c[i] = true
}
for {
p++
if !c[p] {
break
}
}
}
for p++; p < lm; p++ {
if !c[p] && !f(p) {
break
}
}
}
|
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
|
Sequence: nth number with exactly n divisors
|
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors
|
#Perl
|
Perl
|
use strict;
use warnings;
use bigint;
use ntheory <nth_prime is_prime divisors>;
my $limit = 20;
print "First $limit terms of OEIS:A073916\n";
for my $n (1..$limit) {
if ($n > 4 and is_prime($n)) {
print nth_prime($n)**($n-1) . ' ';
} else {
my $i = my $x = 0;
while (1) {
my $nn = $n%2 ? ++$x**2 : ++$x;
next unless $n == divisors($nn) and ++$i == $n;
print "$nn " and last;
}
}
}
|
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
|
Sequence: nth number with exactly n divisors
|
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors
|
#Phix
|
Phix
|
with javascript_semantics
constant LIMIT = 24
include mpfr.e
mpz z = mpz_init()
sequence fn = repeat(0,LIMIT) fn[1] = 1
integer k = 1
printf(1,"The first %d terms in the sequence are:\n",LIMIT)
for i=1 to LIMIT do
if is_prime(i) then
mpz_ui_pow_ui(z,get_prime(i),i-1)
printf(1,"%2d : %s\n",{i,mpz_get_str(z)})
else
while fn[i]<i do
k += 1
integer l = length(factors(k,1))
if l<=LIMIT and fn[l]<l then
fn[l] = iff(fn[l]+1<l?fn[l]+1:k)
end if
end while
printf(1,"%2d : %d\n",{i,fn[i]})
end if
end for
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Factor
|
Factor
|
USING: arrays kernel sequences sets ;
: comb ( x x -- x )
over empty? [ nip 1array ] [
dup pick first intersects?
[ [ unclip ] dip union comb ]
[ [ 1 cut ] dip comb append ] if
] if ;
: consolidate ( x -- x ) { } [ comb ] reduce ;
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Go
|
Go
|
package main
import "fmt"
type set map[string]bool
var testCase = []set{
set{"H": true, "I": true, "K": true},
set{"A": true, "B": true},
set{"C": true, "D": true},
set{"D": true, "B": true},
set{"F": true, "G": true, "H": true},
}
func main() {
fmt.Println(consolidate(testCase))
}
func consolidate(sets []set) []set {
setlist := []set{}
for _, s := range sets {
if s != nil && len(s) > 0 {
setlist = append(setlist, s)
}
}
for i, s1 := range setlist {
if len(s1) > 0 {
for _, s2 := range setlist[i+1:] {
if s1.disjoint(s2) {
continue
}
for e := range s1 {
s2[e] = true
delete(s1, e)
}
s1 = s2
}
}
}
r := []set{}
for _, s := range setlist {
if len(s) > 0 {
r = append(r, s)
}
}
return r
}
func (s1 set) disjoint(s2 set) bool {
for e := range s2 {
if s1[e] {
return false
}
}
return true
}
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#jq
|
jq
|
# divisors as an unsorted stream (without calling sqrt)
def divisors:
if . == 1 then 1
else . as $n
| label $out
| range(1; $n) as $i
| ($i * $i) as $i2
| if $i2 > $n then break $out
else if $i2 == $n
then $i
elif ($n % $i) == 0
then $i, ($n/$i)
else empty
end
end
end;
def count(s): reduce s as $x (0; .+1);
# smallest number with exactly n divisors
def A005179:
. as $n
| first( range(1; infinite) | select( count(divisors) == $n ));
# The task:
"The first 15 terms of the sequence are:",
[range(1; 16) | A005179]
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Julia
|
Julia
|
using Primes
numfactors(n) = reduce(*, e+1 for (_,e) in factor(n); init=1)
A005179(n) = findfirst(k -> numfactors(k) == n, 1:typemax(Int))
println("The first 15 terms of the sequence are:")
println(map(A005179, 1:15))
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Objective-C
|
Objective-C
|
clang -o rosetta_sha256 rosetta_sha256.m /System/Library/Frameworks/Cocoa.framework/Cocoa
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#OCaml
|
OCaml
|
let () =
let s = "Rosetta code" in
let digest = Sha256.string s in
print_endline (Sha256.to_hex digest)
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#PL.2FI
|
PL/I
|
100H: /* FIND THE SMALLEST NUMBER > THE PREVIOUS ONE WITH EXACTLY N DIVISORS */
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* CONSOLE OUTPUT ROUTINES */
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, 0AH, '$' ) ); END;
PR$NUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE INITIAL( '.....$' ), W BYTE;
N$STR( W := LAST( N$STR ) - 1 ) = '0' + ( ( V := N ) MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
/* TASK */
/* RETURNS THE DIVISOR COUNT OF N */
COUNT$DIVISORS: PROCEDURE( N )ADDRESS;
DECLARE N ADDRESS;
DECLARE ( I, I2, COUNT ) ADDRESS;
COUNT = 0;
I = 1;
DO WHILE( ( I2 := I * I ) < N );
IF N MOD I = 0 THEN COUNT = COUNT + 2;
I = I + 1;
END;
IF I2 = N THEN RETURN ( COUNT + 1 ); ELSE RETURN ( COUNT );
END COUNT$DIVISORS ;
DECLARE MAX LITERALLY '15';
DECLARE ( I, NEXT ) ADDRESS;
CALL PR$STRING( .'THE FIRST $' );
CALL PR$NUMBER( MAX );
CALL PR$STRING( .' TERMS OF THE SEQUENCE ARE:$' );
NEXT = 1;
I = 1;
DO WHILE( NEXT <= MAX );
IF NEXT = COUNT$DIVISORS( I ) THEN DO;
CALL PR$CHAR( ' ' );
CALL PR$NUMBER( I );
NEXT = NEXT + 1;
END;
I = I + 1;
END;
EOF
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#OCaml
|
OCaml
|
$ ocaml -I +sha sha1.cma
Objective Caml version 3.12.1
# Sha1.to_hex (Sha1.string "Rosetta Code") ;;
- : string = "48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#Octave
|
Octave
|
sprintf("%02x", SHA1(+"Rosetta Code"(:)))
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
|
Seven-sided dice from five-sided dice
|
Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
|
#VBA
|
VBA
|
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean
'Returns true if the observed frequencies pass the Pearson Chi-squared test at the required significance level.
Dim Total As Long, Ei As Long, i As Integer
Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double
Debug.Print "[1] ""Data set:"" ";
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
Total = Total + ObservationFrequencies(i)
Debug.Print ObservationFrequencies(i); " ";
Next i
DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)
'This is exactly the number of different categories minus 1
Ei = Total / (DegreesOfFreedom + 1)
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei
Next i
p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)
Debug.Print
Debug.Print "Chi-squared test for given frequencies"
Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", ";
Debug.Print "df ="; DegreesOfFreedom; ", ";
Debug.Print "p-value = "; Format(p_value, "0.0000")
Test4DiscreteUniformDistribution = p_value > Significance
End Function
Private Function Dice5() As Integer
Dice5 = Int(5 * Rnd + 1)
End Function
Private Function Dice7() As Integer
Dim i As Integer
Do
i = 5 * (Dice5 - 1) + Dice5
Loop While i > 21
Dice7 = i Mod 7 + 1
End Function
Sub TestDice7()
Dim i As Long, roll As Integer
Dim Bins(1 To 7) As Variant
For i = 1 To 1000000
roll = Dice7
Bins(roll) = Bins(roll) + 1
Next i
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """"
End Sub
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
|
Seven-sided dice from five-sided dice
|
Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
|
#VBScript
|
VBScript
|
Option Explicit
function dice5
dice5 = int(rnd*5) + 1
end function
function dice7
dim j
do
j = 5 * dice5 + dice5 - 6
loop until j < 21
dice7 = j mod 7 + 1
end function
|
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
|
#Jsish
|
Jsish
|
#!/usr/bin/env jsish
/* Show ASCII table, -showAll true to include control codes */
function showASCIITable(args:array|string=void, conf:object=void) {
var options = { // Rosetta Code, Show ASCII table
rootdir :'', // Root directory.
showAll : false // include control code labels if true
};
var self = {};
parseOpts(self, options, conf);
function main() {
var e;
var first = (self.showAll) ? 0 : 2;
var filler = '='.repeat(19 + ((first) ? 0 : 9));
puts(filler, "ASCII table", filler + '=');
var labels = [
'NUL', 'SOH', 'STX', 'ETX', 'EOT', 'ENQ', 'ACK', 'BEL',
'BS ', 'HT ', 'LF ', 'VT ', 'FF ', 'CR ', 'SO ', 'SI ',
'DLE', 'DC1', 'DC2', 'DC3', 'DC4', 'NAK', 'SYN', 'ETB',
'CAN', 'EM ', 'SUB', 'ESC', 'FS ', 'GS ', 'RS ', 'US '];
var table = new Array(128);
for (e = 0; e < 32; e++) table[e] = labels[e];
for (e = 32; e < 127; e++) table[e] = ' ' + Util.fromCharCode(e) + ' ';
table[32] = 'SPC';
table[127] = 'DEL';
for (var row = 0; row < 16; row++) {
for (var col = first; col < 8; col++) {
e = row + col * 16;
printf('%03d %s ', e, table[e]);
}
printf('\n');
}
}
return main();
}
provide(showASCIITable, 1);
if (isMain()) {
if (Interp.conf('unitTest')) showASCIITable('', {showAll:true});
else runModule(showASCIITable);
}
/*
=!EXPECTSTART!=
============================ ASCII table =============================
000 NUL 016 DLE 032 SPC 048 0 064 @ 080 P 096 ` 112 p
001 SOH 017 DC1 033 ! 049 1 065 A 081 Q 097 a 113 q
002 STX 018 DC2 034 " 050 2 066 B 082 R 098 b 114 r
003 ETX 019 DC3 035 # 051 3 067 C 083 S 099 c 115 s
004 EOT 020 DC4 036 $ 052 4 068 D 084 T 100 d 116 t
005 ENQ 021 NAK 037 % 053 5 069 E 085 U 101 e 117 u
006 ACK 022 SYN 038 & 054 6 070 F 086 V 102 f 118 v
007 BEL 023 ETB 039 ' 055 7 071 G 087 W 103 g 119 w
008 BS 024 CAN 040 ( 056 8 072 H 088 X 104 h 120 x
009 HT 025 EM 041 ) 057 9 073 I 089 Y 105 i 121 y
010 LF 026 SUB 042 * 058 : 074 J 090 Z 106 j 122 z
011 VT 027 ESC 043 + 059 ; 075 K 091 [ 107 k 123 {
012 FF 028 FS 044 , 060 < 076 L 092 \ 108 l 124 |
013 CR 029 GS 045 - 061 = 077 M 093 ] 109 m 125 }
014 SO 030 RS 046 . 062 > 078 N 094 ^ 110 n 126 ~
015 SI 031 US 047 / 063 ? 079 O 095 _ 111 o 127 DEL
=!EXPECTEND!=
*/
|
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
|
#PostScript
|
PostScript
|
%!PS-Adobe-3.0
%%BoundingBox 0 0 300 300
/F { 1 0 rlineto } def
/+ { 120 rotate } def
/- {-120 rotate } def
/v {.5 .5 scale } def
/^ { 2 2 scale } def
/!0{ dup 1 sub dup -1 eq not } def
/X { !0 { v X + F - X - F + X ^ } { F } ifelse pop } def
0 1 8 { 300 300 scale 0 1 12 div moveto
X + F + F fill showpage } for
%%EOF
|
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
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 1000
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
DARK_SHADE = '\u2593'
parse arg ordr filr .
if ordr = '' | ordr = '.' then ordr = 3
if filr = '' | filr = '.' then filler = DARK_SHADE
else filler = filr
drawSierpinskiCarpet(ordr, filler)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method drawSierpinskiCarpet(ordr, filler = Rexx '@') public static binary
x = long
y = long
powr = 3 ** ordr
loop x = 0 to powr - 1
loop y = 0 to powr - 1
if isSierpinskiCarpetCellFilled(x, y) then cell = filler
else cell = ' '
say cell'\-'
end y
say
end x
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isSierpinskiCarpetCellFilled(x = long, y = long) public static binary returns boolean
isTrue = boolean (1 == 1)
isFalse = \isTrue
isFilled = isTrue
loop label edge while x \= 0 & y \= 0
if x // 3 = 1 & y // 3 = 1 then do
isFilled = isFalse
leave edge
end
x = x % 3
y = y % 3
end edge
return isFilled
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Pascal
|
Pascal
|
program shortcircuit(output);
function a(value: boolean): boolean;
begin
writeln('a(', value, ')');
a := value
end;
function b(value:boolean): boolean;
begin
writeln('b(', value, ')');
b := value
end;
procedure scandor(value1, value2: boolean);
var
result: boolean;
begin
{and}
if a(value1)
then
result := b(value2)
else
result := false;
writeln(value1, ' and ', value2, ' = ', result);
{or}
if a(value1)
then
result := true
else
result := b(value2)
writeln(value1, ' or ', value2, ' = ', result);
end;
begin
scandor(false, false);
scandor(false, true);
scandor(true, false);
scandor(true, true);
end.
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#BBC_BASIC
|
BBC BASIC
|
INSTALL @lib$+"SOCKLIB"
Server$ = "smtp.gmail.com"
From$ = "sender@somewhere"
To$ = "recipient@elsewhere"
CC$ = "another@nowhere"
Subject$ = "Rosetta Code"
Message$ = "This is a test of sending email."
PROCsendmail(Server$, From$, To$, CC$, "", Subject$, "", Message$)
END
DEF PROCsendmail(smtp$,from$,to$,cc$,bcc$,subject$,replyto$,body$)
LOCAL D%, S%, skt%, reply$
DIM D% LOCAL 31, S% LOCAL 15
SYS "GetLocalTime", S%
SYS "GetDateFormat", 0, 0, S%, "ddd, dd MMM yyyy ", D%, 18
SYS "GetTimeFormat", 0, 0, S%, "HH:mm:ss +0000", D%+17, 15
D%?31 = 13
PROC_initsockets
skt% = FN_tcpconnect(smtp$,"mail")
IF skt% <= 0 skt% = FN_tcpconnect(smtp$,"25")
IF skt% <= 0 ERROR 100, "Failed to connect to SMTP server"
IF FN_readlinesocket(skt%, 1000, reply$)
WHILE FN_readlinesocket(skt%, 10, reply$) > 0 : ENDWHILE
PROCsend(skt%,"HELO "+FN_gethostname)
PROCmail(skt%,"MAIL FROM: ",from$)
IF to$<>"" PROClist(skt%,to$)
IF cc$<>"" PROClist(skt%,cc$)
IF bcc$<>"" PROClist(skt%,bcc$)
PROCsend(skt%, "DATA")
IF FN_writelinesocket(skt%, "Date: "+$D%)
IF FN_writelinesocket(skt%, "From: "+from$)
IF FN_writelinesocket(skt%, "To: "+to$)
IF cc$<>"" IF FN_writelinesocket(skt%, "Cc: "+cc$)
IF subject$<>"" IF FN_writelinesocket(skt%, "Subject: "+subject$)
IF replyto$<>"" IF FN_writelinesocket(skt%, "Reply-To: "+replyto$)
IF FN_writelinesocket(skt%, "MIME-Version: 1.0")
IF FN_writelinesocket(skt%, "Content-type: text/plain; charset=US-ASCII")
IF FN_writelinesocket(skt%, "")
IF FN_writelinesocket(skt%, body$)
IF FN_writelinesocket(skt%, ".")
PROCsend(skt%,"QUIT")
PROC_exitsockets
ENDPROC
DEF PROClist(skt%,list$)
LOCAL comma%
REPEAT
WHILE ASClist$=32 list$=MID$(list$,2):ENDWHILE
comma% = INSTR(list$,",")
IF comma% THEN
PROCmail(skt%,"RCPT TO: ",LEFT$(list$,comma%-1))
list$ = MID$(list$,comma%+1)
ELSE
PROCmail(skt%,"RCPT TO: ",list$)
ENDIF
UNTIL comma% = 0
ENDPROC
DEF PROCmail(skt%,cmd$,mail$)
LOCAL I%,J%
I% = INSTR(mail$,"<")
J% = INSTR(mail$,">",I%)
IF I% IF J% THEN
PROCsend(skt%, cmd$+MID$(mail$,I%,J%-I%+1))
ELSE
PROCsend(skt%, cmd$+"<"+mail$+">")
ENDIF
ENDPROC
DEF PROCsend(skt%,cmd$)
LOCAL reply$
IF FN_writelinesocket(skt%,cmd$) < 0 THEN ERROR 100, "Send failed"
IF FN_readlinesocket(skt%, 200, reply$)
WHILE FN_readlinesocket(skt%, 10, reply$) > 0 : ENDWHILE
ENDPROC
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#C
|
C
|
#include <curl/curl.h>
#include <string.h>
#include <stdio.h>
#define from "<[email protected]>"
#define to "<[email protected]>"
#define cc "<[email protected]>"
static const char *payload_text[] = {
"Date: Mon, 13 Jun 2018 11:30:00 +0100\r\n",
"To: " to "\r\n",
"From: " from " (Example User)\r\n",
"Cc: " cc " (Another example User)\r\n",
"Message-ID: <ecd7db36-10ab-437a-9g3a-e652b9458efd@"
"rfcpedant.example.org>\r\n",
"Subject: Sanding mail via C\r\n",
"\r\n",
"This mail is being sent by a C program.\r\n",
"\r\n",
"It connects to the GMail SMTP server, by far, the most popular mail program of all.\r\n",
"Which is also probably written in C.\r\n",
"To C or not to C..............\r\n",
"That is the question.\r\n",
NULL
};
struct upload_status {
int lines_read;
};
static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)
{
struct upload_status *upload_ctx = (struct upload_status *)userp;
const char *data;
if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) {
return 0;
}
data = payload_text[upload_ctx->lines_read];
if(data) {
size_t len = strlen(data);
memcpy(ptr, data, len);
upload_ctx->lines_read++;
return len;
}
return 0;
}
int main(void)
{
CURL *curl;
CURLcode res = CURLE_OK;
struct curl_slist *recipients = NULL;
struct upload_status upload_ctx;
upload_ctx.lines_read = 0;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_USERNAME, "user");
curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret");
curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:465");
curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem");
curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from);
recipients = curl_slist_append(recipients, to);
recipients = curl_slist_append(recipients, cc);
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
curl_slist_free_all(recipients);
curl_easy_cleanup(curl);
}
return (int)res;
}
|
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.
|
#11l
|
11l
|
F is_semiprime(=c)
V a = 2
V b = 0
L b < 3 & c != 1
I c % a == 0
c /= a
b++
E
a++
R b == 2
print((1..100).filter(n -> is_semiprime(n)))
|
http://rosettacode.org/wiki/Set_of_real_numbers
|
Set of real numbers
|
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | a < x and x < b }
[a, b): {x | a ≤ x and x < b }
(a, b]: {x | a < x and x ≤ b }
Note that if a = b, of the four only [a, a] would be non-empty.
Task
Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
Provide methods for these common set operations (x is a real number; A and B are sets):
x ∈ A: determine if x is an element of A
example: 1 is in [1, 2), while 2, 3, ... are not.
A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B}
example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B}
example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B}
example: [0, 2) − (1, 3) = [0, 1]
Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
(0, 1] ∪ [0, 2)
[0, 2) ∩ (1, 2]
[0, 3) − (0, 1)
[0, 3) − [0, 1]
Implementation notes
'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
Optional work
Create a function to determine if a given set is empty (contains no element).
Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that
|sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
|
#Delphi
|
Delphi
|
program Set_of_real_numbers;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TSet = TFunc<Double, boolean>;
function Union(a, b: TSet): TSet;
begin
Result :=
function(x: double): boolean
begin
Result := a(x) or b(x);
end;
end;
function Inter(a, b: TSet): TSet;
begin
Result :=
function(x: double): boolean
begin
Result := a(x) and b(x);
end;
end;
function Diff(a, b: TSet): TSet;
begin
Result :=
function(x: double): boolean
begin
Result := a(x) and not b(x);
end;
end;
function Open(a, b: double): TSet;
begin
Result :=
function(x: double): boolean
begin
Result := (a < x) and (x < b);
end;
end;
function closed(a, b: double): TSet;
begin
Result :=
function(x: double): boolean
begin
Result := (a <= x) and (x <= b);
end;
end;
function opCl(a, b: double): TSet;
begin
Result :=
function(x: double): boolean
begin
Result := (a < x) and (x <= b);
end;
end;
function clOp(a, b: double): TSet;
begin
Result :=
function(x: double): boolean
begin
Result := (a <= x) and (x < b);
end;
end;
const
BOOLSTR: array[Boolean] of string = ('False', 'True');
begin
var s: TArray<TSet>;
SetLength(s, 4);
s[0] := Union(opCl(0, 1), clOp(0, 2)); // (0,1] ? [0,2)
s[1] := Inter(clOp(0, 2), opCl(1, 2)); // [0,2) n (1,2]
s[2] := Diff(clOp(0, 3), open(0, 1)); // [0,3) - (0,1)
s[3] := Diff(clOp(0, 3), closed(0, 1)); // [0,3) - [0,1]
for var i := 0 to High(s) do
begin
for var x := 0 to 2 do
writeln(format('%d e s%d: %s', [x, i, BOOLSTR[s[i](x)]]));
writeln;
end;
readln;
end.
|
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
|
Sequence of primes by trial division
|
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers.
You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes.
The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value.
Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation.
If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
|
#Action.21
|
Action!
|
BYTE FUNC IsPrime(CARD a)
CARD i
IF a<=1 THEN
RETURN (0)
FI
FOR i=2 TO a/2
DO
IF a MOD i=0 THEN
RETURN (0)
FI
OD
RETURN (1)
PROC PrintPrimes(CARD begin,end)
BYTE notFirst
CARD i
notFirst=0
FOR i=begin TO end
DO
IF IsPrime(i) THEN
IF notFirst THEN
Print(", ")
FI
notFirst=1
PrintC(i)
FI
OD
RETURN
PROC Main()
CARD begin=[2000],end=[3000]
PrintF("Primes in range [%U..%U]:%E",begin,end)
PrintPrimes(begin,end)
RETURN
|
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
|
#Ada
|
Ada
|
with Prime_Numbers, Ada.Text_IO, Ada.Command_Line;
procedure Sequence_Of_Primes is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Start: Natural := Natural'Value(Ada.Command_Line.Argument(1));
Stop: Natural := Natural'Value(Ada.Command_Line.Argument(2));
begin
for I in Start .. Stop loop
if Is_Prime(I) then
Ada.Text_IO.Put(Natural'Image(I));
end if;
end loop;
end Sequence_Of_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.
|
#Ada
|
Ada
|
with Ada.Numerics.Long_Elementary_Functions;
with Ada.Text_IO; use Ada.Text_IO;
procedure Sequence_Of_Non_Squares_Test is
use Ada.Numerics.Long_Elementary_Functions;
function Non_Square (N : Positive) return Positive is
begin
return N + Positive (Long_Float'Rounding (Sqrt (Long_Float (N))));
end Non_Square;
I : Positive;
begin
for N in 1..22 loop -- First 22 non-squares
Put (Natural'Image (Non_Square (N)));
end loop;
New_Line;
for N in 1..1_000_000 loop -- Check first million of
I := Non_Square (N);
if I = Positive (Sqrt (Long_Float (I)))**2 then
Put_Line ("Found a square:" & Positive'Image (N));
end if;
end loop;
end Sequence_Of_Non_Squares_Test;
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Aime
|
Aime
|
record
union(record a, record b)
{
record c;
r_copy(c, a);
r_wcall(b, r_add, 1, 2, c);
return c;
}
record
intersection(record a, record b)
{
record c;
text s;
for (s in a) {
if (r_key(b, s)) {
c[s] = 0;
}
}
return c;
}
record
difference(record a, record b)
{
record c;
r_copy(c, a);
r_vcall(b, r_resign, 1, c);
return c;
}
integer
subset(record a, record b)
{
integer e;
text s;
e = 1;
for (s in a) {
if (!r_key(b, s)) {
e = 0;
break;
}
}
return e;
}
integer
equal(record a, record b)
{
return subset(a, b) && subset(b, a);
}
integer
main(void)
{
record a, b;
text s;
r_fit(a, "apple", 0, "cherry", 0, "grape", 0);
r_fit(b, "banana", 0, "cherry", 0, "date", 0);
s = "banana";
o_(" ", s, " is ", r_key(a, s) ? "" : "not ", "an element of A\n");
o_(" ", s, " is ", r_key(b, s) ? "" : "not ", "an element of B\n");
r_vcall(union(a, b), o_, 1, " ");
o_newline();
r_vcall(intersection(a, b), o_, 1, " ");
o_newline();
r_vcall(difference(a, b), o_, 1, " ");
o_newline();
o_(" ", subset(a, b) ? "yes" : "no", "\n");
o_(" ", equal(a, b) ? "yes" : "no", "\n");
return 0;
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Elena
|
Elena
|
import extensions;
class Example
{
foo(x)
= x + 42;
}
public program()
{
var example := new Example();
var methodSignature := "foo";
var invoker := new MessageName(methodSignature);
var result := invoker(example,5);
console.printLine(methodSignature,"(",5,") = ",result)
}
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Factor
|
Factor
|
USING: accessors kernel math prettyprint sequences words ;
IN: rosetta-code.unknown-method-call
TUPLE: foo num ;
C: <foo> foo
GENERIC: add5 ( x -- y )
M: foo add5 num>> 5 + ;
42 <foo> ! construct a foo
"add" "5" append ! construct a word name
! must specify vocab to look up a word
"rosetta-code.unknown-method-call"
lookup-word execute . ! 47
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Forth
|
Forth
|
include FMS-SI.f
include FMS-SILib.f
var x \ instantiate a class var object named x
\ Use a standard Forth string and evaluate it.
\ This is equivalent to sending the !: message to object x
42 x s" !:" evaluate
x p: 42 \ send the print message ( p: ) to x to verify the contents
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Go
|
Go
|
package main
import (
"fmt"
"reflect"
)
type example struct{}
// the method must be exported to be accessed through reflection.
func (example) Foo() int {
return 42
}
func main() {
// create an object with a method
var e example
// get the method by name
m := reflect.ValueOf(e).MethodByName("Foo")
// call the method with no argments
r := m.Call(nil)
// interpret first return value as int
fmt.Println(r[0].Int()) // => 42
}
|
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
|
#ACL2
|
ACL2
|
(defun nats-to-from (n i)
(declare (xargs :measure (nfix (- n i))))
(if (zp (- n i))
nil
(cons i (nats-to-from n (+ i 1)))))
(defun remove-multiples-up-to-r (factor limit xs i)
(declare (xargs :measure (nfix (- limit i))))
(if (or (> i limit)
(zp (- limit i))
(zp factor))
xs
(remove-multiples-up-to-r
factor
limit
(remove i xs)
(+ i factor))))
(defun remove-multiples-up-to (factor limit xs)
(remove-multiples-up-to-r factor limit xs (* factor 2)))
(defun sieve-r (factor limit)
(declare (xargs :measure (nfix (- limit factor))))
(if (zp (- limit factor))
(nats-to-from limit 2)
(remove-multiples-up-to factor (+ limit 1)
(sieve-r (1+ factor) limit))))
(defun sieve (limit)
(sieve-r 2 limit))
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Haskell
|
Haskell
|
import Data.List (scanl1, elemIndices, nub)
primes :: [Integer]
primes = 2 : filter isPrime [3,5 ..]
isPrime :: Integer -> Bool
isPrime = isPrime_ primes
where
isPrime_ :: [Integer] -> Integer -> Bool
isPrime_ (p:ps) n
| p * p > n = True
| n `mod` p == 0 = False
| otherwise = isPrime_ ps n
primorials :: [Integer]
primorials = 1 : scanl1 (*) primes
primorialsPlusMinusOne :: [Integer]
primorialsPlusMinusOne = concatMap (((:) . pred) <*> (return . succ)) primorials
sequenceOfPrimorialPrimes :: [Int]
sequenceOfPrimorialPrimes = (tail . nub) $ (`div` 2) <$> elemIndices True bools
where
bools = isPrime <$> primorialsPlusMinusOne
main :: IO ()
main = mapM_ print $ take 10 sequenceOfPrimorialPrimes
|
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
|
Sequence: nth number with exactly n divisors
|
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors
|
#Python
|
Python
|
def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n % ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def is_prime(n):
return len(divisors(n)) == 2
def primes():
ii = 1
while True:
ii += 1
if is_prime(ii):
yield ii
def prime(n):
generator = primes()
for ii in range(n - 1):
generator.__next__()
return generator.__next__()
def n_divisors(n):
ii = 0
while True:
ii += 1
if len(divisors(ii)) == n:
yield ii
def sequence(max_n=None):
if max_n is not None:
for ii in range(1, max_n + 1):
if is_prime(ii):
yield prime(ii) ** (ii - 1)
else:
generator = n_divisors(ii)
for jj, out in zip(range(ii - 1), generator):
pass
yield generator.__next__()
else:
ii = 1
while True:
ii += 1
if is_prime(ii):
yield prime(ii) ** (ii - 1)
else:
generator = n_divisors(ii)
for jj, out in zip(range(ii - 1), generator):
pass
yield generator.__next__()
if __name__ == '__main__':
for item in sequence(15):
print(item)
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Haskell
|
Haskell
|
import Data.List (intersperse, intercalate)
import qualified Data.Set as S
consolidate
:: Ord a
=> [S.Set a] -> [S.Set a]
consolidate = foldr comb []
where
comb s_ [] = [s_]
comb s_ (s:ss)
| S.null (s `S.intersection` s_) = s : comb s_ ss
| otherwise = comb (s `S.union` s_) ss
-- TESTS -------------------------------------------------
main :: IO ()
main =
(putStrLn . unlines)
((intercalate ", and " . fmap showSet . consolidate) . fmap S.fromList <$>
[ ["ab", "cd"]
, ["ab", "bd"]
, ["ab", "cd", "db"]
, ["hik", "ab", "cd", "db", "fgh"]
])
showSet :: S.Set Char -> String
showSet = flip intercalate ["{", "}"] . intersperse ',' . S.elems
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Kotlin
|
Kotlin
|
// Version 1.3.21
const val MAX = 15
fun countDivisors(n: Int): Int {
var count = 0
var i = 1
while (i * i <= n) {
if (n % i == 0) {
count += if (i == n / i) 1 else 2
}
i++
}
return count
}
fun main() {
var seq = IntArray(MAX)
println("The first $MAX terms of the sequence are:")
var i = 1
var n = 0
while (n < MAX) {
var k = countDivisors(i)
if (k <= MAX && seq[k - 1] == 0) {
seq[k - 1] = i
n++
}
i++
}
println(seq.asList())
}
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#OS_X_sha256sum
|
OS X sha256sum
|
echo -n 'Rosetta code' | sha256sum
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#PARI.2FGP
|
PARI/GP
|
sha256(s)=extern("echo \"Str(`echo -n '"Str(s)"'|sha256sum|cut -d' ' -f1`)\"")
|
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
|
Sequence: smallest number greater than previous term with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A069654
Related tasks
Sequence: smallest number with exactly n divisors
Sequence: nth number with exactly n divisors
|
#PL.2FM
|
PL/M
|
100H: /* FIND THE SMALLEST NUMBER > THE PREVIOUS ONE WITH EXACTLY N DIVISORS */
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* CONSOLE OUTPUT ROUTINES */
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, 0AH, '$' ) ); END;
PR$NUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE INITIAL( '.....$' ), W BYTE;
N$STR( W := LAST( N$STR ) - 1 ) = '0' + ( ( V := N ) MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
/* TASK */
/* RETURNS THE DIVISOR COUNT OF N */
COUNT$DIVISORS: PROCEDURE( N )ADDRESS;
DECLARE N ADDRESS;
DECLARE ( I, I2, COUNT ) ADDRESS;
COUNT = 0;
I = 1;
DO WHILE( ( I2 := I * I ) < N );
IF N MOD I = 0 THEN COUNT = COUNT + 2;
I = I + 1;
END;
IF I2 = N THEN RETURN ( COUNT + 1 ); ELSE RETURN ( COUNT );
END COUNT$DIVISORS ;
DECLARE MAX LITERALLY '15';
DECLARE ( I, NEXT ) ADDRESS;
CALL PR$STRING( .'THE FIRST $' );
CALL PR$NUMBER( MAX );
CALL PR$STRING( .' TERMS OF THE SEQUENCE ARE:$' );
NEXT = 1;
I = 1;
DO WHILE( NEXT <= MAX );
IF NEXT = COUNT$DIVISORS( I ) THEN DO;
CALL PR$CHAR( ' ' );
CALL PR$NUMBER( I );
NEXT = NEXT + 1;
END;
I = I + 1;
END;
EOF
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#PARI.2FGP
|
PARI/GP
|
sha1(s)=extern("echo \"Str(`echo -n '"Str(s)"'|sha1sum|cut -d' ' -f1`)\"")
|
http://rosettacode.org/wiki/SHA-1
|
SHA-1
|
SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
|
#Pascal
|
Pascal
|
program RosettaSha1;
uses
sha1;
var
d: TSHA1Digest;
begin
d:=SHA1String('Rosetta Code');
WriteLn(SHA1Print(d));
end.
|
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
|
Seven-sided dice from five-sided dice
|
Task
(Given an equal-probability generator of one of the integers 1 to 5
as dice5), create dice7 that generates a pseudo-random integer from
1 to 7 in equal probability using only dice5 as a source of random
numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion:
dice7 might call dice5 twice, re-call if four of the 25
combinations are given, otherwise split the other 21 combinations
into 7 groups of three, and return the group index from the rolls.
(Task adapted from an answer here)
|
#Verilog
|
Verilog
|
///////////////////////////////////////////////////////////////////////////////
/// seven_sided_dice_tb : (testbench) ///
/// Check the distribution of the output of a seven sided dice circuit ///
///////////////////////////////////////////////////////////////////////////////
module seven_sided_dice_tb;
reg [31:0] freq[0:6];
reg clk;
wire [2:0] dice_face;
reg req;
wire valid_roll;
integer i;
initial begin
clk <= 0;
forever begin
#1;
clk <= ~clk;
end
end
initial begin
req <= 1'b1;
for(i = 0; i < 7; i = i + 1) begin
freq[i] <= 32'b0;
end
repeat(10) @(posedge clk);
repeat(7000000) begin
@(posedge clk);
while(~valid_roll) begin
@(posedge clk);
end
freq[dice_face] <= freq[dice_face] + 32'b1;
end
$display("********************************************");
$display("*** Seven sided dice distribution: ");
$display(" Theoretical distribution is an uniform ");
$display(" distribution with (1/7)-probability ");
$display(" for each possible outcome, ");
$display(" The experimental distribution is: ");
for(i = 0; i < 7; i = i + 1) begin
if(freq[i] < 32'd1_000_000) begin
$display("%d with probability 1/7 - (%d ppm)", i, (32'd1_000_000 - freq[i])/7);
end
else begin
$display("%d with probability 1/7 + (%d ppm)", i, (freq[i] - 32'd1_000_000)/7);
end
end
$finish;
end
seven_sided_dice DUT(
.clk(clk),
.req(req),
.valid_roll(valid_roll),
.dice_face(dice_face)
);
endmodule
///////////////////////////////////////////////////////////////////////////////
/// seven_sided_dice : ///
/// Synthsizeable module that using a 5 sided dice as a black box ///
/// is able to reproduce the outcomes if a 7-sided dice ///
///////////////////////////////////////////////////////////////////////////////
module seven_sided_dice(
input wire clk,
input wire req,
output reg valid_roll,
output reg [2:0] dice_face
);
wire [2:0] face1;
wire [2:0] face2;
reg [4:0] combination;
reg req_p1;
reg req_p2;
reg req_p3;
always @(posedge clk) begin
req_p1 <= req;
req_p2 <= req_p1;
end
always @(posedge clk) begin
if(req_p1) begin
combination <= face1 + face2 + {face2, 2'b00};
end
if(req_p2) begin
case(combination)
5'd0, 5'd1, 5'd2: {valid_roll, dice_face} <= {1'b1, 3'd0};
5'd3, 5'd4, 5'd5: {valid_roll, dice_face} <= {1'b1, 3'd1};
5'd6, 5'd7, 5'd8: {valid_roll, dice_face} <= {1'b1, 3'd2};
5'd9, 5'd10, 5'd11: {valid_roll, dice_face} <= {1'b1, 3'd3};
5'd12, 5'd13, 5'd14: {valid_roll, dice_face} <= {1'b1, 3'd4};
5'd15, 5'd16, 5'd17: {valid_roll, dice_face} <= {1'b1, 3'd5};
5'd18, 5'd19, 5'd20: {valid_roll, dice_face} <= {1'b1, 3'd6};
default: valid_roll <= 1'b0;
endcase
end
end
five_sided_dice dice1(
.clk(clk),
.req(req),
.dice_face(face1)
);
five_sided_dice dice2(
.clk(clk),
.req(req),
.dice_face(face2)
);
endmodule
///////////////////////////////////////////////////////////////////////////////
/// five_sided_dice : ///
/// A model of the five sided dice component ///
///////////////////////////////////////////////////////////////////////////////
module five_sided_dice(
input wire clk,
input wire req,
output reg [2:0] dice_face
);
always @(posedge clk) begin
if(req) begin
dice_face <= $urandom % 5;
end
end
endmodule
|
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
|
#jq
|
jq
|
# Pretty printing
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def table($ncols; $colwidth):
nwise($ncols) | map(lpad($colwidth)) | join(" ");
# transposed table
def ttable($rows):
[nwise($rows)] | transpose[] | join(" ");
# Representation of control characters, etc
def humanize:
def special:
{ "0": "NUL", "7": "BEL", "8": "BKS",
"9": "TAB", "10": "LF ", "13": "CR ",
"27": "ESC", "127": "DEL", "155": "CSI" };
if . < 32 or . == 127 or . == 155
then (special[tostring] // "^" + ([64+.]|implode))
elif . > 127 and . < 160 then "\\\(.+72|tostring)"
else [.] | implode
end
| lpad(4) ;
|
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
|
#PowerShell
|
PowerShell
|
function triangle($o) {
$n = [Math]::Pow(2, $o)
$line = ,' '*(2*$n+1)
$line[$n] = '█'
$OFS = ''
for ($i = 0; $i -lt $n; $i++) {
Write-Host $line
$u = '█'
for ($j = $n - $i; $j -lt $n + $i + 1; $j++) {
if ($line[$j-1] -eq $line[$j+1]) {
$t = ' '
} else {
$t = '█'
}
$line[$j-1] = $u
$u = $t
}
$line[$n+$i] = $t
$line[$n+$i+1] = '█'
}
}
|
http://rosettacode.org/wiki/Sierpinski_carpet
|
Sierpinski carpet
|
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
|
#Nim
|
Nim
|
import math
proc inCarpet(x, y: int): bool =
var x = x
var y = y
while true:
if x == 0 or y == 0:
return true
if x mod 3 == 1 and y mod 3 == 1:
return false
x = x div 3
y = y div 3
proc carpet(n: int) =
for i in 0 ..< 3^n:
for j in 0 ..< 3^n:
stdout.write if inCarpet(i, j): "* " else: " "
echo()
carpet(3)
|
http://rosettacode.org/wiki/Short-circuit_evaluation
|
Short-circuit evaluation
|
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
|
#Perl
|
Perl
|
sub a { print 'A'; return $_[0] }
sub b { print 'B'; return $_[0] }
# Test-driver
sub test {
for my $op ('&&','||') {
for (qw(1,1 1,0 0,1 0,0)) {
my ($x,$y) = /(.),(.)/;
print my $str = "a($x) $op b($y)", ': ';
eval $str; print "\n"; } }
}
# Test and display
test();
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#C.23
|
C#
|
static void Main(string[] args)
{
//First of all construct the SMTP client
SmtpClient SMTP = new SmtpClient("smtp.gmail.com", 587); //I have provided the URI and port for GMail, replace with your providers SMTP details
SMTP.EnableSsl = true; //Required for gmail, may not for your provider, if your provider does not require it then use false.
SMTP.DeliveryMethod = SmtpDeliveryMethod.Network;
SMTP.Credentials = new NetworkCredential("YourUserName", "YourPassword");
MailMessage Mail = new MailMessage("[email protected]", "[email protected]");
//Then we construct the message
Mail.Subject = "Important Message";
Mail.Body = "Hello over there"; //The body contains the string for your email
//using "Mail.IsBodyHtml = true;" you can put an HTML page in your message body
//Then we use the SMTP client to send the message
SMTP.Send(Mail);
Console.WriteLine("Message Sent");
}
|
http://rosettacode.org/wiki/Send_email
|
Send email
|
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
|
#C.2B.2B
|
C++
|
// on Ubuntu: sudo apt-get install libpoco-dev
// or see http://pocoproject.org/
// compile with: g++ -Wall -O3 send-mail-cxx.C -lPocoNet -lPocoFoundation
#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
using namespace Poco::Net;
int main (int argc, char **argv)
{
try
{
MailMessage msg;
msg.addRecipient (MailRecipient (MailRecipient::PRIMARY_RECIPIENT,
"[email protected]",
"Alice Moralis"));
msg.addRecipient (MailRecipient (MailRecipient::CC_RECIPIENT,
"[email protected]",
"Patrick Kilpatrick"));
msg.addRecipient (MailRecipient (MailRecipient::BCC_RECIPIENT,
"[email protected]",
"Michael Carmichael"));
msg.setSender ("Roy Kilroy <[email protected]>");
msg.setSubject ("Rosetta Code");
msg.setContent ("Sending mail from C++ using POCO C++ Libraries");
SMTPClientSession smtp ("mail.example.com"); // SMTP server name
smtp.login ();
smtp.sendMessage (msg);
smtp.close ();
std::cerr << "Sent mail successfully!" << std::endl;
}
catch (std::exception &e)
{
std::cerr << "failed to send mail: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
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.
|
#360_Assembly
|
360 Assembly
|
* Semiprime 14/03/2017
SEMIPRIM CSECT
USING SEMIPRIM,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R10,PG pgi=0
LA R8,0 m=0
L R6,=F'2' i=2
DO WHILE=(C,R6,LE,=F'100') do i=2 to 100
ST R6,N n=i
LA R9,0 f=0
LA R7,2 j=2
LOOPJ EQU * do j=2 while f<2 and j*j<=n
C R9,=F'2' if f<2
BNL EXITJ then exit do j
LR R5,R7 j
MR R4,R7 *j
C R5,N if j*j<=n
BH EXITJ then exit do j
LOOPK EQU * do while n mod j=0
L R4,N n
SRDA R4,32 ~
DR R4,R7 /j
LTR R4,R4 if n mod <>0
BNZ EXITK then exit do j
ST R5,N n=n/j
LA R9,1(R9) f=f+1
B LOOPK enddo k
EXITK LA R7,1(R7) j++
B LOOPJ enddo j
EXITJ L R4,N n
IF C,R4,GT,=F'1' THEN if n>1 then
LA R2,1 g=1
ELSE , else
LA R2,0 g=0
ENDIF , endif
AR R2,R9 +f
IF C,R2,EQ,=F'2' THEN if f+(n>1)=2 then
XDECO R6,XDEC edit i
MVC 0(5,R10),XDEC+7 output i
LA R10,5(R10) pgi=pgi+10
LA R8,1(R8) m=m+1
LR R4,R8 m
SRDA R4,32 ~
D R4,=F'16' m/16
IF LTR,R4,Z,R4 THEN if m mod 16=0 then
XPRNT PG,L'PG print buffer
MVC PG,=CL80' ' clear buffer
LA R10,PG pgi=0
ENDIF , endif
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT PG,L'PG print buffer
MVC PG,=CL80'..... semiprimes' init buffer
XDECO R8,XDEC edit m
MVC PG(5),XDEC+7 output m
XPRNT PG,L'PG print buffer
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
N DS F n
PG DC CL80' ' buffer
XDEC DS CL12 temp
YREGS
END SEMIPRIM
|
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.
|
#Action.21
|
Action!
|
BYTE FUNC IsSemiPrime(INT n)
INT a,b
a=2 b=0
WHILE b<3 AND n#1
DO
IF n MOD a=0 THEN
n==/a b==+1
ELSE
a==+1
FI
OD
IF b=2 THEN
RETURN(1)
FI
RETURN(0)
PROC Main()
INT i
PrintE("Semiprimes:")
FOR i=1 TO 500
DO
IF IsSemiPrime(i) THEN
PrintI(i) Put(32)
FI
OD
RETURN
|
http://rosettacode.org/wiki/Set_of_real_numbers
|
Set of real numbers
|
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | a < x and x < b }
[a, b): {x | a ≤ x and x < b }
(a, b]: {x | a < x and x ≤ b }
Note that if a = b, of the four only [a, a] would be non-empty.
Task
Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
Provide methods for these common set operations (x is a real number; A and B are sets):
x ∈ A: determine if x is an element of A
example: 1 is in [1, 2), while 2, 3, ... are not.
A ∪ B: union of A and B, i.e. {x | x ∈ A or x ∈ B}
example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
A ∩ B: intersection of A and B, i.e. {x | x ∈ A and x ∈ B}
example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
A - B: difference between A and B, also written as A \ B, i.e. {x | x ∈ A and x ∉ B}
example: [0, 2) − (1, 3) = [0, 1]
Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
(0, 1] ∪ [0, 2)
[0, 2) ∩ (1, 2]
[0, 3) − (0, 1)
[0, 3) − [0, 1]
Implementation notes
'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
Optional work
Create a function to determine if a given set is empty (contains no element).
Define A = {x | 0 < x < 10 and |sin(π x²)| > 1/2 }, B = {x | 0 < x < 10 and |sin(π x)| > 1/2}, calculate the length of the real axis covered by the set A − B. Note that
|sin(π x)| > 1/2 is the same as n + 1/6 < x < n + 5/6 for all integers n; your program does not need to derive this by itself.
|
#EchoLisp
|
EchoLisp
|
(lib 'match) ;; reader-infix macros
(reader-infix '∈ )
(reader-infix '∩ )
(reader-infix '∪ )
(reader-infix '⊖ ) ;; set difference
(define-syntax-rule (∈ x a) (a x))
(define-syntax-rule (∩ a b) (lambda(x) (and ( a x) (b x))))
(define-syntax-rule (∪ a b) (lambda(x) (or ( a x) (b x))))
(define-syntax-rule (⊖ a b) (lambda(x) (and ( a x) (not (b x)))))
;; predicates to define common sets
(define (∅ x) #f) ;; the empty set predicate
(define (Z x) (integer? x))
(define (N x) (and (Z x) (>= x 0)))
(define (Q x) (rational? x))
(define (ℜ x) #t)
;; predicates to define convex sets
(define (⟦...⟧ a b)(lambda(x) (and (>= x a) (<= x b))))
(define (⟦...⟦ a b)(lambda(x) (and (>= x a) (< x b))))
(define (⟧...⟧ a b)(lambda(x) (and (> x a) (<= x b))))
(define (⟧...⟦ a b)(lambda(x) (and (> x a) (< x b))))
|
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
|
#ALGOL_68
|
ALGOL 68
|
# is prime PROC from the primality by trial division task #
MODE ISPRIMEINT = INT;
PROC is prime = ( ISPRIMEINT p )BOOL:
IF p <= 1 OR ( NOT ODD p AND p/= 2) THEN
FALSE
ELSE
BOOL prime := TRUE;
FOR i FROM 3 BY 2 TO ENTIER sqrt(p)
WHILE prime := p MOD i /= 0 DO SKIP OD;
prime
FI;
# end of code from the primality by trial division task #
# returns an array of n primes >= start #
PROC prime sequence = ( INT start, INT n )[]INT:
BEGIN
[ n ]INT seq;
INT prime count := 0;
FOR p FROM start WHILE prime count < n DO
IF is prime( p ) THEN
prime count +:= 1;
seq[ prime count ] := p
FI
OD;
seq
END; # prime sequence #
# find 20 primes >= 30 #
[]INT primes = prime sequence( 30, 20 );
print( ( "20 primes starting at 30: " ) );
FOR p FROM LWB primes TO UPB primes DO
print( ( " ", whole( primes[ p ], 0 ) ) )
OD;
print( ( newline ) )
|
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.
|
#ALGOL_68
|
ALGOL 68
|
PROC non square = (INT n)INT: n + ENTIER(0.5 + sqrt(n));
main: (
# first 22 values (as a list) has no squares: #
FOR i TO 22 DO
print((whole(non square(i),-3),space))
OD;
print(new line);
# The following check shows no squares up to one million: #
FOR i TO 1 000 000 DO
REAL j = sqrt(non square(i));
IF j = ENTIER j THEN
put(stand out, ("Error: number is a square:", j, new line));
stop
FI
OD
)
|
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.
|
#ALGOL_W
|
ALGOL W
|
begin
% check values of the function: f(n) = n + floor(1/2 + sqrt(n)) %
% are not squares %
integer procedure f ( integer value n ) ;
begin
n + entier( 0.5 + sqrt( n ) )
end f ;
logical noSquares;
% first 22 values of f %
for n := 1 until 22 do writeon( i_w := 1, f( n ) );
% check f(n) does not produce a square for n in 1..1 000 000 %
noSquares := true;
for n := 1 until 1000000 do begin
integer fn, rn;
fn := f( n );
rn := round( sqrt( fn ) );
if ( rn * rn ) = fn then begin
write( "Found square at: ", n );
noSquares := false
end if_fn_is_a_square
end for_n ;
if noSquares then write( "f(n) did not produce a square in 1 .. 1 000 000" )
else write( "f(n) produced a square" )
end.
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#ALGOL_68
|
ALGOL 68
|
# sets using associative arrays #
# include the associative array code for string keys and values #
PR read "aArray.a68" PR
# adds the elements of s to the set a, #
# the elements will have empty strings for values #
OP // = ( REF AARRAY a, []STRING s )REF AARRAY:
BEGIN
FOR s pos FROM LWB s TO UPB s DO
a // s[ s pos ] := ""
OD;
a
END # // # ;
# returns a set containing the elements of a that aren't in b #
OP - = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AARRAY result := INIT HEAP AARRAY;
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
IF NOT ( b CONTAINSKEY key OF e ) THEN
result // key OF e := value OF e
FI;
e := NEXT a
OD;
result
END # - # ;
# returns a set containing the elements of a and those of b, i.e. a UNION b #
PRIO U = 6;
OP U = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AARRAY result := INIT HEAP AARRAY;
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
result // key OF e := value OF e;
e := NEXT a
OD;
e := FIRST b;
WHILE e ISNT nil element DO
result // key OF e := value OF e;
e := NEXT b
OD;
result
END # U # ;
# returns a set containing the elements of a INTERSECTION b #
PRIO N = 6;
OP N = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AARRAY result := INIT HEAP AARRAY;
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
IF b CONTAINSKEY key OF e THEN
result // key OF e := value OF e
FI;
e := NEXT a
OD;
result
END # N # ;
# returns TRUE if all the elements of a are in b, FALSE otherwise #
OP <= = ( REF AARRAY a, REF AARRAY b )BOOL:
BEGIN
BOOL result := TRUE;
REF AAELEMENT e := FIRST a;
WHILE result AND ( e ISNT nil element ) DO
result := b CONTAINSKEY key OF e;
e := NEXT a
OD;
result
END # <= # ;
# returns TRUE if all the elements of a are in b #
# and all the elements of b are in a, FALSE otherwise #
OP = = ( REF AARRAY a, REF AARRAY b )BOOL: a <= b AND b <= a;
# returns NOT ( a = b ) #
OP /= = ( REF AARRAY a, REF AARRAY b )BOOL: NOT ( a = b );
# returns TRUE if all the elements of a are in b #
# but not all the elements of b are in a, FALSE otherwise #
OP < = ( REF AARRAY a, REF AARRAY b )BOOL: a <= b AND b /= a;
# prints the elements of a in no-particlar order #
PROC print set = ( REF AARRAY a )VOID:
BEGIN
print( ( "[" ) );
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
print( ( " ", key OF e ) );
e := NEXT a
OD;
print( ( " ]", newline ) )
END # print set # ;
# construct associative arrays for the task #
REF AARRAY gas giants := INIT LOC AARRAY;
REF AARRAY ice giants := INIT LOC AARRAY;
REF AARRAY rocky planets := INIT LOC AARRAY;
REF AARRAY inner planets := INIT LOC AARRAY;
REF AARRAY moonless planets := INIT LOC AARRAY;
gas giants // []STRING( "Jupiter", "Saturn" );
ice giants // []STRING( "Uranus", "Neptune" );
rocky planets // []STRING( "Mercury", "Venus", "Earth", "Mars" );
inner planets // []STRING( "Mercury", "Venus", "Earth", "Mars" );
moonless planets // []STRING( "Mercury", "Venus" );
print( ( "rocky planets : " ) );print set( rocky planets );
print( ( "inner planets : " ) );print set( inner planets );
print( ( "gas giants : " ) );print set( gas giants );
print( ( "ice giants : " ) );print set( ice giants );
print( ( "moonless planets: " ) );print set( moonless planets );
print( ( newline ) );
print( ( """Saturn"" is "
, IF gas giants CONTAINSKEY "Saturn" THEN "" ELSE " not" FI
, "in gas giants", newline
)
);
print( ( """Venus"" is "
, IF gas giants CONTAINSKEY "Venus" THEN "" ELSE "not " FI
, "in gas giants", newline
)
);
print( ( "gas giants UNION ice giants : " ) );
print set( gas giants U ice giants );
print( ( "moonless planets INTERSECTION rocky planets: " ) );
print set( moonless planets N rocky planets );
print( ( "rocky planets \ moonless planets : " ) );
print set( rocky planets - moonless planets );
print( ( "moonless planets <= rocky planets : "
, IF moonless planets <= rocky planets THEN "yes" ELSE "no" FI
, newline
)
);
print( ( "moonless planets = rocky planets : "
, IF moonless planets = rocky planets THEN "yes" ELSE "no" FI
, newline
)
);
print( ( "inner planets = rocky planets : "
, IF inner planets = rocky planets THEN "yes" ELSE "no" FI
, newline
)
);
print( ( "moonless planets < rocky planets : "
, IF moonless planets < rocky planets THEN "yes" ELSE "no" FI
, newline
)
);
# REF AARRAYs are mutable #
REF AARRAY all planets := inner planets U gas giants U ice giants;
print( ( "all planets : " ) );
print set( all planets );
print( ( "... after restoration of Pluto: " ) );
all planets // "Pluto";
print set( all planets )
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Groovy
|
Groovy
|
class Example {
def foo(value) {
"Invoked with '$value'"
}
}
def example = new Example()
def method = "foo"
def arg = "test value"
assert "Invoked with 'test value'" == example."$method"(arg)
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
x := foo() # create object
x.m1() # static call of m1 method
# two examples where the method string can be dynamically constructed ...
"foo_m1"(x) # ... need to know class name and method name to construct name
x.__m["m1"] # ... general method (better)
end
class foo(a,b,c) # define object
method m1(x)
end
end
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#Io
|
Io
|
Example := Object clone
Example foo := method(x, 42+x)
name := "foo"
Example clone perform(name,5) println // prints "47"
|
http://rosettacode.org/wiki/Send_an_unknown_method_call
|
Send an unknown method call
|
Task
Invoke an object method where the name of the method to be invoked can be generated at run time.
Related tasks
Respond to an unknown method call.
Runtime evaluation
|
#J
|
J
|
sum =: +/
prod =: */
count =: #
nameToDispatch =: 'sum' NB. pick a name already defined
". nameToDispatch,' 1 2 3'
6
nameToDispatch~ 1 2 3
6
nameToDispatch (128!:2) 1 2 3
6
nameToDispatch =: 'count' NB. pick another name
". nameToDispatch,' 1 2 3'
3
nameToDispatch~ 1 2 3
3
nameToDispatch (128!:2) 1 2 3
3
|
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
|
#Action.21
|
Action!
|
DEFINE MAX="1000"
PROC Main()
BYTE ARRAY t(MAX+1)
INT i,j,k,first
FOR i=0 TO MAX
DO
t(i)=1
OD
t(0)=0
t(1)=0
i=2 first=1
WHILE i<=MAX
DO
IF t(i)=1 THEN
IF first=0 THEN
Print(", ")
FI
PrintI(i)
FOR j=2*i TO MAX STEP i
DO
t(j)=0
OD
first=0
FI
i==+1
OD
RETURN
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#J
|
J
|
primoprim=: [: I. [: +./ 1 p: (1,_1) +/ */\@:p:@i.
|
http://rosettacode.org/wiki/Sequence_of_primorial_primes
|
Sequence of primorial primes
|
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.
Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.
Task
Generate and show here the first ten values of the sequence.
Optional extended task
Show the first twenty members of the series.
Notes
This task asks for the primorial indices that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers will be needed for intermediate results).
There is some confusion in the references, but for the purposes of this task the sequence begins with n = 1.
Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.
Related tasks
Primorial numbers
Factorial
See also
Primorial prime Wikipedia.
Primorial prime from The Prime Glossary.
Sequence A088411 from The On-Line Encyclopedia of Integer Sequences
|
#Java
|
Java
|
import java.math.BigInteger;
public class PrimorialPrimes {
final static int sieveLimit = 1550_000;
static boolean[] notPrime = sieve(sieveLimit);
public static void main(String[] args) {
int count = 0;
for (int i = 1; i < 1000_000 && count < 20; i++) {
BigInteger b = primorial(i);
if (b.add(BigInteger.ONE).isProbablePrime(1)
|| b.subtract(BigInteger.ONE).isProbablePrime(1)) {
System.out.printf("%d ", i);
count++;
}
}
}
static BigInteger primorial(int n) {
if (n == 0)
return BigInteger.ONE;
BigInteger result = BigInteger.ONE;
for (int i = 0; i < sieveLimit && n > 0; i++) {
if (notPrime[i])
continue;
result = result.multiply(BigInteger.valueOf(i));
n--;
}
return result;
}
public static boolean[] sieve(int limit) {
boolean[] composite = new boolean[limit];
composite[0] = composite[1] = true;
int max = (int) Math.sqrt(limit);
for (int n = 2; n <= max; n++) {
if (!composite[n]) {
for (int k = n * n; k < limit; k += n) {
composite[k] = true;
}
}
}
return composite;
}
}
|
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
|
Sequence: nth number with exactly n divisors
|
Calculate the sequence where each term an is the nth that has n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
See also
OEIS:A073916
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: smallest number with exactly n divisors
|
#Raku
|
Raku
|
sub div-count (\x) {
return 2 if x.is-prime;
+flat (1 .. x.sqrt.floor).map: -> \d {
unless x % d { my \y = x div d; y == d ?? y !! (y, d) }
}
}
my $limit = 20;
my @primes = grep { .is-prime }, 1..*;
@primes[$limit]; # prime the array. SCNR
put "First $limit terms of OEIS:A073916";
put (1..$limit).hyper(:2batch).map: -> $n {
($n > 4 and $n.is-prime) ??
exp($n - 1, @primes[$n - 1]) !!
do {
my $i = 0;
my $iterator = $n %% 2 ?? (1..*) !! (1..*).map: *²;
$iterator.first: {
next unless $n == .&div-count;
next unless ++$i == $n;
$_
}
}
};
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#J
|
J
|
consolidate=:4 :0/
b=. y 1&e.@e.&> x
(1,-.b)#(~.;x,b#y);y
)
|
http://rosettacode.org/wiki/Set_consolidation
|
Set consolidation
|
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
Example 1:
Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
Example 2:
Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
Example 3:
Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
Example 4:
The consolidation of the five sets:
{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
Is the two sets:
{A, C, B, D}, and {G, F, I, H, K}
See also
Connected component (graph theory)
Range consolidation
|
#Java
|
Java
|
import java.util.*;
public class SetConsolidation {
public static void main(String[] args) {
List<Set<Character>> h1 = hashSetList("AB", "CD");
System.out.println(consolidate(h1));
List<Set<Character>> h2 = hashSetList("AB", "BD");
System.out.println(consolidateR(h2));
List<Set<Character>> h3 = hashSetList("AB", "CD", "DB");
System.out.println(consolidate(h3));
List<Set<Character>> h4 = hashSetList("HIK", "AB", "CD", "DB", "FGH");
System.out.println(consolidateR(h4));
}
// iterative
private static <E> List<Set<E>>
consolidate(Collection<? extends Set<E>> sets) {
List<Set<E>> r = new ArrayList<>();
for (Set<E> s : sets) {
List<Set<E>> new_r = new ArrayList<>();
new_r.add(s);
for (Set<E> x : r) {
if (!Collections.disjoint(s, x)) {
s.addAll(x);
} else {
new_r.add(x);
}
}
r = new_r;
}
return r;
}
// recursive
private static <E> List<Set<E>> consolidateR(List<Set<E>> sets) {
if (sets.size() < 2)
return sets;
List<Set<E>> r = new ArrayList<>();
r.add(sets.get(0));
for (Set<E> x : consolidateR(sets.subList(1, sets.size()))) {
if (!Collections.disjoint(r.get(0), x)) {
r.get(0).addAll(x);
} else {
r.add(x);
}
}
return r;
}
private static List<Set<Character>> hashSetList(String... set) {
List<Set<Character>> r = new ArrayList<>();
for (int i = 0; i < set.length; i++) {
r.add(new HashSet<Character>());
for (int j = 0; j < set[i].length(); j++)
r.get(i).add(set[i].charAt(j));
}
return r;
}
}
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Maple
|
Maple
|
with(NumberTheory):
countDivisors := proc(x::integer)
return numelems(Divisors(x));
end proc:
sequenceValue := proc(x::integer)
local count:
for count from 1 to infinity while not countDivisors(count) = x do end:
return count;
end proc:
seq(sequenceValue(number), number = 1..15);
|
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
|
Sequence: smallest number with exactly n divisors
|
Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly n divisors
See also
OEIS:A005179
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
Take[SplitBy[SortBy[{DivisorSigma[0, #], #} & /@ Range[100000], First], First][[All, 1]], 15] // Grid
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Perl
|
Perl
|
#!/usr/bin/perl
use strict ;
use warnings ;
use Digest::SHA qw( sha256_hex ) ;
my $digest = sha256_hex my $phrase = "Rosetta code" ;
print "SHA-256('$phrase'): $digest\n" ;
|
http://rosettacode.org/wiki/SHA-256
|
SHA-256
|
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
|
#Phix
|
Phix
|
include builtins\sha256.e
function asHex(string s)
string res = ""
for i=1 to length(s) do
res &= sprintf("%02X",s[i])
end for
return res
end function
?asHex(sha256("Rosetta code"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.