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/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:
*
* *
* *
* * * *
* *
* * * *
... | #Ursala | Ursala | #import nat
triangle = ~&a^?\<<&>>! ^|RNSiDlrTSPxSxNiCK9xSx4NiCSplrTSPT/~& predecessor |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Racket | Racket |
#lang racket
(define (carpet n)
(if (zero? n)
'("#")
(let* ([prev (carpet (sub1 n))]
[spaces (regexp-replace* #rx"#" (car prev) " ")])
(append (map (λ(x) (~a x x x)) prev)
(map (λ(x) (~a x spaces x)) prev)
(map (λ(x) (~a x x x)) prev)))))
(for-each displayln (c... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Haskell | Haskell | import qualified Data.Set as S
semordnilaps
:: (Ord a, Foldable t)
=> t [a] -> [[a]]
semordnilaps =
let f x (s, w)
| S.member (reverse x) s = (s, x : w)
| otherwise = (S.insert x s, w)
in snd . foldr f (S.empty, [])
main :: IO ()
main = do
s <- readFile "unixdict.txt"
let l = semordnilap... |
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 f... | #SQL_PL | SQL PL |
UPDATE DB CFG FOR myDb USING SMTP_SERVER 'smtp.ibm.com';
CALL UTL_MAIL.SEND ('senderAccount@myDomain.com','recipientAccount@yourDomain.com', 'copy@anotherDomain.com', NULL, 'The subject of the message', 'The content of the message');
|
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 f... | #Tcl | Tcl | package require smtp
package require mime
package require tls
set gmailUser *******
set gmailPass hunter2; # Hello, bash.org!
proc send_simple_message {recipient subject body} {
global gmailUser gmailPass
# Build the message
set token [mime::initialize -canonical text/plain -string $body]
mime::se... |
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 Arecib... | #Lua | Lua |
function semiprime (n)
local divisor, count = 2, 0
while count < 3 and n ~= 1 do
if n % divisor == 0 then
n = n / divisor
count = count + 1
else
divisor = divisor + 1
end
end
return count == 2
end
for n = 1675, 1680 do
print(n, semiprime(n))
end
|
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #Maple | Maple | SemiPrimes := proc( n )
local fact;
fact := NumberTheory:-Divisors( n ) minus {1, n};
if numelems( fact ) in {1,2} and not( member( 'false', isprime ~ ( fact ) ) ) then
return n;
else
return NULL;
end if;
end proc:
{ seq( SemiPrimes( i ), i = 1..100 ) }; |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #D | D | import std.stdio, std.algorithm, std.string, std.numeric, std.ascii;
char checksum(in char[] sedol) pure @safe /*@nogc*/
in {
assert(sedol.length == 6);
foreach (immutable c; sedol)
assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c)));
} out (result) {
assert(result.isDigit);
} body {
stati... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #LiveCode | LiveCode | function selfDescNumber n
local tSelfD, tLen
put len(n) into tLen
repeat with x = 0 to (tLen - 1)
put n into nCopy
replace x with empty in nCopy
put char (x + 1) of n = (tLen - len(nCopy)) into tSelfD
if not tSelfD then exit repeat
end repeat
return tSelfD
end selfDe... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #Logo | Logo | TO XX
BT
MAKE "AA (ARRAY 10 0)
MAKE "BB (ARRAY 10 0)
FOR [Z 0 9][SETITEM :Z :AA "0 SETITEM :Z :BB "0 ]
FOR [A 1 50000][
MAKE "B COUNT :A
MAKE "Y 0
MAKE "X 0
MAKE "R 0
MAKE "J 0
MAKE "K 0
FOR [C 1 :B][MAKE "D ITEM :C :A
SETITEM :C - 1 :AA :D
MAKE "X ITEM :D :BB ... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[primeq]
primeq[1]:=False
primeq[2]:=True
primeq[n_Integer?(GreaterThan[2])]:=Module[{},
AllTrue[Range[2,Sqrt[n]+1],Mod[n,#]!=0&]
]
Select[Range[100],primeq] |
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... | #MATLAB | MATLAB | function primeList = sieveOfEratosthenes(lastNumber)
list = (2:lastNumber); %Construct list of numbers
primeList = []; %Preallocate prime list
while( list(1)^2 <lastNumber )
primeList = [primeList list(1)]; %add prime to the prime list
list( mod(list,list(1))==0 ) = []; %filter out all... |
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.
| #GAP | GAP | # Here we use generators : the given formula doesn't need one, but the alternate
# non-squares function is better done with a generator.
# The formula is implemented with exact floor(sqrt(n)), so we use
# a trick: multiply by 100 to get the first decimal digit of the
# square root of n, then add 5 (that's 1/2 multipl... |
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.
| #Go | Go | package main
import (
"fmt"
"math"
)
func remarkable(n int) int {
return n + int(.5+math.Sqrt(float64(n)))
}
func main() {
// task 1
fmt.Println(" n r(n)")
fmt.Println("--- ---")
for n := 1; n <= 22; n++ {
fmt.Printf("%3d %3d\n", n, remarkable(n))
}
// task 2
... |
http://rosettacode.org/wiki/Set | Set |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an... | #Forth | Forth | include FMS-SI.f
include FMS-SILib.f
: union {: a b -- c :}
begin
b each:
while dup
a indexOf: if 2drop else a add: then
repeat b <free a dup sort: ; ok
i{ 2 5 4 3 } i{ 5 6 7 } union p: i{ 2 3 4 5 6 7 } ok
: free2 ( a b -- ) <free <free ;
: intersect {: a b | c -- c :}
heap> 1-array2 to c
be... |
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... | #Bracmat | Bracmat | ( ( eratosthenes
= n j i
. !arg:?n
& 1:?i
& whl
' ( (1+!i:?i)^2:~>!n:?j
& ( !!i
| whl
' ( !j:~>!n
& nonprime:?!j
& !j+!i:?j
)
)
)
& 1:?i
& whl
' ( 1+!i:~>!n:?... |
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
Bioin... | #REXX | REXX | /*REXX program displays an ASCII table of characters (within a 16x16 indexed grid).*/
parse upper version !ver . /*some REXXes can't display '1b'x glyph*/
!pcRexx= 'REXX/PERSONAL'==!ver | "REXX/PC"==!ver /*is this PC/REXX or REXX/Personal? */
func= ' nul soh stx etx eot enq ack ... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #VBA | VBA | Sub sierpinski(n As Integer)
Dim lim As Integer: lim = 2 ^ n - 1
For y = lim To 0 Step -1
Debug.Print String$(y, " ")
For x = 0 To lim - y
Debug.Print IIf(x And y, " ", "# ");
Next
Debug.Print
Next y
End Sub
Public Sub main()
Dim i As Integer
For i = 1 To... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Raku | Raku | sub carpet
{
(['#'], -> @c {
[
|@c.map({$_ x 3}),
|@c.map({ $_ ~ $_.trans('#'=>' ') ~ $_}),
|@c.map({$_ x 3})
]
} ... *).map: { .join("\n") };
}
say carpet[3];
# Same as above, structured as an array bound to a sequence, with a separate sub for clarity.
sub weave ( @... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Icon_and_Unicon | Icon and Unicon | procedure main(a)
words := set()
found := 0
every word := map(!&input) do {
if member(words, reverse(word)) then {
if (found +:= 1) <= 5 then write("\t",reverse(word),"/",word)
}
else insert(words, word)
}
write("\nFound ",found," semordnilap words")
end
|
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #J | J | isSemordnilap=: |.&.> (~: *. e.) ]
unixdict=: <;._2 freads 'unixdict.txt'
#semordnilaps=: ~. /:~"1 (,. |.&.>) (#~ isSemordnilap) unixdict
158 |
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 f... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
system=SYSTEM ()
IF (system=="WIN") THEN
SET to="name@domain.org"
SET cc="name@domain.net"
subject="test"
text=*
DATA how are you?
status = SEND_MAIL (to,cc,subject,text,-)
ENDIF
|
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 f... | #TXR | TXR | #!/usr/bin/txr
@(next :args)
@(cases)
@TO
@SUBJ
@ (maybe)
@CC
@ (or)
@ (bind CC "")
@ (end)
@(or)
@ (throw error "must specify at least To and Subject")
@(end)
@(next *stdin*)
@(collect)
@BODY
@(end)
@(output (open-command `mail -s "@SUBJ" -a CC: "@CC" "@TO"` "w"))
@(repeat)
@BODY
@(end)
.
@(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 f... | #VBA | VBA | Option Explicit
Const olMailItem = 0
Sub SendMail(MsgTo As String, MsgTitle As String, MsgBody As String)
Dim OutlookApp As Object, Msg As Object
Set OutlookApp = CreateObject("Outlook.Application")
Set Msg = OutlookApp.CreateItem(olMailItem)
With Msg
.To = MsgTo
.Subject = MsgTitle
... |
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 Arecib... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | semiPrimeQ[n_Integer] := Module[{factors, numfactors},
factors = FactorInteger[n] // Transpose;
numfactors = factors[[2]] // Total ;
numfactors == 2
] |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #MiniScript | MiniScript | isSemiprime = function(num)
divisor = 2
primes = 0
while primes < 3 and num != 1
if num % divisor == 0 then
num = num / divisor;
primes = primes + 1
else
divisor = divisor + 1
end if
end while
return primes == 2
end function
print "Semipr... |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Delphi | Delphi | program Sedol;
{$APPTYPE CONSOLE}
uses
SysUtils;
const
SEDOL_CHR_COUNT = 6;
DIGITS = ['0'..'9'];
LETTERS = ['A'..'Z'];
VOWELS = ['A', 'E', 'I', 'O', 'U'];
ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS;
WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9);
LETTER_OFFSET = 9;
fun... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #Lua | Lua | function Is_self_describing( n )
local s = tostring( n )
local t = {}
for i = 0, 9 do t[i] = 0 end
for i = 1, s:len() do
local idx = tonumber( s:sub(i,i) )
t[idx] = t[idx] + 1
end
for i = 1, s:len() do
if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end
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... | #Nim | Nim | import strformat
func isPrime(n: int): bool =
if n < 2: return false
if n mod 2 == 0: return n == 2
if n mod 3 == 0: return n == 3
var d = 5
while d * d <= n:
if n mod d == 0: return false
inc d, 2
if n mod d == 0: return false
inc d, 4
true
var count = 1
write(stdout, " 2")
for i in ... |
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... | #Oforth | Oforth | : primeSeq(n) n seq filter(#isPrime) ; |
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.
| #Groovy | Groovy | def nonSquare = { long n -> n + ((1/2 + n**0.5) as long) } |
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... | #FreeBASIC | FreeBASIC | function is_in( N as integer, S() as integer ) as boolean
'test if the value N is in the set S
for i as integer = 0 to ubound(S)
if N=S(i) then return true
next i
return false
end function
sub add_to_set( N as integer, S() as integer )
'adds the element N to the set S
if is_in( N, S() ... |
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... | #C | C | #include <stdlib.h>
#include <math.h>
char*
eratosthenes(int n, int *c)
{
char* sieve;
int i, j, m;
if(n < 2)
return NULL;
*c = n-1; /* primes count */
m = (int) sqrt((double) n);
/* calloc initializes to zero */
sieve = calloc(n+1,sizeof(char));
sieve[0] = 1;
sieve[1] = 1;
for(i = 2; i <= m; i+... |
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
Bioin... | #Ring | Ring |
# Project : Show Ascii table
load "guilib.ring"
load "stdlib.ring"
decarr = newlist(16,6)
ascarr = newlist(16,6)
new qapp
{
win1 = new qwidget() {
setwindowtitle("Show Ascii table")
setgeometry(100,100,800,600)
for n = 1 to 16
... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #VBScript | VBScript |
Sub triangle(o)
n = 2 ^ o
Dim line()
ReDim line(2*n)
line(n) = "*"
i = 0
Do While i < n
WScript.StdOut.WriteLine Join(line,"")
u = "*"
j = n - i
Do While j < (n+i+1)
If line(j-1) = line(j+1) Then
t = " "
Else
t = "*"
End If
line(j-1) = u
u = t
j = j + 1
Loop
line(n+i) = t
... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Relation | Relation |
function incarpet(x,y)
set a = x
set b = y
while floor(a)>0 and floor(b)>0
if floor(a mod 3) = 1 and floor(b mod 3) = 1
set a = -1
set b = -1
else
set a = a / 3
set b = b / 3
end if
end while
if a < 0
set result = "_"
else
set result = "#"
end if
end function
program carpet(n)
set d = pow(3,n)
set y = 0
while y < ... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Java | Java | import java.nio.file.*;
import java.util.*;
public class Semordnilap {
public static void main(String[] args) throws Exception {
List<String> lst = Files.readAllLines(Paths.get("unixdict.txt"));
Set<String> seen = new HashSet<>();
int count = 0;
for (String w : lst) {
... |
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 f... | #VBScript | VBScript |
Function send_mail(from,recipient,cc,subject,message)
With CreateObject("CDO.Message")
.From = from
.To = recipient
.CC = cc
.Subject = subject
.Textbody = message
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Configuration.Fields.Item _
("http://s... |
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 f... | #Wren | Wren | /* send_email.wren */
foreign class Authority {
construct plainAuth(identity, username, password, host) {}
}
class SMTP {
foreign static sendMail(address, auth, from, to, msg)
}
class Message {
static check(host, user, pass) {
if (host == "") Fiber.abort("Bad host")
if (user == "") Fib... |
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 Arecib... | #NewLisp | NewLisp |
;;; Practically identical to the EchoLisp solution
(define (semiprime? n)
(= (length (factor n)) 2))
;
;;; Example (sadly factor doesn't accept bigints)
(println (filter semiprime? (sequence 2 100)))
(setq x 9223372036854775807)
(while (not (semiprime? x)) (-- x))
(println "Biggest semiprime reachable: " x " = " ((f... |
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 Arecib... | #Nim | Nim | proc isSemiPrime(k: int): bool =
var
i = 2
count = 0
x = k
while i <= x and count < 3:
if x mod i == 0:
x = x div i
inc count
else:
inc i
result = count == 2
for k in 1675..1680:
echo k, (if k.isSemiPrime(): " is" else: " isn’t"), " semi-prime" |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #E | E | def weights := [1,3,1,7,3,9]
def Digit := ('0'..'9')
def Letter := ('B'..'D'|'F'..'H'|'J'..'N'|'P'..'T'|'V'..'Z')
def sedolCharValue(c) {
switch (c) {
match digit :Digit { return digit - '0' }
match letter :Letter {
return letter - 'A'
}
}
}
def checksum(sedol :String) {
require(sedol.size() =... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | isSelfDescribing[n_Integer] := (RotateRight[DigitCount[n]] == PadRight[IntegerDigits[n], 10]) |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #MATLAB_.2F_Octave | MATLAB / Octave | function z = isSelfDescribing(n)
s = int2str(n)-'0'; % convert to vector of digits
y = hist(s,0:9);
z = all(y(1:length(s))==s);
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... | #PARI.2FGP | PARI/GP | trial(n)={
if(n < 4, return(n > 1)); /* Handle negatives */
forprime(p=2,sqrt(n),
if(n%p == 0, return(0))
);
1
};
select(trial, [1..100]) |
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division | Sequence of primes by trial division | Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by... | #Pascal | Pascal |
program PrimeRng;
uses
primTrial;
var
Range : ptPrimeList;
i : integer;
Begin
Range := PrimeRange(1000*1000*1000,1000*1000*1000+100);
For i := Low(Range) to High(Range) do
write(Range[i]:12);
writeln;
end. |
http://rosettacode.org/wiki/Sequence_of_non-squares | Sequence of non-squares | Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
| #Haskell | Haskell | nonsqr :: Integral a => a -> a
nonsqr n = n + round (sqrt (fromIntegral n)) |
http://rosettacode.org/wiki/Sequence_of_non-squares | Sequence of non-squares | Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
| #HicEst | HicEst | REAL :: n=22, nonSqr(n)
nonSqr = $ + FLOOR(0.5 + $^0.5)
WRITE() nonSqr
squares_found = 0
DO i = 1, 1E6
non2 = i + FLOOR(0.5 + i^0.5)
root = FLOOR( non2^0.5 )
squares_found = squares_found + (non2 == root*root)
ENDDO
WRITE(Name) squares_found
END |
http://rosettacode.org/wiki/Set | Set |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an... | #Frink | Frink |
a = new set[1, 2]
b = toSet[[2,3]] // Construct a set from an array
a.contains[2] // Element test (returns true)
union[a,b]
intersection[a,b]
setDifference[a,b]
isSubset[a,b] // Returns true if a is a subset of b
a==b // set equality test
|
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... | #C.23 | C# | using System;
using System.Collections;
using System.Collections.Generic;
namespace SieveOfEratosthenes
{
class Program
{
static void Main(string[] args)
{
int maxprime = int.Parse(args[0]);
var primelist = GetAllPrimesLessThan(maxprime);
foreach (int prime ... |
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
Bioin... | #Ruby | Ruby | chars = (32..127).map do |ord|
k = case ord
when 32 then "␠"
when 127 then "␡"
else ord.chr
end
"#{ord.to_s.ljust(3)}: #{k}"
end
chars.each_slice(chars.size/6).to_a.transpose.each{|s| puts s.join(" ")} |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Vedit_macro_language | Vedit macro language | #3 = 16 // size (height) of the triangle
Buf_Switch(Buf_Free) // Open a new buffer for output
Ins_Char(' ', COUNT, #3*2+2) // fill first line with spaces
Ins_Newline
Line(-1) Goto_Col(#3)
Ins_Char('*', OVERWRITE) // the top of triangle
for (#10=0; #10 < #3-1; #10++) {
BOL Reg_Copy(9,1) Reg_Ins(9) // dupl... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #REXX | REXX | /*REXX program draws any order Sierpinski carpet (order 20 would be ≈ 3.4Gx3.4G carpet).*/
parse arg N char . /*get the order of the carpet. */
if N=='' | N=="," then N= 3 /*if none specified, then assume 3. */
if char=='' then char= "*" ... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #JavaScript | JavaScript | #!/usr/bin/env node
var fs = require('fs');
var sys = require('sys');
var dictFile = process.argv[2] || "unixdict.txt";
var dict = {};
fs.readFileSync(dictFile)
.toString()
.split('\n')
.forEach(function(word) {
dict[word] = word.split("").reverse().join("");
});
function isSemordnilap(word) { return... |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #Objeck | Objeck |
class SemiPrime {
function : Main(args : String[]) ~ Nil {
for(i := 0; i < 100; i+=1;) {
if(SemiPrime(i)) {
"{$i} "->Print();
};
};
IO.Console->PrintLine();
}
function : native : SemiPrime(n : Int) ~ Bool {
nf := 0;
for(i := 2; i <= n; i+=1;) {
while(n%i = 0) {
... |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Elixir | Elixir | defmodule SEDOL do
@sedol_char "0123456789BCDFGHJKLMNPQRSTVWXYZ" |> String.codepoints
@sedolweight [1,3,1,7,3,9]
defp char2value(c) do
unless c in @sedol_char, do: raise ArgumentError, "No vowels"
String.to_integer(c,36)
end
def checksum(sedol) do
if String.length(sedol) != length(@sedolweig... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #MiniScript | MiniScript | numbers = [12, 1210, 1300, 2020, 21200, 5]
occurrences = function(test, values)
count = 0
for i in values
if i.val == test then count = count + 1
end for
return count
end function
for number in numbers
check = "" + number
digits = check.values
describing = true
for digit in d... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #Modula-2 | Modula-2 |
MODULE SelfDescribingNumber;
FROM WholeStr IMPORT
CardToStr;
FROM STextIO IMPORT
WriteString, WriteLn;
FROM SWholeIO IMPORT
WriteCard;
PROCEDURE Check(Number: CARDINAL): BOOLEAN;
VAR
I, D: CARDINAL;
A: ARRAY [0 .. 9] OF CHAR;
Count, W: ARRAY [0 .. 9] OF CARDINAL;
Result: BOOLEAN;
BEGIN
CardToStr(N... |
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division | Sequence of primes by trial division | Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by... | #Perl | Perl | sub isprime {
my $n = shift;
return ($n >= 2) if $n < 4;
return unless $n % 2 && $n % 3;
my $sqrtn = int(sqrt($n));
for (my $i = 5; $i <= $sqrtn; $i += 6) {
return unless $n % $i && $n % ($i+2);
}
1;
}
print join(" ", grep { isprime($_) } 0 .. 100 ), "\n";
print join(" ", grep { isprime($_) } 123456... |
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.
| #Icon_and_Unicon | Icon and Unicon | link numbers
procedure main()
every n := 1 to 22 do
write("nsq(",n,") := ",nsq(n))
every x := sqrt(nsq(n := 1 to 1000000)) do
if x = floor(x)^2 then write("nsq(",n,") = ",x," is a square.")
write("finished.")
end
procedure nsq(n) # return non-squares
return n + floor(0.5 + sqrt(n))
end |
http://rosettacode.org/wiki/Set | Set |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an... | #FunL | FunL | A = {1, 2, 3}
B = {3, 4, 5}
C = {1, 2, 3, 4, 5}
D = {2, 1, 3}
println( '2 is in A: ' + (2 in A) )
println( '4 is in A: ' + (4 in A) )
println( 'A union B: ' + A.union(B) )
println( 'A intersect B: ' + A.intersect(B) )
println( 'A difference B: ' + A.diff(B) )
println( 'A subset of B: ' + A.subsetOf(B) )
println( 'A s... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <algorithm>
#include <vector>
// requires Iterator satisfies RandomAccessIterator
template <typename Iterator>
size_t prime_sieve(Iterator start, Iterator end)
{
if (start == end) return 0;
// clear the container with 0
std::fill(start, end, 0);
// mark composites with 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
Bioin... | #Rust | Rust | fn main() {
for i in 0u8..16 {
for j in ((32+i)..128).step_by(16) {
let k = (j as char).to_string();
print!("{:3} : {:<3} ", j, match j {
32 => "Spc",
127 => "Del",
_ => &k,
});
}
println!();
}
} |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Wren | Wren | var size = 1 << 4
for (y in size-1..0) {
System.write(" " * y)
for (x in 0...size-y) System.write((x&y != 0) ? " " : "* ")
System.print()
} |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Ring | Ring |
load "guilib.ring"
new qapp
{
win1 = new qwidget() {
etwindowtitle("drawing using qpainter")
setgeometry(100,100,500,500)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #jq | jq |
# Produce a stream
def report:
split("\n") as $list
# construct the dictionary:
| (reduce $list[] as $entry ({}; . + {($entry): 1})) as $dict
# construct the list of semordnilaps:
| $list[]
| select( (explode|reverse|implode) as $rev
| (. < $rev and $dict[$rev]) );
[report] | (.[0:5][], "le... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Julia | Julia | raw = readdlm("unixdict.txt",String)[:]
inter = intersect(raw,map(reverse,raw)) #find the matching strings/revstrings
res = String[b == 1 && a != reverse(a) && a < reverse(a) ? a : reverse(a) for a in inter, b in 1:2] #create pairs
res = res[res[:,1] .!= res[:,2],:] #get rid of duplicates, palindromes |
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 Arecib... | #Oforth | Oforth | func: semiprime(n)
| i |
0 2 n sqrt asInteger for: i [ while(n i /mod swap 0 &=) [ ->n 1+ ] drop ]
n 1 > ifTrue: [ 1+ ] 2 == ; |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #PARI.2FGP | PARI/GP | issemi(n)=bigomega(n)==2 |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Excel | Excel | SEDOLCHECKSUM
=LAMBDA(s,
IF(6 = LEN(s),
LET(
cs, MID(s, SEQUENCE(1, 6, 1, 1), 1),
isVowel, LAMBDA(c,
ELEM(c)({"A","E","I","O","U"})
),
sedolValue, LAMBDA(c,
LET(
ic, CODE(c),
IF(65 > ic,
... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #Nim | Nim | import algorithm, sequtils, std/monotimes, times
type Digit = 0..9
var digits = newSeqOfCap[Digit](10)
proc getDigits(n: Positive) =
digits.setLen(0)
var n = n.int
while n != 0:
digits.add n mod 10
n = n div 10
digits.reverse()
proc isSelfDescribing(n: Natural): bool =
n.getDigits()
for i, d... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #ooRexx | ooRexx |
-- REXX program to check if a number (base 10) is self-describing.
parse arg x y .
if x=='' then exit
if y=='' then y=x
-- 10 digits is the maximum size number that works here, so cap it
numeric digits 10
y=min(y, 9999999999)
loop number = x to y
loop i = 1 to number~length
digit = number~subchar(i)
-... |
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division | Sequence of primes by trial division | Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by... | #Phix | Phix | function is_prime_by_trial_division(integer n)
if n<2 then return 0 end if
if n=2 then return 1 end if
if remainder(n,2)=0 then return 0 end if
for i=3 to floor(sqrt(n)) by 2 do
if remainder(n,i)=0 then
return 0
end if
end for
return 1
end function
?filter(tagset(32),... |
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... | #PicoLisp | PicoLisp | (de prime? (N)
(or
(= N 2)
(and
(> N 1)
(bit? 1 N)
(let S (sqrt N)
(for (D 3 T (+ D 2))
(T (> D S) T)
(T (=0 (% N D)) NIL) ) ) ) ) )
(de primeseq (A B)
(filter prime? (range A B)) )
(println (primeseq 50 99)) |
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.
| #IDL | IDL | n = lindgen(1000000)+1 ; Take a million numbers
f = n+floor(.5+sqrt(n)) ; Apply formula
print,f[0:21] ; Output first 22
print,where(sqrt(f) eq fix(sqrt(f))) ; Test for squares |
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.
| #J | J | rf=: + 0.5 <.@+ %: NB. Remarkable formula
rf 1+i.22 NB. Results from 1 to 22
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
+/ (rf e. *:) 1+i.1e6 NB. Number of square RFs <= 1e6
0 |
http://rosettacode.org/wiki/Set | Set |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an... | #FutureBasic | FutureBasic | include "NSLog.incl"
local fn DoIt
// create
CFSetRef s1 = fn SetWithArray( @[@"a",@"b",@"c",@"d",@"e"] )
CFSetRef s2 = fn SetWithArray( @[@"b",@"c",@"d",@"e",@"f",@"h"] )
CFSetRef s3 = fn SetWithArray( @[@"b",@"c",@"d"] )
CFSetRef s4 = fn SetWithArray( @[@"b",@"c",@"d"] )
NSLog(@"s1: %@",s1)
NSLog(@"s2... |
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... | #Chapel | Chapel | // yield prime and remove all multiples of it from children sieves
iter sieve(prime):int {
yield prime;
var last = prime;
label candidates for candidate in sieve(prime+1) do {
for composite in last..candidate by prime do {
// candidate is a multiple ... |
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
Bioin... | #Scala | Scala | object AsciiTable extends App {
val (strtCharVal, lastCharVal, nColumns) = (' '.toByte, '\u007F'.toByte, 6)
require(nColumns % 2 == 0, "Number of columns must be even.")
val nChars = lastCharVal - strtCharVal + 1
val step = nChars / nColumns
val threshold = strtCharVal + (nColumns - 1) * step
def indexG... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #X86_Assembly | X86 Assembly | .model tiny
.code
.486
org 100h
start: xor ebx, ebx ;S1:= 0
mov edx, 8000h ;S2:= $8000
mov cx, 16 ;for I:= Size downto 1
tri10: mov ebx, edx ; S1:= S2
tri15: test edx, edx ; while S2#0
je tri20
... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Ruby | Ruby | def sierpinski_carpet(n)
carpet = ["#"]
n.times do
carpet = carpet.collect {|x| x + x + x} +
carpet.collect {|x| x + x.tr("#"," ") + x} +
carpet.collect {|x| x + x + x}
end
carpet
end
4.times{|i| puts "\nN=#{i}", sierpinski_carpet(i)} |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Kotlin | Kotlin | // version 1.2.0
import java.io.File
fun main(args: Array<String>) {
val words = File("unixdict.txt").readLines().toSet()
val pairs = words.map { Pair(it, it.reversed()) }
.filter { it.first < it.second && it.second in words } // avoid dupes+palindromes, find matches
println("Found ${pairs.s... |
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 Arecib... | #Pascal | Pascal | program SemiPrime;
{$IFDEF FPC}
{$Mode objfpc}// compiler switch to use result
{$ELSE}
{$APPTYPE CONSOLE} // for Delphi
{$ENDIF}
uses
primTrial;
function isSemiprime(n: longWord;doWrite:boolean): boolean;
var
fac1 : LongWord;
begin
//a simple isAlmostPrime(n,2) would do without output;
fac1 := SmallFactor... |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #F.23 | F# | open System
let Inputs = ["710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL"
"557910"; "B0YBKR"; "585284"; "B0YBKT"; "B00030"]
let Vowels = set ['A'; 'E'; 'I'; 'O'; 'U']
let Weights = [1; 3; 1; 7; 3; 9; 1]
let inline isVowel c = Vowels.Contains (Char.ToUpper c)
let char2value c =
if C... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #PARI.2FGP | PARI/GP | S=[1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000];
isself(n)=vecsearch(S,n) |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #Pascal | Pascal | Program SelfDescribingNumber;
uses
SysUtils;
function check(number: longint): boolean;
var
i, d: integer;
a: string;
count, w : array [0..9] of integer;
begin
a := intToStr(number);
for i := 0 to 9 do
begin
count[i] := 0;
w[i] := 0;
end;
for i := 1 to length(a) do... |
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... | #PowerShell | PowerShell |
function eratosthenes ($n) {
if($n -ge 1){
$prime = @(1..($n+1) | foreach{$true})
$prime[1] = $false
$m = [Math]::Floor([Math]::Sqrt($n))
for($i = 2; $i -le $m; $i++) {
if($prime[$i]) {
for($j = $i*$i; $j -le $n; $j += $i) {
$prime[$j... |
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.
| #Java | Java | public class SeqNonSquares {
public static int nonsqr(int n) {
return n + (int)Math.round(Math.sqrt(n));
}
public static void main(String[] args) {
// first 22 values (as a list) has no squares:
for (int i = 1; i < 23; i++)
System.out.print(nonsqr(i) + " ");
Sys... |
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... | #Go | Go | package main
import "fmt"
// Define set as a type to hold a set of complex numbers. A type
// could be defined similarly to hold other types of elements. A common
// variation is to make a map of interface{} to represent a set of
// mixed types. Also here the map value is a bool. By always storing
// true, the ... |
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... | #Clojure | Clojure | (defn primes< [n]
(remove (set (mapcat #(range (* % %) n %)
(range 2 (Math/sqrt n))))
(range 2 n))) |
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
Bioin... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: row is 0;
var integer: column is 0;
var integer: number is 0;
begin
for row range 0 to 15 do
for column range 0 to 5 do
number := 32 + 16 * column + row;
write(number lpad 3 <& " : ");
case number o... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #XPL0 | XPL0 | code ChOut=8, CrLf=9;
def Order=4, Size=1<<Order;
int S1, S2, I;
[S1:= 0; S2:= $8000;
for I:= 0 to Size-1 do
[S1:= S2;
while S2 do
[ChOut(0, if S2&1 then ^* else ^ ); S2:= S2>>1];
CrLf(0);
S2:= S2 xor S1<<1;
S2:= S2 xor S1>>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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Rust | Rust | fn main() {
for i in 0..4 {
println!("\nN={}", i);
println!("{}", sierpinski_carpet(i));
}
}
fn sierpinski_carpet(n: u32) -> String {
let mut carpet = vec!["#".to_string()];
for _ in 0..n {
let mut top: Vec<_> = carpet.iter().map(|x| x.repeat(3)).collect();
let middle: ... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Ksh | Ksh |
#!/bin/ksh
# Semordnilap
# # Variables:
#
integer MIN_WORD_LEN=1 TRUE=1 FALSE=0
dict='/home/ostrande/prj/roscode/unixdict.txt'
integer i j=0 k=0
typeset -A word
# # Functions:
#
# # Function _flipit(string) - return flipped string
#
function _flipit {
typeset _buf ; _buf="$1"
typeset _tmp ; unset _tmp
... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Lasso | Lasso | local(
words = string(include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt')) -> split('\n'),
semordnilaps = array,
found_size,
example,
haveexamples = false,
examples = array
)
#words -> removeall('')
with word in #words do {
local(reversed = string(#word) -> reverse&)
if(not(#word == #reversed... |
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 Arecib... | #Perl | Perl | use ntheory "is_semiprime";
for ([1..100], [1675..1681], [2,4,99,100,1679,5030,32768,1234567,9876543,900660121]) {
print join(" ",grep { is_semiprime($_) } @$_),"\n";
} |
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 Arecib... | #Phix | Phix | function semiprime(integer n)
return length(prime_factors(n,true))==2
end function
pp(filter(tagset(100)&tagset(1680,1675),semiprime),{pp_IntCh,false})
|
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Factor | Factor | USING: combinators combinators.short-circuit formatting io kernel
math math.parser regexp sequences unicode ;
IN: rosetta-code.sedols
<PRIVATE
CONSTANT: input {
"710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL"
"557910" "B0YBKR" "585284" "B0YBKT" "B00030" "AEIOUA"
"123" "" "B_7K90"
}
CONS... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #Perl | Perl | sub is_selfdesc
{
local $_ = shift;
my @b = (0) x length;
$b[$_]++ for my @a = split //;
return "@a" eq "@b";
}
# check all numbers from 0 to 100k plus two 'big' ones
for (0 .. 100000, 3211000, 42101000) {
print "$_\n" if is_selfdesc($_);
} |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #Phix | Phix | with javascript_semantics
function self_desc(integer i)
sequence digits = repeat(0,10),
counts = repeat(0,10)
integer n = 0, digit
while 1 do
digit := mod(i,10)
digits[10-n] := digit
digit += 1
counts[digit] += 1
i = floor(i/10)
if i=0 then exit ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.