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... | #Julia | Julia | julia> S1 = Set(1:4) ; S2 = Set(3:6) ; println(S1,"\n",S2)
Set{Int64}({4,2,3,1})
Set{Int64}({5,4,6,3})
julia> 5 in S1 , 5 in S2
(false,true)
julia> intersect(S1,S2)
Set{Int64}({4,3})
julia> union(S1,S2)
Set{Int64}({5,4,6,2,3,1})
julia> setdiff(S1,S2)
Set{Int64}({2,1})
julia> issubset(S1,S2)
false
julia> isequal(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... | #D | D | import std.stdio, std.algorithm, std.range, std.functional;
uint[] sieve(in uint limit) nothrow @safe {
if (limit < 2)
return [];
auto composite = new bool[limit];
foreach (immutable uint n; 2 .. cast(uint)(limit ^^ 0.5) + 1)
if (!composite[n])
for (uint k = n * n; k < limit;... |
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... | #zkl | zkl | const width=9;
println(" ",[0..width].pump(String,"%4d".fmt));
[30..127].pump("".println,T(Void.Read,width,False), // don't fail on short lines
fcn(a,b,c){
String("%3d: ".fmt(a),
vm.arglist.pump(String,"toChar", // parameters (ints) to list to text
T("replace","\x1e",""),T("replace","\x1f",... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #uBasic.2F4tH | uBasic/4tH | Input "Carpet order: ";n
l = (3^n) - 1
For i = 0 To l
For j = 0 To l
Push i,j
Gosub 100
If Pop() Then
Print "#";
Else
Print " ";
EndIf
Next
Print
Next
End
100 y = Pop(): x = Pop() : Push 1
Do While (x > 0) * (y > 0)
If (x % 3 = 1) * (y % 3 = 1) Then
Push (P... |
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 ... | #Oforth | Oforth | : semordnilap
| w wr wrds |
ListBuffer new ->wrds
ListBuffer new
File new("unixdict.txt") forEach: w [
wrds include(w reverse dup ->wr) ifTrue: [ [wr, w] over add ]
w wr < ifTrue: [ wrds add(w) ]
] ; |
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 ... | #Perl | Perl | while (<>) {
chomp;
my $r = reverse;
$seen{$r}++ and $c++ < 5 and print "$_ $r\n" or $seen{$_}++;
}
print "$c\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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: semiPrime (in var integer: n) is func
result
var boolean: isSemiPrime is TRUE;
local
var integer: p is 2;
var integer: f is 0;
begin
while f < 2 and p**2 <= n do
while n rem p = 0 do
n := n div p;
incr(f);
end while;
... |
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... | #Sidef | Sidef | say is_semiprime(2**128 + 1) #=> true
say is_semiprime(2**256 - 1) #=> 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
... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every write(sedol("710889"|"B0YBKJ"|"406566"|"B0YBLH"|"228276"|
"B0YBKL"|"557910"|"B0YBKR"|"585284"|"B0YBKT"|"B00030"))
end
procedure sedol(x) #: return the completed sedol with check digit
static w,c
initial {
every (i := -1, c := table())[!(&digits||&ucase)] := i +:= 1 # map chars
... |
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 ... | #Red | Red | Red []
;;-------------------------------------
count-dig: func ["count occurence of digit in number"
;;-------------------------------------
s [string!] "number as string"
sdig [char!] "search number as char"
][
cnt: #"0" ;; counter as char for performance optimization
while [s: find/tail s sdig][cnt: cnt + 1]
... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #REXX | REXX | /*REXX program determines if a number (in base 10) is a self─describing, */
/*────────────────────────────────────────────────────── self─descriptive, */
/*────────────────────────────────────────────────────── autobiographical, or a */
/*─────────────────────────────────────────────... |
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... | #Tcl | Tcl | set primes {}
proc havePrime n {
global primes
foreach p $primes {
# Do the test-by-trial-division
if {$n/$p*$p == $n} {return false}
}
return true
}
for {set n 2} {$n < 100} {incr n} {
if {[havePrime $n]} {
lappend primes $n
puts -nonewline "$n "
}
}
puts "" |
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... | #Wren | Wren | import "/fmt" for Fmt
var primeSeq = Fiber.new {
Fiber.yield(2)
var n = 3
while (true) {
var isPrime = true
var p = 3
while (p * p <= n) {
if (n%p == 0) {
isPrime = false
break
}
p = p + 2
}
if (is... |
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.
| #min | min | (dup sqrt 0.5 + int +) :non-sq
(sqrt dup floor - 0 ==) :sq?
(:n =q 1 'dup q concat 'succ concat n times pop) :upto
(non-sq print! " " print!) 22 upto newline
"Squares for n below one million:" puts!
(non-sq 'sq? 'puts when pop) 999999 upto |
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.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 1 П4 ИП4 0 , 5 ИП4 КвКор + [x]
+ С/П КИП4 БП 02 |
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... | #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
val fruits = setOf("apple", "pear", "orange", "banana")
println("fruits : $fruits")
val fruits2 = setOf("melon", "orange", "lemon", "gooseberry")
println("fruits2 : $fruits2\n")
println("fruits contains 'banana' : ${"banana" in fruits}")
prin... |
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... | #Dart | Dart | // helper function to pretty print an Iterable
String iterableToString(Iterable seq) {
String str = "[";
Iterator i = seq.iterator;
if (i.moveNext()) str += i.current.toString();
while(i.moveNext()) {
str += ", " + i.current.toString();
}
return str + "]";
}
main() {
int limit = 1000;
int strt = 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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR x=0 TO 9
20 PRINT AT 0,4+2*x;x
30 PRINT AT x+1,0;10*(3+x)
40 NEXT x
50 FOR x=32 TO 127
60 LET d=x-10*INT (x/10)
70 LET t=(x-d)/10
80 PRINT AT t-2,4+2*d;CHR$ x
90 NEXT x |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #UNIX_Shell | UNIX Shell | #!/bin/bash
sierpinski_carpet() {
local -i n="${1:-3}"
local carpet="${2:-#}"
while (( n-- )); do
local center="${carpet//#/ }"
carpet="$(paste -d ' ' <(echo "$carpet"$'\n'"$carpet"$'\n'"$carpet") <(echo "$carpet"$'\n'"$center"$'\n'"$carpet") <(echo "$carpet"$'\n'"$carpet"$'\n'"$carpet"))"... |
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 ... | #Phix | Phix | with javascript_semantics
sequence words = unix_dict(), semordnilap={}
for i=1 to length(words) do
string word = words[i]
if rfind(reverse(word),words,i-1) then
semordnilap = append(semordnilap,word)
end if
end for
printf(1,"%d semordnilap found, the first five are:\n",length(semordnilap))
for i=1 t... |
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... | #Swift | Swift | import Foundation
func primes(n: Int) -> AnyGenerator<Int> {
var (seive, i) = ([Int](0..<n), 1)
let lim = Int(sqrt(Double(n)))
return anyGenerator {
while ++i < n {
if seive[i] != 0 {
if i <= lim {
for notPrime in stride(from: i*i, to: n, by: i) {
seive[notPrime] = 0
... |
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... | #Tcl | Tcl | package require math::numtheory
proc isSemiprime n {
if {!($n & 1)} {
return [::math::numtheory::isprime [expr {$n >> 1}]]
}
for {set i 3} {$i*$i < $n} {incr i 2} {
if {$n / $i * $i != $n && [::math::numtheory::isprime $i]} {
if {[::math::numtheory::isprime [expr {$n/$i}]]} {
return 1
}
}
... |
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
... | #J | J | sn =. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ac0 =: (, 10 | 1 3 1 7 3 9 +/@:* -)&.(sn i. |:) |
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 ... | #Ring | Ring |
# Project : Self-describing numbers
for num = 1 to 45000000
res = 0
for n=1 to len(string(num))
temp = string(num)
pos = number(temp[n])
cnt = count(temp,string(n-1))
if cnt = pos
res = res + 1
ok
next
if res = len(string(num))
... |
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 ... | #Ruby | Ruby | def self_describing?(n)
digits = n.digits.reverse
digits.each_with_index.all?{|digit, idx| digits.count(idx) == digit}
end
3_300_000.times {|n| puts n if self_describing?(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... | #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
int N;
for N:= 2 to 100 do
if IsPrime(N) then
[IntOut(0, N); ChOut(0, ^ )] |
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division | Sequence of primes by trial division | Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by... | #Yabasic | Yabasic | sub isPrime(v)
if v < 2 then return False : fi
if mod(v, 2) = 0 then return v = 2 : fi
if mod(v, 3) = 0 then return v = 3 : fi
d = 5
while d * d <= v
if mod(v, d) = 0 then return False else d = d + 2 : fi
wend
return True
end sub
for i = 101 to 999
if isPrime(i) print str$(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... | #zkl | zkl | fcn isPrime(p){
(p>=2) and (not [2 .. p.toFloat().sqrt()].filter1('wrap(n){ p%n==0 }))
}
fcn primesBelow(n){ [0..n].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.
| #MMIX | MMIX | LOC Data_Segment
GREG @
buf OCTA 0,0
GREG @
NL BYTE #a,0
errh BYTE "Sorry, number ",0
errt BYTE "is a quare.",0
prtOk BYTE "No squares found below 1000000.",0
i IS $1 % loop var.
x IS $2 % computations
y IS $3 % ..
z IS $4 % ..
t IS $5 % temp
Ja IS $127 % return address
LOC #100 % locate program
G... |
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... | #Lasso | Lasso | // Extend set type
define set->issubsetof(p::set) => .intersection(#p)->size == .size
define set->oncompare(p::set) => .intersection(#p)->size - .size
// Set creation
local(set1) = set('j','k','l','m','n')
local(set2) = set('m','n','o','p','q')
//Test m ∈ S -- "m is an element in set S"
#set1 >> 'm'
// A ∪ B -- ... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #Delphi | Delphi | program erathostenes;
{$APPTYPE CONSOLE}
type
TSieve = class
private
fPrimes: TArray<boolean>;
procedure InitArray;
procedure Sieve;
function getNextPrime(aStart: integer): integer;
function getPrimeArray: TArray<integer>;
public
function getPrimes(aMax: integer): TArray<integer>;
en... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Ursala | Ursala | #import std
#import nat
carpet = ~&a^?\<<&>>! (-*<7,5,7>; *=DS ~&K7+ ~&B**DS*=rlDS)^|R/~& predecessor
#show+
test = mat0 ~&?(`#!,` !)*** carpet* <0,1,2,3> |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #PHP | PHP | <?php
// Read dictionary into array
$dictionary = array_fill_keys(file(
'http://www.puzzlers.org/pub/wordlists/unixdict.txt',
FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
), true);
foreach (array_keys($dictionary) as $word) {
$reversed_word = strrev($word);
if (isset($dictionary[$reversed_word]) && $wo... |
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... | #TypeScript | TypeScript |
// Semiprime
function primeFactorsCount(n: number): number {
n = Math.abs(n);
var count = 0; // Result
if (n >= 2)
for (factor = 2; factor <= n; factor++)
while n % factor == 0) {
count++;
n /= factor;
}
return count;
}
const readline = require('readline').createInterface(... |
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... | #Wren | Wren | var semiprime = Fn.new { |n|
if (n < 3) return false
var nf = 0
for (i in 2..n) {
while (n%i == 0) {
if (nf == 2) return false
nf = nf + 1
n = (n/i).floor
}
}
return nf == 2
}
for (v in 1675..1680) {
System.print("%(v) -> %(semiprime.call(v) ... |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Java | Java | import java.util.Scanner;
public class SEDOL{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String sedol = sc.next();
System.out.println(sedol + getSedolCheckDigit(sedol));
}
}
private static final int[] mult = {1, 3, 1, 7, 3, 9};
public static i... |
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 ... | #Run_BASIC | Run BASIC | for i = 0 to 50000000 step 10
a$ = str$(i)
for c = 1 TO len(a$)
d = val(mid$(a$, c, 1))
j(d) = j(d) + 1
k(c-1) = d
next c
r = 0
for n = 0 to 10
r = r + (j(n) = k(n))
j(n) = 0
k(n) = 0
next n
if r = 11 then print i
next i
print "== End =="
end |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #Rust | Rust |
fn is_self_desc(xx: u64) -> bool
{
let s: String = xx.to_string();
let mut count_vec = vec![0; 10];
for c in s.chars() {
count_vec[c.to_digit(10).unwrap() as usize] += 1;
}
for (i, c) in s.chars().enumerate() {
if count_vec[i] != c.to_digit(10).unwrap() as usize {
retur... |
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.
| #Modula-3 | Modula-3 | MODULE NonSquare EXPORTS Main;
IMPORT IO, Fmt, Math;
VAR i: INTEGER;
PROCEDURE NonSquare(n: INTEGER): INTEGER =
BEGIN
RETURN n + FLOOR(0.5D0 + Math.sqrt(FLOAT(n, LONGREAL)));
END NonSquare;
BEGIN
FOR n := 1 TO 22 DO
IO.Put(Fmt.Int(NonSquare(n)) & " ");
END;
IO.Put("\n");
FOR n := 1 TO 100000... |
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.
| #Nim | Nim | import math, strutils
func nosqr(n: int): seq[int] =
result = newSeq[int](n)
for i in 1..n:
result[i - 1] = i + i.float.sqrt.toInt
func issqr(n: int): bool =
sqrt(float(n)).splitDecimal().floatpart < 1e-7
echo "Sequence for n = 22:"
echo nosqr(22).join(" ")
for i in nosqr(1_000_000 - 1):
assert no... |
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... | #LFE | LFE |
> (set set-1 (sets:new))
#(set 0 16 16 8 80 48 ...)
> (set set-2 (sets:add_element 'a set-1))
#(set 1 16 16 8 80 48 ...)
> (set set-3 (sets:from_list '(a b)))
#(set 2 16 16 8 80 48 ...)
> (sets:is_element 'a set-2)
true
> (set union (sets:union set-2 set-3))
#(set 2 16 16 8 80 48 ...)
> (sets:to_list union)
(a b)
> (... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #Draco | Draco | /* Sieve of Eratosthenes - fill a given boolean array */
proc nonrec sieve([*] bool prime) void:
word p, c, max;
max := dim(prime,1)-1;
prime[0] := false;
prime[1] := false;
for p from 2 upto max do prime[p] := true od;
for p from 2 upto max>>1 do
if prime[p] then
for c from ... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #VBA | VBA | Const Order = 4
Function InCarpet(ByVal x As Integer, ByVal y As Integer)
Do While x <> 0 And y <> 0
If x Mod 3 = 1 And y Mod 3 = 1 Then
InCarpet = " "
Exit Function
End If
x = x \ 3
y = y \ 3
Loop
InCarpet = "#"
End Function
Public Sub sierpinski_... |
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 ... | #PicoLisp | PicoLisp | (let Semordnilap
(mapcon
'((Lst)
(when (member (reverse (car Lst)) (cdr Lst))
(cons (pack (car Lst))) ) )
(make (in "unixdict.txt" (while (line) (link @)))) )
(println (length Semordnilap) (head 5 Semordnilap)) ) |
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 ... | #PL.2FI | PL/I |
find: procedure options (main); /* 20/1/2013 */
declare word character (20) varying controlled;
declare dict(*) character (20) varying controlled;
declare 1 pair controlled,
2 a character (20) varying, 2 b character (20) varying;
declare (i, j) fixed binary;
declare in file;
open fil... |
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... | #XPL0 | XPL0 | func Semiprime(N); \Return 'true' if N is semiprime
int N, F, C;
[C:= 0; F:= 2;
repeat if rem(N/F) = 0 then
[C:= C+1;
N:= N/F;
]
else F:= F+1;
until F > N;
return C = 2;
];
int N;
[for N:= 1 to 100 do
if Semiprime(N) then
[IntOut(0, 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... | #zkl | zkl | fcn semiprime(n){
reg f = 0;
p:=2; while(f < 2 and p*p <= n){
while(0 == n % p){ n /= p; f+=1; }
p+=1;
}
return(f + (n > 1) == 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
... | #JavaScript | JavaScript | function sedol(input) {
return input + sedol_check_digit(input);
}
var weight = [1, 3, 1, 7, 3, 9, 1];
function sedol_check_digit(char6) {
if (char6.search(/^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}$/) == -1)
throw "Invalid SEDOL number '" + char6 + "'";
var sum = 0;
for (var i = 0; i < char6.length; i++... |
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 ... | #Scala | Scala | object SelfDescribingNumbers extends App {
def isSelfDescribing(a: Int): Boolean = {
val s = Integer.toString(a)
(0 until s.length).forall(i => s.count(_.toString.toInt == i) == s(i).toString.toInt)
}
println("Curious numbers n = x0 x1 x2...x9 such that xi is the number of digits equal to i in 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 ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: selfDescr (in string: stri) is func
result
var boolean: check is TRUE;
local
var integer: idx is 0;
var array integer: count is [0 .. 9] times 0;
begin
for idx range 1 to length(stri) do
incr(count[ord(stri[idx]) - ord('0')]);
end for;
... |
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.
| #OCaml | OCaml | # let nonsqr n = n + truncate (0.5 +. sqrt (float n));;
val nonsqr : int -> int = <fun>
# (* first 22 values (as a list) has no squares: *)
for i = 1 to 22 do
Printf.printf "%d " (nonsqr i)
done;
print_newline ();;
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
- : unit = ()
# (* The following ch... |
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... | #Liberty_BASIC | Liberty BASIC |
A$ ="red hot chili peppers rule OK"
B$ ="lady in red"
print " New set, in space-separated form. Extra spaces and duplicates will be removed. "
input newSet$
newSet$ =trim$( newSet$)
newSet$ =stripBigSpaces$( newSet$)
newSet$ =removeDupes$( newSet$)
print " Set stored as the string '"; newSet$; "'... |
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... | #DWScript | DWScript | function Primes(limit : Integer) : array of Integer;
var
n, k : Integer;
sieve := new Boolean[limit+1];
begin
for n := 2 to Round(Sqrt(limit)) do begin
if not sieve[n] then begin
for k := n*n to limit step n do
sieve[k] := True;
end;
end;
for k:=2 to limit do
if n... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #VBScript | VBScript | Function InCarpet(i,j)
If i > 0 And j > 0 Then
Do While i > 0 And j > 0
If i Mod 3 = 1 And j Mod 3 = 1 Then
InCarpet = " "
Exit Do
Else
InCarpet = "#"
End If
i = Int(i / 3)
j = Int(j / 3)
Loop
Else
InCarpet = "#"
End If
End Function
Function Carpet(n)
k = 3^n - 1
x2 = 0
y2 = 0... |
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 ... | #PowerShell | PowerShell |
function Reverse-String ([string]$String)
{
[char[]]$output = $String.ToCharArray()
[Array]::Reverse($output)
$output -join ""
}
[string]$url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt"
[string]$out = ".\unixdict.txt"
(New-Object System.Net.WebClient).DownloadFile($url, $out)
[string[]]$f... |
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
... | #jq | jq | def ascii_upcase:
explode | map( if 97 <= . and . <= 122 then . - 32 else . end) | implode;
def sedol_checksum:
def encode(a): 10 + (a|explode[0]) - ("A"|explode[0]);
. as $sed
| [1,3,1,7,3,9] as $sw
| reduce range(0;6) as $i
(0;
$sed[$i:$i+1] as $c
| if ( "0123456789" | index($c) )
... |
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
... | #Julia | Julia | using Base.Test
function appendchecksum(chars::AbstractString)
if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end
weights = [1, 3, 1, 7, 3, 9, 1]
s = 0
for (w, c) in zip(weights, chars)
s += w * parse(Int, c, 36)
end
return string(chars, (10 - s % 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 ... | #Sidef | Sidef | func sdn(Number n) {
var b = [0]*n.len
var a = n.digits.flip
a.each { |i| b[i] := 0 ++ }
a == b
}
var values = [1210, 2020, 21200, 3211000,
42101000, 521001000, 6210001000, 27, 115508]
values.each { |test|
say "#{test} is #{sdn(test) ? '' : 'NOT ' }a self describing number."
}
say "\nSelf-desc... |
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 ... | #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public var isSelfDescribing: Bool {
let stringChars = String(self).map({ String($0) })
let counts = stringChars.reduce(into: [Int: Int](), {res, char in res[Int(char), default: 0] += 1})
for (i, n) in stringChars.enumerated() where counts[i, def... |
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.
| #Oforth | Oforth | 22 seq map(#[ dup sqrt 0.5 + floor + ]) println
1000000 seq map(#[ dup sqrt 0.5 + floor + ]) conform(#[ sqrt dup floor <>]) println |
http://rosettacode.org/wiki/Sequence_of_non-squares | Sequence of non-squares | Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
| #Ol | Ol |
(import (lib math))
(print
; sequence for 1 .. 22
(map (lambda (n)
(+ n (floor (+ 1/2 (exact (sqrt n))))))
(iota 22 1)))
; ==> (2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
(print
; filter out non squares
(filter
(lambda (x)
(let ((s (floor (exact (sqrt x)... |
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... | #Lua | Lua | function emptySet() return { } end
function insert(set, item) set[item] = true end
function remove(set, item) set[item] = nil end
function member(set, item) return set[item] end
function size(set)
local result = 0
for _ in pairs(set) do result = result + 1 end
return result
end
function fromTable(tbl)... |
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... | #Dylan | Dylan | define method primes(n)
let limit = floor(n ^ 0.5) + 1;
let sieve = make(limited(<simple-vector>, of: <boolean>), size: n + 1, fill: #t);
let last-prime = 2;
while (last-prime < limit)
for (x from last-prime ^ 2 to n by last-prime)
sieve[x] := #f;
end for;
block (found-prime)
for (n fr... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Wren | Wren | var inCarpet = Fn.new { |x, y|
while (true) {
if (x == 0 || y == 0) return true
if (x%3 == 1 && y%3 == 1) return false
x = (x/3).floor
y = (y/3).floor
}
}
var carpet = Fn.new { |n|
var power = 3.pow(n)
for (i in 0...power) {
for (j in 0...power) {
Sy... |
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 ... | #PureBasic | PureBasic | If OpenConsole("")=0 : End 1 : EndIf
If ReadFile(0,"./Data/unixdict.txt")=0 : End 2 : EndIf
NewList dict$()
While Eof(0)=0 : AddElement(dict$()) : dict$()=Trim(ReadString(0)) : Wend : CloseFile(0)
While FirstElement(dict$())
buf$=dict$() : DeleteElement(dict$())
If buf$="" : Continue : EndIf
xbuf$=ReverseSt... |
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
... | #Kotlin | Kotlin | // version 1.1.0
val weights = listOf(1, 3, 1, 7, 3, 9, 1)
fun sedol7(sedol6: String): String {
if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6")
var sum = 0
for (i in 0..5) {
val c = sedol6[i]
val v = when (c) {
in '0'..'9' -> c.t... |
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 ... | #Tcl | Tcl | package require Tcl 8.5
proc isSelfDescribing num {
set digits [split $num ""]
set len [llength $digits]
set count [lrepeat $len 0]
foreach d $digits {
if {$d >= $len} {return false}
lset count $d [expr {[lindex $count $d] + 1}]
}
foreach d $digits c $count {if {$c != $d} {return false}}
r... |
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 ... | #UNIX_Shell | UNIX Shell | selfdescribing() {
local n=$1
local count=()
local i
for ((i=0; i<${#n}; i++)); do
((count[${n:i:1}]++))
done
for ((i=0; i<${#n}; i++)); do
(( ${n:i:1} == ${count[i]:-0} )) || return 1
done
return 0
}
for n in 0 1 10 11 1210 2020 21200 3211000 42101000; do
if selfd... |
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.
| #Oz | Oz | declare
fun {NonSqr N}
N + {Float.toInt {Floor 0.5 + {Sqrt {Int.toFloat N}}}}
end
fun {SqrtInt N}
{Float.toInt {Sqrt {Int.toFloat N}}}
end
fun {IsSquare N}
{Pow {SqrtInt N} 2} == N
end
Ns = {Map {List.number 1 999999 1} NonSqr}
in
{Show {List.take Ns 22}}
{Show {Some Ns IsSquare}} |
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... | #M2000_Interpreter | M2000 Interpreter |
Module Sets {
setA=("apple", "cherry", "grape")
setB=("banana","cherry", "date")
Print Len(setA)=3 'true
Print setA#pos("apple")>=0=true ' exist
Print setA#pos("banana")>=0=False ' not exist
intersection=lambda SetB (x$)-> SetB#pos(x$)>=0
SetC=SetA#filter(intersection,(,))
Print SetC
Difference= la... |
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... | #E | E | def rangeFromBelowBy(start, limit, step) {
return def stepper {
to iterate(f) {
var i := start
while (i < limit) {
f(null, i)
i += step
}
}
}
}
|
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #X86_Assembly | X86 Assembly | ;x86-64 assembly code for Microsoft Windows
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
;Assembled with NASM version 2.11.06
;Linked to C library with gcc version 4.9.2 (x86_64-win32-seh-rev1, Built by MinGW-W64 project)
;Assembled and linked with the following commands:... |
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 ... | #Python | Python | >>> with open('unixdict.txt') as f:
wordset = set(f.read().strip().split())
>>> revlist = (''.join(word[::-1]) for word in wordset)
>>> pairs = set((word, rev) for word, rev in zip(wordset, revlist)
if word < rev and rev in wordset)
>>> len(pairs)
158
>>> sorted(pairs, key=lambda p: (len(p[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
... | #langur | langur | val .csd = f(.code) {
given len(.code) {
case 0:
return "nada, zip, zilch"
case != 6:
return "invalid length"
}
if matching(re/[^B-DF-HJ-NP-TV-Z0-9]/, .code) {
return "invalid character(s)"
}
val .weight = [1,3,1,7,3,9]
val .nums = s2n .code
... |
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 ... | #VBScript | VBScript |
Function IsSelfDescribing(n)
IsSelfDescribing = False
Set digit = CreateObject("Scripting.Dictionary")
For i = 1 To Len(n)
k = Mid(n,i,1)
If digit.Exists(k) Then
digit.Item(k) = digit.Item(k) + 1
Else
digit.Add k,1
End If
Next
c = 0
For j = 0 To Len(n)-1
l = Mid(n,j+1,1)
If digit.Exists(CStr(... |
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 ... | #Wren | Wren | var selfDesc = Fn.new { |n|
var ns = "%(n)"
var nc = ns.count
var count = List.filled(nc, 0)
var sum = 0
while (n > 0) {
var d = n % 10
if (d >= nc) return false // can't have a digit >= number of digits
sum = sum + d
if (sum > nc) return false
count[d] = cou... |
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.
| #PARI.2FGP | PARI/GP | [vector(22,n,n + floor(1/2 + sqrt(n))), sum(n=1,1e6,issquare(n + floor(1/2 + sqrt(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.
| #Pascal | Pascal | Program SequenceOfNonSquares(output);
uses
Math;
var
m, n, test: longint;
begin
for n := 1 to 22 do
begin
test := n + floor(0.5 + sqrt(n));
write(test, ' ');
end;
writeln;
for n := 1 to 1000000 do
begin
test := n + floor(0.5 + sqrt(n));
m := round(sqrt(test));
if (m*m = tes... |
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... | #Maple | Maple |
> S := { 2, 3, 5, 7, 11, Pi, "foo", { 2/3, 3/4, 4/5 } };
S := {2, 3, 5, 7, 11, "foo", Pi, {2/3, 3/4, 4/5}}
> type( S, set );
true
> Pi in S;
Pi in {2, 3, 5, 7, 11, "foo", Pi, {2/3, 3/4, 4/5}}
> if Pi in S then print( yes ) else print( no ) end:
... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #EasyLang | EasyLang | len prims[] 100
max = sqrt len prims[]
tst = 2
while tst <= max
if prims[tst] = 0
i = tst * tst
while i < len prims[]
prims[i] = 1
i += tst
.
.
tst += 1
.
i = 2
while i < len prims[]
if prims[i] = 0
print i
.
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc DrawPat(X0, Y0, S); \Draw 3x3 pattern with hole in middle
int X0, Y0, S; \coordinate of upper-left corner, size
int X, Y;
[for Y:= 0 to 2 do
for X:= 0 to 2 do
if X#1 or Y#1 then \don't draw middle pattern
... |
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 ... | #Quackery | Quackery | []
$ "rosetta/unixdict.txt" sharefile drop
nest$
[ behead reverse swap
2dup find over found iff
[ dip [ nested join ] ]
else nip
dup [] = until ]
drop
say "Number of semordnilaps: "
dup size echo cr
sortwith [ size swap size > ]
5 split drop
say "Five longest: "
witheach
[ ... |
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 ... | #Racket | Racket |
#lang racket
(define seen (make-hash))
(define semordnilaps '())
(call-with-input-file "/usr/share/dict/words"
(λ(i) (for ([l (in-lines i)])
(define r (list->string (reverse (string->list l))))
(unless (equal? r l)
(hash-set! seen l #t)
(when (hash-ref seen r #f)
... |
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
... | #Liberty_BASIC | Liberty BASIC |
'adapted from BASIC solution
mult(1) = 1: mult(2) = 3: mult(3) = 1
mult(4) = 7: mult(5) = 3: mult(6) = 9
DO
INPUT a$
PRINT a$ + STR$(getSedolCheckDigit(a$))
LOOP WHILE a$ <> ""
FUNCTION getSedolCheckDigit (str$)
IF LEN(str$) <> 6 THEN
PRINT "Six chars only please"
EXIT ... |
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 ... | #XPL0 | XPL0 | code ChOut=8, IntOut=11;
func SelfDesc(N); \Returns 'true' if N is self-describing
int N;
int Len, \length = number of digits in N
I, D;
char Digit(10), Count(10);
proc Num2Str(N); \Convert integer N to string in Digit
int N;
int R;
[N:= 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 ... | #Yabasic | Yabasic | FOR N = 1 TO 5E7
IF FNselfdescribing(N) PRINT N
NEXT
sub FNselfdescribing(N)
LOCAL D(9), I, L, O
O = N
L = INT(LOG(N, 10))
WHILE(N)
I = MOD(N, 10)
D(I) = D(I) + 10^(L-I)
N = INT(N / 10)
WEND
L = 0
FOR I = 0 TO 8 : L = L + D(I) : NEXT
RETURN O = L
END S... |
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.
| #Perl | Perl | sub nonsqr { my $n = shift; $n + int(0.5 + sqrt $n) }
print join(' ', map nonsqr($_), 1..22), "\n";
foreach my $i (1..1_000_000) {
my $root = sqrt nonsqr($i);
die "Oops, nonsqr($i) is a square!" if $root == int $root;
} |
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.
| #Phix | Phix | with javascript_semantics
sequence s = repeat(0,22)
for n=1 to length(s) do
s[n] = n + floor(1/2 + sqrt(n))
end for
printf(1,"%V\n",{s})
integer nxt = 2, snxt = nxt*nxt, k
for n=1 to 1000000 do
k = n + floor(1/2 + sqrt(n))
if k>snxt then
-- printf(1,"%d didn't occur\n",snxt)
nxt += 1
s... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | set1 = {"a", "b", "c", "d", "e"}; set2 = {"a", "b", "c", "d", "e", "f", "g"};
MemberQ[set1, "a"]
Union[set1 , set2]
Intersection[set1 , set2]
Complement[set2, set1](*Set Difference*)
MemberQ[Subsets[set2], set1](*Subset*)
set1 == set2(*Equality*)
set1 == set1(*Equality*) |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #eC | eC |
public class FindPrime
{
Array<int> primeList { [ 2 ], minAllocSize = 64 };
int index;
index = 3;
bool HasPrimeFactor(int x)
{
int max = (int)floor(sqrt((double)x));
for(i : primeList)
{
if(i > max) break;
if(x % i == 0) return true;
}
return false;... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Yabasic | Yabasic | sub sp$(n)
local i, s$
for i = 1 to n
s$ = s$ + " "
next i
return s$
end sub
sub replace$(s$, cf$, cr$)
local i, p
do
i = instr(s$, cf$, p)
if not i break
mid$(s$, i, 1) = cr$
p = i
loop
return s$
end sub
sub foreach$(carpet$, p$, m)
local n, i, t$(1)
n = token(carpet$, t$(), ",")
for 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 ... | #Raku | Raku | my $words = set slurp("unixdict.txt").lines;
my @sems = gather for $words.flat -> $word {
my $drow = $word.key.flip;
take $drow if $drow ∈ $words and $drow lt $word;
}
say $_ ~ ' ' ~ $_.flip for @sems.pick(5); |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #REXX | REXX | /* REXX ***************************************************************
* 07.09.2012 Walter Pachl
**********************************************************************/
fid='unixdict.txt' /* the test dictionary */
have.='' /* words encountered */
pi=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
... | #M4 | M4 | divert(-1)
changequote(`[',`]')
define([_bar],include(sedol.inp))
define([eachlineA],
[ifelse(eval($2>0),1,
[$3(substr([$1],0,$2))[]eachline(substr([$1],incr($2)),[$3])])])
define([eachline],[eachlineA([$1],index($1,[
]),[$2])])
define([_idx],
[index([0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ],substr($1,$2,1))])... |
http://rosettacode.org/wiki/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #zkl | zkl | fcn isSelfDescribing(n){
if (n.bitAnd(1)) return(False); // Wikipedia: last digit must be zero
nu:= n.toString();
ns:=["0".."9"].pump(String,nu.inCommon,"len"); //"12233".inCommon("2")-->"22"
(nu+"0000000000")[0,10] == ns; //"2020","2020000000"
} |
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.
| #PHP | PHP | <?php
//First Task
for($i=1;$i<=22;$i++){
echo($i + floor(1/2 + sqrt($i)) . "\n");
}
//Second Task
$found_square=False;
for($i=1;$i<=1000000;$i++){
$non_square=$i + floor(1/2 + sqrt($i));
if(sqrt($non_square)==intval(sqrt($non_square))){
$found_square=True;
}
}
echo("\n");
if($found_square){
ech... |
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... | #MATLAB_.2F_Octave | MATLAB / Octave |
% Set creation
s = [1, 2, 4]; % numeric values
t = {'a','bb','ccc'}; % cell array of strings
u = unique([1,2,3,3,2,3,2,4,1]); % set consists only of unique elements
% Test m ∈ S -- "m is an element in set S"
ismember(m, S)
% A ∪ B -- union; a set of all elements either in set A or ... |
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... | #EchoLisp | EchoLisp | (require 'types) ;; bit-vector
;; converts sieve->list for integers in [nmin .. nmax[
(define (s-range sieve nmin nmax (base 0))
(for/list ([ i (in-range nmin nmax)]) #:when (bit-vector-ref sieve i) (+ i base)))
;; next prime in sieve > p, or #f
(define (s-next-prime sieve p ) ;;
(bit-vector-scan-1 sieve (1+ p)... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Z80_Assembly | Z80 Assembly | ; Sierpinski carpet in Z80 assembly (for CP/M OS - you can use `tnylpo` or `z88dk-ticks` on PC)
OPT --syntax=abf : OUTPUT "sierpinc.com" ; asm syntax for z00m's variant of sjasmplus
ORG $100
; start for n=0, total size is 1x1 (just '#'), show five carpets for n=0,1,2,3,4
ld h,%00000001 ; 3**0 = ... |
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 ... | #Ring | Ring |
# Project : Semordnilap
load "stdlib.ring"
nr = 0
num = 0
aList = file2list("C:\Ring\CalmoSoft\unixdict.txt")
for n = 1 to len(aList)
bool = semordnilap(aList[n])
if (bool > 0 and nr > n)
num = num + 1
if num % 31 = 0
see aList[n] + " " + aList[nr] + nl
ok
ok
next... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.