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_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #Perl | Perl | use strict;
use English;
use Smart::Comments;
my @ex1 = consolidate( (['A', 'B'], ['C', 'D']) );
### Example 1: @ex1
my @ex2 = consolidate( (['A', 'B'], ['B', 'D']) );
### Example 2: @ex2
my @ex3 = consolidate( (['A', 'B'], ['C', 'D'], ['D', 'B']) );
### Example 3: @ex3
my @ex4 = consolidate( (['H', 'I', 'K'], ['A', ... |
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors | Sequence: smallest number with exactly n divisors | Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly... | #Swift | Swift | // See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
// Deal with powers of 2 first
while n % 2 == 0 {
total += 1
n /= 2
}
// Odd prime factors up to the square root
var p = 3
while p * p <= n {
... |
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors | Sequence: smallest number with exactly n divisors | Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly... | #Tcl | Tcl | proc divCount {n} {
set cnt 0
for {set d 1} {($d * $d) <= $n} {incr d} {
if {0 == ($n % $d)} {
incr cnt
if {$d < ($n / $d)} {
incr cnt
}
}
}
return $cnt
}
proc A005179 {n} {
if {$n >= 1} {
for {set k 1} {1} {incr k} {
... |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Smalltalk | Smalltalk |
(SHA256 new hashStream: 'Rosetta code' readStream) hex.
|
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Tcl | Tcl | package require sha256
puts [sha2::sha256 -hex "Rosetta code"] |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #Scheme | Scheme |
; band - binary AND operation
; bor - binary OR operation
; bxor - binary XOR operation
; >>, << - binary shift operations
; runes->string - convert byte list to string /(runes->string '(65 66 67 65)) => "ABCA"/
(define (sha1-padding-size n)
(let ((x (mod (- 56 (rem n 64)) 64)))
(if (= x 0) 64 x)))
(de... |
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... | #OxygenBasic | OxygenBasic |
uses console
int i,j
string c
for i=32 to 127
select case i
case 32 : c="spc"
case 127: c="del"
case else c=chr i
end select
print i ": " c tab
j++
if j = 8 'columns
print cr
j=0
endif
next
pause
|
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:
*
* *
* *
* * * *
* *
* * * *
... | #Ring | Ring |
# Project : Sierpinski triangle
norder=4
xy = list(40)
for i = 1 to 40
xy[i] = " "
next
triangle(1, 1, norder)
for i = 1 to 36
see xy[i] + nl
next
func triangle(x, y, n)
if n = 0
xy[y] = left(xy[y],x-1) + "*" + substr(xy[y],x+1)
else
n=n-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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #PHP | PHP | <?php
function isSierpinskiCarpetPixelFilled($x, $y) {
while (($x > 0) or ($y > 0)) {
if (($x % 3 == 1) and ($y % 3 == 1)) {
return false;
}
$x /= 3;
$y /= 3;
}
return true;
}
function sierpinskiCarpet($order) {
$size = pow(3, $order);
for ($y = 0 ; $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 ... | #Clojure | Clojure | (ns rosettacode.semordnilaps
(:require [clojure.string :as str])
[clojure.java.io :as io ]))
(def dict-file
(or (first *command-line-args*) "unixdict.txt"))
(def dict (-> dict-file io/reader line-seq set))
(defn semordnilap? [word]
(let [rev (str/reverse word)]
(and (not= word rev) (dict ... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Ring | Ring |
# Project : Short-circuit evaluation
for k = 1 to 2
word = ["AND","OR"]
see "========= " + word[k] + " ==============" + nl
for i = 0 to 1
for j = 0 to 1
see "a(" + i + ") " + word[k] +" b(" + j + ")" + nl
res =a(i)
if word[k] = "AND" ... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Ruby | Ruby | def a( bool )
puts "a( #{bool} ) called"
bool
end
def b( bool )
puts "b( #{bool} ) called"
bool
end
[true, false].each do |a_val|
[true, false].each do |b_val|
puts "a( #{a_val} ) and b( #{b_val} ) is #{a( a_val ) and b( b_val )}."
puts
puts "a( #{a_val} ) or b( #{b_val} ) is #{a( a_val) ... |
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... | #Lasso | Lasso | // with a lot of unneeded params.
// sends plain text and html in same email
// simple usage is below
email_send(
-host = 'mail.example.com',
-port = 25,
-timeout = 100,
-username = 'user.name',
-password = 'secure_password',
-priority = 'immediate',
-to = 'joe@average.com',
-cc = 'jane@average.com',
... |
http://rosettacode.org/wiki/Send_email | Send email | Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or f... | #Liberty_BASIC | Liberty BASIC |
text$ = "This is a simple text message."
from$ = "user@diga.me.es"
username$ = "me@diga.me.es"
'password$ = "***********"
recipient$ = "somebody@gmail.com"
server$ = "auth.smtp.1and1.co.uk:25"
subject$ = chr$( 34) +text$ +chr$( 34) ' Use quotes to allow spaces in text.
message$ ... |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #Common_Lisp | Common Lisp | (defun semiprimep (n &optional (a 2))
(cond ((> a (isqrt n)) nil)
((zerop (rem n a)) (and (primep a) (primep (/ n a))))
(t (semiprimep n (+ a 1)))))
(defun primep (n &optional (a 2))
(cond ((> a (isqrt n)) t)
((zerop (rem n a)) nil)
(t (primep n (+ a 1))))) |
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... | #Crystal | Crystal | def semiprime(n)
nf = 0
(2..n).each do |i|
while n % i == 0
return false if nf == 2
nf += 1
n /= i
end
end
nf == 2
end
(1675..1681).each { |n| puts "#{n} -> #{semiprime(n)}" } |
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
... | #ALGOL_68 | ALGOL 68 | []INT sedol weights = (1, 3, 1, 7, 3, 9);
STRING reject = "AEIOUaeiou";
PROC strcspn = (STRING s,reject)INT: (
INT out:=0;
FOR i TO UPB s DO
IF char in string(s[i], LOC INT, reject) THEN
return out
FI;
out:=i
OD;
return out: out
);
PROC sedol checksum = (REF STRING sedol6)INT:
(
INT out;... |
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 ... | #C.2B.2B | C++ |
#include <iostream>
//--------------------------------------------------------------------------------------------------
typedef unsigned long long bigint;
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Go | Go | package main
import (
"fmt"
"time"
)
func sumDigits(n int) int {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
func main() {
st := time.Now()
count := 0
var selfs []int
... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | (* defining functions *)
setcc[a_, b_] := a <= x <= b
setoo[a_, b_] := a < x < b
setco[a_, b_] := a <= x < b
setoc[a_, b_] := a < x <= b
setSubtract[s1_, s2_] := s1 && Not[s2]; (* new function; subtraction not built in *)
inSetQ[y_, set_] := set /. x -> y
(* testing sets *)
set1 = setoc[0, 1] || setco[0, 2] (* uni... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #Nim | Nim | import math, strformat, sugar
type
RealPredicate = (float) -> bool
RangeType {.pure} = enum Closed, BothOpen, LeftOpen, RightOpen
RealSet = object
low, high: float
predicate: RealPredicate
proc initRealSet(slice: Slice[float]; rangeType: RangeType): RealSet =
result = RealSet(low: slice.a, h... |
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... | #Delphi | Delphi | (lib 'sequences)
(define (is-prime? p)
(cond
[(< p 2) #f]
[(zero? (modulo p 2)) (= p 2)]
[else
(for/and ((d [3 5 .. (1+ (sqrt p))] )) (!zero? (modulo p d)))]))
(is-prime? 101) → #t |
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... | #EchoLisp | EchoLisp | (lib 'sequences)
(define (is-prime? p)
(cond
[(< p 2) #f]
[(zero? (modulo p 2)) (= p 2)]
[else
(for/and ((d [3 5 .. (1+ (sqrt p))] )) (!zero? (modulo p d)))]))
(is-prime? 101) → #t |
http://rosettacode.org/wiki/Sequence_of_non-squares | Sequence of non-squares | Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
| #C.2B.2B | C++ | #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <boost/bind.hpp>
#include <iterator>
double nextNumber( double number ) {
return number + floor( 0.5 + sqrt( number ) ) ;
}
int main( ) {
std::vector<double> non_squares ;
typedef std::vector<double>::iterator SVI ;
non... |
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... | #C.2B.2B | C++ |
#include <set>
#include <iostream>
#include <iterator>
#include <algorithm>
namespace set_display {
template <class T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& set)
{
os << '[';
if (!set.empty()) {
std::copy(set.begin(), --set.end(), std::ostream_iterator<T>(os, ", "));
... |
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... | #AppleScript | AppleScript | on sieveOfEratosthenes(limit)
script o
property numberList : {missing value}
end script
repeat with n from 2 to limit
set end of o's numberList to n
end repeat
repeat with n from 2 to (limit ^ 0.5 div 1)
if (item n of o's numberList is n) then
repeat with multip... |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #Phix | Phix | with javascript_semantics
function has_intersection(sequence set1, set2)
for i=1 to length(set1) do
if find(set1[i],set2) then
return true
end if
end for
return false
end function
function get_union(sequence set1, set2)
for i=1 to length(set2) do
if not find(set2[i]... |
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors | Sequence: smallest number with exactly n divisors | Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly... | #Wren | Wren | import "/math" for Int
var limit = 22
var numbers = List.filled(limit, 0)
var i = 1
while (true) {
var nd = Int.divisors(i).count
if (nd <= limit && numbers[nd-1] == 0) {
numbers[nd-1] = i
if (numbers.all { |n| n > 0 }) break
}
i = i + 1
}
System.print("The first %(limit) terms are:")
... |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Vlang | Vlang | import crypto.sha256
fn main() {
println("${sha256.hexhash('Rosetta code')}")
mut h := sha256.new()
h.write('Rosetta code'.bytes()) ?
println('${h.checksum().map(it.hex()).join('')}')
} |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Wren | Wren | import "/crypto" for Sha256
import "/fmt" for Fmt
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"The q... |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "msgdigest.s7i";
const proc: main is func
begin
writeln(hex(sha1("Rosetta Code")));
end func; |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #Sidef | Sidef | var sha = frequire('Digest::SHA');
say sha.sha1_hex('Rosetta Code'); |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioin... | #Perl | Perl | use charnames ':full';
binmode STDOUT, ':utf8';
sub glyph {
my($n) = @_;
if ($n < 33) { chr 0x2400 + $n } # display symbol names for invisible glyphs
elsif ($n==124) { '<nowiki>|</nowiki>' }
elsif ($n==127) { 'DEL' }
else { chr $n }
}
print qq[{|class="wikitable" style="text-align:... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Ruby | Ruby | ruby -le'16.times{|y|print" "*(15-y),*(0..y).map{|x|~y&x>0?" ":" *"}}' |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Picat | Picat |
in_carpet(X, Y) =>
while (X != 0, Y != 0)
if (X mod 3 == 1, Y mod 3 == 1) then
false
end,
X := X div 3,
Y := Y div 3
end.
in_carpet(_, _) =>
true.
main(Args) =>
N = to_int(Args[1]),
Power1 = 3 ** N - 1,
foreach (I in 0..Power1)
foreach (J... |
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 ... | #Common_Lisp | Common Lisp | (defun semordnilaps (word-list)
(let ((word-map (make-hash-table :test 'equal)))
(loop for word in word-list do
(setf (gethash word word-map) t))
(loop for word in word-list
for rword = (reverse word)
when (and (string< word rword) (gethash rword word-map))
collect (cons word rwo... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Run_BASIC | Run BASIC | for k = 1 to 2
ao$ = word$("AND,OR",k,",")
print "========= ";ao$;" =============="
for i = 0 to 1
for j = 0 to 1
print "a("; i; ") ";ao$;" b("; j; ")"
res =a(i) 'call always
'print res;"<===="
if ao$ = "AND" and res <> 0 then res = b(j)
if ao$ = "OR" and res = 0 then res = b(j)
next
next
n... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Rust | Rust | fn a(foo: bool) -> bool {
println!("a");
foo
}
fn b(foo: bool) -> bool {
println!("b");
foo
}
fn main() {
for i in vec![true, false] {
for j in vec![true, false] {
println!("{} and {} == {}", i, j, a(i) && b(j));
println!("{} or {} == {}", i, j, a(i) || b(j));
... |
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... | #Lingo | Lingo | ----------------------------------------
-- Sends email via SMTP using senditquiet.exe (15 KB)
-- @param {string} fromAddr
-- @param {string} toAddr - multiple addresses separated with ;
-- @param {string} subject
-- @param {string} message - use "\n" for line breaks
-- @param {string} [cc=VOID] - optional; multiple ad... |
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... | #LiveCode | LiveCode | revMail "help@example.com",,"Help!",field "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... | #LotusScript | LotusScript | Dim session As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Set db = session.CurrentDatabase
Set doc = New NotesDocument( db )
doc.Form = "Memo"
doc.SendTo = "John Doe"
doc.Subject = "Subject of this mail"
Call doc.Send( False ) |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #D | D | bool semiprime(long n) pure nothrow @safe @nogc {
auto nf = 0;
foreach (immutable i; 2 .. n + 1) {
while (n % i == 0) {
if (nf == 2)
return false;
nf++;
n /= i;
}
}
return nf == 2;
}
void main() {
import std.stdio;
foreach (... |
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
... | #ALGOL_W | ALGOL W | begin
% returns the check digit for the specified SEDOL %
string(1) procedure sedolCheckDigit ( string(6) value sedol ) ;
begin
integer checkSum, checkDigit;
checkSum := 0;
for cPos := 0 until 5 do begin
string(1) c;
integer digit;
c := sed... |
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 ... | #Common_Lisp | Common Lisp | (defun to-ascii (str) (mapcar #'char-code (coerce str 'list)))
(defun to-digits (n)
(mapcar #'(lambda(v) (- v 48)) (to-ascii (princ-to-string n))))
(defun count-digits (n)
(do
((counts (make-array '(10) :initial-contents '(0 0 0 0 0 0 0 0 0 0)))
(curlist (to-digits n) (cdr curlist)))
((null ... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Haskell | Haskell | import Control.Monad (forM_)
import Text.Printf
selfs :: [Integer]
selfs = sieve (sumFs [0..]) [0..]
where
sumFs = zipWith (+) [ a+b+c+d+e+f+g+h+i+j
| a <- [0..9] , b <- [0..9]
, c <- [0..9] , d <- [0..9]
, e <- [0..9] , f <- [0..9]
... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #PARI.2FGP | PARI/GP | set11(x,a,b)=select(x -> a <= x && x <= b, x);
set01(x,a,b)=select(x -> a < x && x <= b, x);
set10(x,a,b)=select(x -> a <= x && x < b, x);
set00(x,a,b)=select(x -> a < x && x < b, x);
V = [0, 1, 2];
setunion(set01(V, 0, 1), set10(V, 0, 2))
setintersect(set10(V, 0, 2), set01(V, 1, 2))
setminus(set10(V, 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... | #EDSAC_order_code | EDSAC order code |
[List of primes by trial division, for Rosetta Code website.]
[EDSAC program, Initial Orders 2.]
[Division is done implicitly by the use of wheels.
One wheel for each possible prime divisor, up to an editable limit.]
T51K [G parameter: print subroutine, 54 locations.]
P56F [must be ev... |
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... | #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
do
sequence (1, 27)
end
sequence (lower, upper: INTEGER)
-- Sequence of primes from 'lower' to 'upper'.
require
lower_positive: lower > 0
upper_positive: upper > 0
lower_smaller: lower < upper
local
i: INTEGER
do
io.put_string ("Seq... |
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.
| #Clojure | Clojure | ;; provides floor and sqrt, but we use Java's sqrt as it's faster
;; (Clojure's is more exact)
(use 'clojure.contrib.math)
(defn nonsqr [#^Integer n] (+ n (floor (+ 0.5 (Math/sqrt n)))))
(defn square? [#^Double n]
(let [r (floor (Math/sqrt n))]
(= (* r r) n)))
(doseq [n (range 1 23)] (printf "%s -> %s\n" 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.
| #CLU | CLU | non_square = proc (n: int) returns (int)
return(n + real$r2i(0.5 + real$i2r(n)**0.5))
end non_square
is_square = proc (n: int) returns (bool)
return(n = real$r2i(real$i2r(n)**0.5))
end is_square
start_up = proc()
po: stream := stream$primary_output()
for n: int in int$from_to(1, 22) do
str... |
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... | #Ceylon | Ceylon | shared void run() {
value a = set {1, 2, 3};
value b = set {3, 4, 5};
value union = a | b;
value intersection = a & b;
value difference = a ~ b;
value subset = a.subset(b);
value equality = a == b;
print("set a: ``a``
set b: ``b``
1 in a? ``... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program cribleEras.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a ... |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #PicoLisp | PicoLisp | (de consolidate (S)
(when S
(let R (cons (car S))
(for X (consolidate (cdr S))
(if (mmeq X (car R))
(set R (uniq (conc X (car R))))
(conc R (cons X)) ) )
R ) ) ) |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #PL.2FI | PL/I | Set: procedure options (main); /* 13 November 2013 */
declare set(20) character (200) varying;
declare e character (1);
declare (i, n) fixed binary;
set = '';
n = 1;
do until (e = ']');
get edit (e) (a(1)); put edit (e) (a(1));
if e = '}' then n = n + 1; /* end of set. */
if e ... |
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors | Sequence: smallest number with exactly n divisors | Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly... | #XPL0 | XPL0 | func Divisors(N); \Return number of divisors of N
int N, Count, D;
[Count:= 0;
for D:= 1 to N do
if rem(N/D) = 0 then Count:= Count+1;
return Count;
];
int N, AN;
[for N:= 1 to 15 do
[AN:= 0;
repeat AN:= AN+1 until Divisors(AN) = N;
IntOut(0, AN); ChOut(0, ^ );
];
] |
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors | Sequence: smallest number with exactly n divisors | Calculate the sequence where each term an is the smallest natural number that has exactly n divisors.
Task
Show here, on this page, at least the first 15 terms of the sequence.
Related tasks
Sequence: smallest number greater than previous term with exactly n divisors
Sequence: nth number with exactly... | #zkl | zkl | fcn countDivisors(n)
{ [1.. n.toFloat().sqrt()].reduce('wrap(s,i){ s + (if(0==n%i) 1 + (i!=n/i)) },0) }
A005179w:=(1).walker(*).tweak(fcn(n){
var N=0,cache=Dictionary();
if(cache.find(n)) return(cache.pop(n)); // prune
while(1){
if(n == (d:=countDivisors(N+=1))) return(N);
if(n<d and not cache.... |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #zkl | zkl | var MsgHash=Import("zklMsgHash");
MsgHash.SHA256("Rosetta code")=="764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf" |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #Smalltalk | Smalltalk | PackageLoader fileInPackage: 'Digest'.
(SHA1 hexDigestOf: 'Rosetta Code') displayNl. |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #Tcl | Tcl | package require sha1
puts [sha1::sha1 "Rosetta Code"] |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioin... | #Phix | Phix | with javascript_semantics
sequence ascii = {}
for ch=32 to 127 do
ascii = append(ascii,sprintf("%4d (#%02x): %c ",ch))
end for
puts(1,substitute(join_by(ascii,16,6),"\x7F","del"))
|
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:
*
* *
* *
* * * *
* *
* * * *
... | #Run_BASIC | Run BASIC | nOrder=4
dim xy$(40)
for i = 1 to 40
xy$(i) = " "
next i
call triangle 1, 1, nOrder
for i = 1 to 36
print xy$(i)
next i
end
SUB triangle x, y, n
IF n = 0 THEN
xy$(y) = left$(xy$(y),x-1) + "*" + mid$(xy$(y),x+1)
ELSE
n=n-1
length=2^n
call tr... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #PicoLisp | PicoLisp | (de carpet (N)
(let Carpet '("#")
(do N
(setq Carpet
(conc
(mapcar '((S) (pack S S S)) Carpet)
(mapcar
'((S) (pack S (replace (chop S) "#" " ") S))
Carpet )
(mapcar '((S) (pack S S S)) Carpet) ) ) ) ) )
(map... |
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 ... | #Crystal | Crystal | require "set"
UNIXDICT = File.read("unixdict.txt").lines
def word?(word : String)
UNIXDICT.includes?(word)
end
# is it a word and is it a word backwards?
semordnilap = UNIXDICT.select { |word| word?(word) && word?(word.reverse) }
# consolidate pairs like [bad, dab] == [dab, bad]
final_results = semordnilap.ma... |
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 ... | #D | D | void main() {
import std.stdio, std.file, std.string, std.algorithm;
bool[string] seenWords;
size_t pairCount = 0;
foreach (const word; "unixdict.txt".readText.toLower.splitter) {
//const drow = word.dup.reverse();
auto drow = word.dup;
drow.reverse();
if (drow in see... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Sather | Sather | class MAIN is
a(v:BOOL):BOOL is
#OUT + "executing a\n";
return v;
end;
b(v:BOOL):BOOL is
#OUT + "executing b\n";
return v;
end;
main is
x:BOOL;
x := a(false) and b(true);
#OUT + "F and T = " + x + "\n\n";
x := a(true) or b(true);
#OUT + "T or T = " + x + "\n\n";
... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Scala | Scala | object ShortCircuit {
def a(b:Boolean)={print("Called A=%5b".format(b));b}
def b(b:Boolean)={print(" -> B=%5b".format(b));b}
def main(args: Array[String]): Unit = {
val boolVals=List(false,true)
for(aa<-boolVals; bb<-boolVals){
print("\nTesting A=%5b AND B=%5b -> ".format(aa, bb))
... |
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... | #Lua | Lua | -- load the smtp support
local smtp = require("socket.smtp")
-- Connects to server "localhost" and sends a message to users
-- "fulano@example.com", "beltrano@example.com",
-- and "sicrano@example.com".
-- Note that "fulano" is the primary recipient, "beltrano" receives a
-- carbon copy and neither of them knows th... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SendMail["From" -> "from@email.com", "To" -> "to@email.com",
"Subject" -> "Sending Email from Mathematica", "Body" -> "Hello world!",
"Server" -> "smtp.email.com"] |
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... | #DCL | DCL | $ p1 = f$integer( p1 )
$ if p1 .lt. 2
$ then
$ write sys$output "out of range 2 thru 2^31-1"
$ exit
$ endif
$
$ close /nolog primes
$ on control_y then $ goto clean
$ open primes primes.txt
$
$ loop1:
$ read /end_of_file = prime primes prime
$ prime = f$integer( prime )
$ loop2:
$ t = p1 / prime
$ if t * 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
... | #AppleScript | AppleScript | on appendCheckDigitToSEDOL(sedol)
if ((count sedol) is not 6) then ¬
return {false, "Error in appendCheckDigitToSEDOL handler: " & sedol & " doesn't have 6 characters."}
set chars to "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set vowels to "AEIOU"
set weights to {1, 3, 1, 7, 3, 9}
set s to 0
... |
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 ... | #Crystal | Crystal | def self_describing?(n)
digits = n.to_s.chars.map(&.to_i) # 12345 => [1, 2, 3, 4, 5]
digits.each_with_index.all? { |digit, idx| digits.count(idx) == digit }
end
t = Time.monotonic
600_000_000.times { |n| (puts "#{n} in #{(Time.monotonic - t).total_seconds} secs";\
t = Time.monotoni... |
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 ... | #D | D | import std.stdio, std.algorithm, std.range, std.conv, std.string;
bool isSelfDescribing(in long n) pure nothrow @safe {
auto nu = n.text.representation.map!q{ a - '0' };
return nu.length.iota.map!(a => nu.count(a)).equal(nu);
}
void main() {
4_000_000.iota.filter!isSelfDescribing.writeln;
} |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Java | Java | public class SelfNumbers {
private static final int MC = 103 * 1000 * 10000 + 11 * 9 + 1;
private static final boolean[] SV = new boolean[MC + 1];
private static void sieve() {
int[] dS = new int[10_000];
for (int a = 9, i = 9999; a >= 0; a--) {
for (int b = 9; b >= 0; b--) {
... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #Perl | Perl | use utf8;
# numbers used as boundaries to real sets. Each has 3 components:
# the real value x;
# a +/-1 indicating if it's x + ϵ or x - ϵ
# a 0/1 indicating if it's the left border or right border
# e.g. "[1.5, ..." is written "1.5, -1, 0", while "..., 2)" is "2, -1, 1"
package BNum;
use overload (
'""' => \&_st... |
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... | #Elena | Elena | import extensions;
import system'routines;
import system'math;
isPrime =
(n => new Range(2,(n.sqrt() - 1).RoundedInt).allMatchedBy:(i => n.mod:i != 0));
Primes =
(n => new Range(2, n - 2).filterBy:isPrime);
public program()
{
console.printLine(Primes(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... | #Elixir | Elixir | defmodule Prime do
def sequence do
Stream.iterate(2, &(&1+1)) |> Stream.filter(&is_prime/1)
end
def is_prime(2), do: true
def is_prime(n) when n<2 or rem(n,2)==0, do: false
def is_prime(n), do: is_prime(n,3)
defp is_prime(n,k) when n<k*k, do: true
defp is_prime(n,k) when rem(n,k)==0, do: false
d... |
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. NONSQR.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 NEWTON.
03 SQR-INP PIC 9(7)V9(5).
03 SQUARE-ROOT PIC 9(7)V9(5).
03 FILLER REDEFINES SQUARE-ROOT.
05 FILLER PIC 9(7).
... |
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... | #Clojure | Clojure | (require 'clojure.set)
; sets can be created using the set method or set literal syntax
(def a (set [1 2 3 4]))
(def b #{4 5 6 7})
(a 10) ; returns the element if it's contained in the set, otherwise nil
(clojure.set/union a b)
(clojure.set/intersection a b)
(clojure.set/difference a b)
(clojure.set/subset?... |
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... | #Arturo | Arturo | sieve: function [upto][
composites: array.of: inc upto false
loop 2..to :integer sqrt upto 'x [
if not? composites\[x][
loop range.step: x x^2 upto 'c [
composites\[c]: true
]
]
]
result: new []
loop.with:'i composites 'c [
unless c -> ... |
http://rosettacode.org/wiki/Set_consolidation | Set consolidation | Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is:
The two input sets if no common item exists between the two input sets of items.
The single set that is the union of the two input sets if they share a common item... | #Python | Python | def consolidate(sets):
setlist = [s for s in sets if s]
for i, s1 in enumerate(setlist):
if s1:
for s2 in setlist[i+1:]:
intersection = s1.intersection(s2)
if intersection:
s2.update(s1)
s1.clear()
s1... |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #UNIX_Shell | UNIX Shell | $ echo -n 'ASCII string' | sha1
9e9aeefe5563845ec5c42c5630842048c0fc261b |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government... | #Vlang | Vlang | import crypto.sha1
fn main() {
println("${sha1.hexhash('Rosetta Code')}")//Rosetta code
mut h := sha1.new()
h.write('Rosetta Code'.bytes()) ?
println('${h.checksum().map(it.hex()).join('')}')
} |
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... | #PHP | PHP | <?php
echo '+' . str_repeat('----------+', 6), PHP_EOL;
for ($j = 0 ; $j < 16 ; $j++) {
for ($i = 0 ; $i < 6 ; $i++) {
$val = 32 + $i * 16 + $j;
switch ($val) {
case 32: $chr = 'Spc'; break;
case 127: $chr = 'Del'; break;
default: $chr = chr($val) ; ... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Rust | Rust |
use std::iter::repeat;
fn sierpinski(order: usize) {
let mut triangle = vec!["*".to_string()];
for i in 0..order {
let space = repeat(' ').take(2_usize.pow(i as u32)).collect::<String>();
// save original state
let mut d = triangle.clone();
// extend existing lines
... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #PL.2FI | PL/I |
/* Sierpinski carpet */
Sierpinski_carpet: procedure options (main); /* 28 January 2013 */
call carpet(3);
In_carpet: procedure (a, b) returns (bit(1));
declare (a, b) fixed binary nonassignable;
declare (x, y) fixed binary;
declare (true value ('1'b), false value ('0'b)) bit (1);
x = a ; y = b;
... |
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 ... | #Delphi | Delphi |
program Semordnilap;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
System.StrUtils,
System.Diagnostics;
function Sort(s: string): string;
var
c: Char;
i, j, aLength: Integer;
begin
aLength := s.Length;
if aLength = 0 then
exit('');
Result := s;
for i := 1 to a... |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Scheme | Scheme | >(define (a x)
(display "a\n")
x)
>(define (b x)
(display "b\n")
x)
>(for-each (lambda (i)
(for-each (lambda (j)
(display i) (display " and ") (display j) (newline)
(and (a i) (b j))
(display i) (display " or ") (display j) (newline)
(or (a i) (b j))
) '(#t #f))
) '(#t #f))
#t a... |
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... | #NewLISP | NewLISP | (module "smtp.lsp")
(SMTP:send-mail "user@asite.com" "somebody@isp.com" "Greetings" "How are you today? - john doe -" "smtp.asite.com" "user" "password") |
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... | #Nim | Nim | import smtp
proc sendMail(fromAddr: string; toAddrs, ccAddrs: seq[string];
subject, message, login, password: string;
server = "smtp.gmail.com"; port = Port 465; ssl = true) =
let msg = createMessage(subject, message, toAddrs, ccAddrs)
let session = newSmtp(useSsl = ssl, debug = true)
... |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #EchoLisp | EchoLisp |
(lib 'math)
(define (semi-prime? n)
(= (length (prime-factors n)) 2))
(for ((i 100))
(when (semi-prime? i) (write i)))
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
(lib 'bigint)
(define N (* (random-prime 10000000) (random-prime 10000000)))
→ 676... |
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
... | #Arturo | Arturo | ord0: to :integer `0`
ord7: to :integer `7`
c2v: function [c][
ordC: to :integer c
if? c < `A` -> return ordC - ord0
else -> return ordC - ord7
]
weight: [1 3 1 7 3 9]
checksum: function [sedol][
val: new 0
loop .with:'i sedol 'ch ->
'val + weight\[i] * c2v ch
return to :char ord0 + ... |
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 ... | #Elixir | Elixir | defmodule Self_describing do
def number(n) do
digits = Integer.digits(n)
Enum.map(0..length(digits)-1, fn s ->
length(Enum.filter(digits, fn c -> c==s end))
end) == digits
end
end
m = 3300000
Enum.filter(0..m, fn n -> Self_describing.number(n) 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 ... | #Erlang | Erlang |
sdn(N) -> lists:map(fun(S)->length(lists:filter(fun(C)->C-$0==S end,N))+$0 end,lists:seq(0,length(N)-1))==N.
gen(M) -> lists:filter(fun(N)->sdn(integer_to_list(N)) end,lists:seq(0,M)).
|
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #jq | jq |
def sumdigits: tostring | explode | map([.]|implode|tonumber) | add;
def gsum: . + sumdigits;
def isnonself:
def ndigits: tostring|length;
. as $i
| ($i - ($i|ndigits)*9) as $n
| any( range($i-1; [0,$n]|max; -1);
gsum == $i);
# an array
def last81:
[limit(81; range(1; infinite) | select(isno... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Julia | Julia | gsum(i) = sum(digits(i)) + i
isnonself(i) = any(x -> gsum(x) == i, i-1:-1:i-max(1, ndigits(i)*9))
const last81 = filter(isnonself, 1:5000)[1:81]
function checkselfnumbers()
i, selfcount = 1, 0
while selfcount <= 100_000_000 && i <= 1022727208
if !(i in last81)
selfcount += 1
if... |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #Kotlin | Kotlin | private const val MC = 103 * 1000 * 10000 + 11 * 9 + 1
private val SV = BooleanArray(MC + 1)
private fun sieve() {
val dS = IntArray(10000)
run {
var a = 9
var i = 9999
while (a >= 0) {
for (b in 9 downTo 0) {
var c = 9
val s = a + b
... |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #Phix | Phix | with javascript_semantics
enum ID,ARGS
function cf(sequence f, atom x) return call_func(f[ID],deep_copy(f[ARGS])&x) end function
function Union(sequence a, b, atom x) return cf(a,x) or cf(b,x) end function
function Inter(sequence a, b, atom x) return cf(a,x) and cf(b,x) end function
function Diffr(sequence 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... | #ERRE | ERRE |
PROGRAM PRIME_GENERATOR
!$DOUBLE
BEGIN
PRINT(CHR$(12);) !CLS
N=1
LOOP
N+=1
FOR F=2 TO N DO
IF F=N THEN PRINT(N;) EXIT END IF
EXIT IF N=F*INT(N/F)
END FOR
END LOOP
END PROGRAM
|
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... | #F.23 | F# |
(*
Nigel Galloway April 7th., 2017.
*)
let SofE =
let rec fg ng = seq{
let n = Seq.item 0 ng
yield n; yield! fg (Seq.cache(Seq.filter (fun g->g%n<>0) (Seq.skip 1 ng)))}
fg (Seq.initInfinite(id)|>Seq.skip 2)
|
http://rosettacode.org/wiki/Sequence_of_non-squares | Sequence of non-squares | Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
| #CoffeeScript | CoffeeScript |
non_square = (n) -> n + Math.floor(1/2 + Math.sqrt(n))
is_square = (n) ->
r = Math.floor(Math.sqrt(n))
r * r is n
do ->
first_22_non_squares = (non_square i for i in [1..22])
console.log first_22_non_squares
# test is_square has no false negatives:
for i in [1..10000]
throw Error("is_square brok... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.