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/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 ... | #Forth | Forth |
wordlist constant dict
: load-dict ( c-addr u -- )
r/o open-file throw >r
begin
pad 1024 r@ read-line throw while
pad swap ['] create execute-parsing
repeat
drop r> close-file throw ;
: xreverse {: c-addr u -- c-addr2 u :}
u allocate throw u + c-addr swap over u + >r begin ( from to r:en... |
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... | #Tcl | Tcl | package require Tcl 8.5
proc tcl::mathfunc::a boolean {
puts "a($boolean) called"
return $boolean
}
proc tcl::mathfunc::b boolean {
puts "b($boolean) called"
return $boolean
}
foreach i {false true} {
foreach j {false true} {
set x [expr {a($i) && b($j)}]
puts "x = a($i) && b($j) =... |
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... | #TXR | TXR | @(define a (x out))
@ (output)
a (@x) called
@ (end)
@ (bind out x)
@(end)
@(define b (x out))
@ (output)
b (@x) called
@ (end)
@ (bind out x)
@(end)
@(define short_circuit_demo (i j))
@ (output)
a(@i) and b(@j):
@ (end)
@ (maybe)
@ (a i "1")
@ (b j "1")
@ (end)
@ (output)
a(@i) or b(@j):
@ (end)
... |
http://rosettacode.org/wiki/Send_email | Send email | Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or f... | #Python | Python | import smtplib
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message,
login, password,
smtpserver='smtp.gmail.com:587'):
header = 'From: %s\n' % from_addr
header += 'To: %s\n' % ','.join(to_addr_list)
header += 'Cc: %s\n' % ','.join(cc_addr_list)
... |
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... | #R | R | library(RDCOMClient)
send.mail <- function(to, title, body) {
olMailItem <- 0
ol <- COMCreate("Outlook.Application")
msg <- ol$CreateItem(olMailItem)
msg[["To"]] <- to
msg[["Subject"]] <- title
msg[["Body"]] <- body
msg$Send()
ol$Quit()
}
send.mail("somebody@somewhere", "Title", "Hello") |
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... | #Haskell | Haskell | isSemiprime :: Int -> Bool
isSemiprime n = (length factors) == 2 && (product factors) == n ||
(length factors) == 1 && (head factors) ^ 2 == n
where factors = primeFactors 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... | #Icon_and_Unicon | Icon and Unicon | link "factors"
procedure main(A)
every nf := semiprime(n := !A) do write(n," = ",nf[1]," * ",nf[2])
end
procedure semiprime(n) # Succeeds and produces the factors only if n is semiprime.
return (2 = *(nf := factors(n)), nf)
end |
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
... | #C.23 | C# | static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 };
static int sedolChecksum(string sedol)
{
int len = sedol.Length;
int sum = 0;
if (len == 7) //SEDOL code already checksummed?
return (int)sedol[6];
if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeio... |
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 ... | #J | J | digits =: 10&#.^:_1
counts =: _1 + [: #/.~ i.@:# , ]
selfdesc =: = counts&.digits"0 NB. Note use of "under" |
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 ... | #Java | Java | public class SelfDescribingNumbers{
public static boolean isSelfDescribing(int a){
String s = Integer.toString(a);
for(int i = 0; i < s.length(); i++){
String s0 = s.charAt(i) + "";
int b = Integer.parseInt(s0); // number of times i-th digit must occur for it to be a self des... |
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... | #REXX | REXX | /*REXX program displays N self numbers (aka Colombian or Devlali numbers). OEIS A3052.*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/
tell = n>0; n= abs(n) ... |
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... | #Ring | Ring |
load "stdlib.ring"
see "working..." + nl
see "The first 50 self numbers are:" + nl
n = 0
num = 0
limit = 51
limit2 = 10000000
while true
n = n + 1
for m = 1 to n
flag = 1
sum = 0
strnum = string(m)
for p = 1 to len(strnum)
sum = sum + number(strnum[p])
... |
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 | ... | #Rust | Rust | #[derive(Debug)]
enum SetOperation {
Union,
Intersection,
Difference,
}
#[derive(Debug, PartialEq)]
enum RangeType {
Inclusive,
Exclusive,
}
#[derive(Debug)]
struct CompositeSet<'a> {
operation: SetOperation,
a: &'a RealSet<'a>,
b: &'a RealSet<'a>,
}
#[derive(Debug)]
struct RangeSe... |
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 | ... | #Tcl | Tcl | package require Tcl 8.5
proc inRange {x range} {
lassign $range a aClosed b bClosed
expr {($aClosed ? $a<=$x : $a<$x) && ($bClosed ? $x<=$b : $x<$b)}
}
proc normalize {A} {
set A [lsort -index 0 -real [lsort -index 1 -integer -decreasing $A]]
for {set i 0} {$i < [llength $A]} {incr i} {
lassign [lind... |
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... | #Haskell | Haskell | [n | n <- [2..], []==[i | i <- [2..n-1], rem n i == 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... | #J | J | primTrial=:3 :0
try=. i.&.(p:inv) %: >./ y
candidate=. (y>1)*y=<.y
y #~ candidate*(y e.try) = +/ 0= try|/ y
) |
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.
| #Euphoria | Euphoria | function nonsqr( atom n)
return n + floor( 0.5 + sqrt( n ) )
end function
puts( 1, " n r(n)\n" )
puts( 1, "--- ---\n" )
for i = 1 to 22 do
printf( 1, "%3d %3d\n", { i, nonsqr(i) } )
end for
atom j
atom found
found = 0
for i = 1 to 1000000 do
j = sqrt(nonsqr(i))
if integer(j) then
found =... |
http://rosettacode.org/wiki/Set | Set |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an... | #EchoLisp | EchoLisp |
; use { } to read a set
(define A { 1 2 3 4 3 5 5}) → { 1 2 3 4 5 } ; duplicates are removed from a set
; or use make-set to make a set from a list
(define B (make-set ' ( 3 4 5 6 7 8 8))) → { 3 4 5 6 7 8 }
(set-intersect A B) → { 3 4 5 }
(set-intersect? A B) → #t ; predicate
(set-union A B) → { 1 2 3 4 5 6 7 8 }
(se... |
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... | #Batch_File | Batch File | :: Sieve of Eratosthenes for Rosetta Code - PG
@echo off
setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEEXTENSIONS
rem echo on
set /p n=limit:
rem set n=100
for /L %%i in (1,1,%n%) do set crible.%%i=1
for /L %%i in (2,1,%n%) do (
if !crible.%%i! EQU 1 (
set /A w = %%i * 2
for /L %%j in (!w!,%%i,%n%) do (
... |
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... | #Tcl | Tcl | package require struct::set
proc consolidate {sets} {
if {[llength $sets] < 2} {
return $sets
}
set r [list {}]
set r0 [lindex $sets 0]
foreach x [consolidate [lrange $sets 1 end]] {
if {[struct::set size [struct::set intersect $x $r0]]} {
struct::set add r0 $x
} else {
lappend r $x... |
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... | #Quackery | Quackery |
[ dup 32 = iff
[ drop say 'spc' ] done
dup 127 = iff
[ drop say 'del' ] done
emit sp sp ] is echoascii ( n --> )
[ dup echo say ': '
dup echoascii
84 < 3 + times sp ] is echoelt ( n --> )
[ sp 81 times
[ dup i^ + echoelt 16 step ]
dro... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Tcl | Tcl | package require Tcl 8.5
proc map {lambda list} {
foreach elem $list {
lappend result [apply $lambda $elem]
}
return $result
}
proc sierpinski_triangle n {
set down [list *]
set space " "
for {set i 1} {$i <= $n} {incr i} {
set down [concat \
[map [subst -nocommand... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Python | Python | def in_carpet(x, y):
while True:
if x == 0 or y == 0:
return True
elif x % 3 == 1 and y % 3 == 1:
return False
x /= 3
y /= 3
def carpet(n):
for i in xrange(3 ** n):
for j in xrange(3 ** n):
if in_carpet(i, j):
print ... |
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 ... | #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 21:50:08
!
!a=./F && make $a && $a < unixdict.txt
!f95 -Wall -ffree-form F.F -o F
! 5 of 158 semordnilaps
!yaw
!room
!xi
!tim ... |
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... | #UNIX_Shell | UNIX Shell | a() {
echo "Called a $1"
"$1"
}
b() {
echo "Called b $1"
"$1"
}
for i in false true; do
for j in false true; do
a $i && b $j && x=true || x=false
echo " $i && $j is $x"
a $i || b $j && y=true || y=false
echo " $i || $j is $y"
done
done |
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... | #Racket | Racket |
#lang racket
;; using sendmail:
(require net/sendmail)
(send-mail-message
"sender@somewhere.com" "Some Subject"
'("recipient@elsewhere.com" "recipient2@elsewhere.com")
'("cc@elsewhere.com")
'("bcc@elsewhere.com")
(list "Some lines of text" "go here."))
;; and using smtp (and adding more headers here):
(requi... |
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... | #Raku | Raku | use Email::Simple;
my $to = 'mail@example.com';
my $from = 'me@example.com';
my $subject = 'test';
my $body = 'This is a test.';
my $email = Email::Simple.create(
:header[['To', $to], ['From', $from], ['Subject', $subject]],
:body($body)
);
say ~$email;
# Note that the following will fail wit... |
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... | #J | J | isSemiPrime=: 2 = #@q: ::0:"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... | #Java | Java | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class SemiPrime{
private static final BigInteger TWO = BigInteger.valueOf(2);
public static List<BigInteger> primeDecomp(BigInteger a){
// impossible for values lower than 2
if(a.compareTo(TWO) < 0){
return 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
... | #C.2B.2B | C++ |
#include <numeric>
#include <cctype>
#include <iostream>
#include <string>
template<typename result_sink_t>
auto sedol_checksum(std::string const& sedol, result_sink_t result_sink)
{
if(sedol.size() != 6)
return result_sink(0, "length of sedol string != 6");
const char * valid_chars = "BCDFGHJK... |
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 ... | #JavaScript | JavaScript | function is_self_describing(n) {
var digits = Number(n).toString().split("").map(function(elem) {return Number(elem)});
var len = digits.length;
var count = digits.map(function(x){return 0});
digits.forEach(function(digit, idx, ary) {
if (digit >= count.length)
return false
... |
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... | #Sidef | Sidef | func is_self_number(n) {
if (n < 30) {
return (((n < 10) && (n.is_odd)) || (n == 20))
}
var qd = (1 + n.ilog10)
var r = (1 + (n-1)%9)
var h = (r + 9*(r%2))/2
var ld = 10
while (h + 9*qd >= n%ld) {
ld *= 10
}
var vs = idiv(n, ld).sumdigits
n %= ld
0... |
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 | ... | #Wren | Wren | import "/dynamic" for Enum
var RangeType = Enum.create("RangeType", ["CLOSED", "BOTH_OPEN", "LEFT_OPEN", "RIGHT_OPEN"])
class RealSet {
construct new(start, end, pred) {
_low = start
_high = end
_pred = (pred == RangeType.CLOSED) ? Fn.new { |d| d >= _low && d <= _high } :
... |
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... | #Java | Java | import java.util.stream.IntStream;
public class Test {
static IntStream getPrimes(int start, int end) {
return IntStream.rangeClosed(start, end).filter(n -> isPrime(n));
}
public static boolean isPrime(long x) {
if (x < 3 || x % 2 == 0)
return x == 2;
long max = (... |
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... | #jq | jq | # Produce a (possibly empty) stream of primes in the range [m,n], i.e. m <= p <= n
def primes(m; n):
([m,2] | max) as $m
| if $m > n then empty
elif $m == 2 then 2, primes(3;n)
else (1 + (2 * range($m/2 | floor; (n + 1) /2 | floor))) | select( is_prime )
end; |
http://rosettacode.org/wiki/Sequence_of_non-squares | Sequence of non-squares | Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
| #F.23 | F# | open System
let SequenceOfNonSquares =
let nonsqr n = n+(int(0.5+Math.Sqrt(float (n))))
let isqrt n = int(Math.Sqrt(float(n)))
let IsSquare n = n = (isqrt n)*(isqrt n)
{1 .. 999999}
|> Seq.map(fun f -> (f, nonsqr f))
|> Seq.filter(fun f -> IsSquare(snd f))
;; |
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.
| #Factor | Factor | USING: kernel math math.functions math.ranges prettyprint
sequences ;
: non-sq ( n -- m ) dup sqrt 1/2 + floor + >integer ;
: print-first22 ( -- ) 22 [1,b] [ non-sq ] map . ;
: check-for-sq ( -- ) 1,000,000 [1,b)
[ non-sq sqrt dup floor = [ "Square found." throw ] when ]
each ;
print-first22 check-for-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... | #Elixir | Elixir | iex(1)> s = MapSet.new
#MapSet<[]>
iex(2)> sa = MapSet.put(s, :a)
#MapSet<[:a]>
iex(3)> sab = MapSet.put(sa, :b)
#MapSet<[:a, :b]>
iex(4)> sbc = Enum.into([:b, :c], MapSet.new)
#MapSet<[:b, :c]>
iex(5)> MapSet.member?(sab, :a)
true
iex(6)> MapSet.member?(sab, :c)
false
iex(7)> :a in sab
true
iex(8)> MapSet.union(sab, 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... | #BBC_BASIC | BBC BASIC | limit% = 100000
DIM sieve% limit%
prime% = 2
WHILE prime%^2 < limit%
FOR I% = prime%*2 TO limit% STEP prime%
sieve%?I% = 1
NEXT
REPEAT prime% += 1 : UNTIL sieve%?prime%=0
ENDWHILE
REM Display the primes:
FOR I% = 1 TO limit%
IF siev... |
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... | #TXR | TXR | (defun mkset (p x) (set [p x] (or [p x] x)))
(defun fnd (p x) (if (eq [p x] x) x (fnd p [p x])))
(defun uni (p x y)
(let ((xr (fnd p x)) (yr (fnd p y)))
(set [p xr] yr)))
(defun consoli (sets)
(let ((p (hash)))
(each ((s sets))
(each ((e s))
(mkset p e)
(uni p e (car s))))
(h... |
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... | #VBA | VBA | Private Function has_intersection(set1 As Collection, set2 As Collection) As Boolean
For Each element In set1
On Error Resume Next
tmp = set2(element)
If tmp = element Then
has_intersection = True
Exit Function
End If
Next element
End Function
Private Sub ... |
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... | #R | R | chr <- function(n) {
rawToChar(as.raw(n))
}
idx <- 32
while (idx < 128) {
for (i in 0:5) {
num <- idx + i
if (num<100) cat(" ")
cat(num,": ")
if (num == 32) { cat("Spc "); next }
if (num == 127) { cat("Del "); next }
cat(chr(num)," ")
}
idx <- idx + 6
cat("\n")
} |
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:
*
* *
* *
* * * *
* *
* * * *
... | #TI-83_BASIC | TI-83 BASIC | PROGRAM:SIRPNSKI
:ClrHome
:Output(1,8,"^")
:{0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}→L1
:{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}→L2
:L2→L3
:For(X,2,8,1)
:For(Y,2,17,1)
:If L1(Y-1)
:Then
:4→N
:End
:If L1(Y)
:Then
:N+2→N
:End
:If L1(Y+1)
:Then
:N+1→N
:End
:If N=1 or N=3 or N=4 or N=6
:Then
:1→L2(Y)
:Output(X,Y-1,"^")
:End
:0→N
:End
:... |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #QB64 | QB64 | _Title "Sierpinski Carpet"
Screen _NewImage(500, 545, 8)
Cls , 15: Color 1, 15
'labels
_PrintString (96, 8), "Order 0"
_PrintString (345, 8), "Order 1"
_PrintString (96, 280), "Order 3"
_PrintString (345, 280), "Order 4"
'carpets
Call carpet(5, 20, 243, 0)
Call carpet(253, 20, 243, 1)
Call carpet(5, 293, 243, 2)
... |
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 ... | #FreeBASIC | FreeBASIC | ' version 20-06-2015
' compile with: fbc -s console
Function reverse(norm As String) As String
Dim As String rev
Dim As Integer i, l = Len(norm) -1
rev = norm
For i = 0 To l
rev[l-i] = norm[i]
Next
Return rev
End Function
' ------=< MAIN >=------
Dim As Integer i, j, count,... |
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... | #VBA | VBA | Private Function a(i As Variant) As Boolean
Debug.Print "a: "; i = 1,
a = i
End Function
Private Function b(j As Variant) As Boolean
Debug.Print "b: "; j = 1;
b = j
End Function
Public Sub short_circuit()
Dim x As Boolean, y As Boolean
'Dim p As Boolean, q As Boolean
Debug.Print "=====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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function A(v As Boolean) As Boolean
Console.WriteLine("a")
Return v
End Function
Function B(v As Boolean) As Boolean
Console.WriteLine("b")
Return v
End Function
Sub Test(i As Boolean, j As Boolean)
Console.WriteLine("{0} and {1} = {2} (ea... |
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... | #REBOL | REBOL | send user@host.dom "My 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... | #REXX | REXX |
load "stdlib.ring"
See "Send email..." + nl
sendemail("smtp://smtp.gmail.com",
"calmosoft@gmail.com",
"password",
"calmosoft@gmail.com",
"calmosoft@gmail.com",
"calmosoft@gmail.com",
"Sending email from Ring",
"Hello
How are you?
... |
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... | #Ring | Ring |
load "stdlib.ring"
See "Send email..." + nl
sendemail("smtp://smtp.gmail.com",
"calmosoft@gmail.com",
"password",
"calmosoft@gmail.com",
"calmosoft@gmail.com",
"calmosoft@gmail.com",
"Sending email from Ring",
"Hello
How are you?
... |
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... | #jq | jq |
# Output: a stream of proper factors (probably unsorted)
def proper_factors:
range(2; 1 + sqrt|floor) as $i
| if (. % $i) == 0
then (. / $i) as $r
| if $i == $r then $i else $i, $r end
else empty
end;
def is_semiprime:
. as $n
| any(proper_factors;
is_prime and (($n / .) | (. == $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... | #Julia | Julia | using Primes
issemiprime(n::Integer) = sum(values(factor(n))) == 2
@show filter(issemiprime, 1:100) |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class Utils.Check [ Abstract ]
{
ClassMethod SEDOL(x As %String) As %Boolean
{
// https://en.wikipedia.org/wiki/SEDOL
IF x'?1(7N,1U5UN1N) QUIT 0
IF x'=$TRANSLATE(x,"AEIOU") QUIT 0
SET cd=$EXTRACT(x,*), x=$EXTRACT(x,1,*-1)
SET wgt="1317391", t=0
FOR i=1:1:$LENGTH(x) {
SET n=$EXTRACT(x,i)
IF n'=+n SET n=$ASCI... |
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
... | #Clojure | Clojure | (defn sedols [xs]
(letfn [(sedol [ys] (let [weights [1 3 1 7 3 9]
convtonum (map #(Character/getNumericValue %) ys)
check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))]
(str ys check)))]
(map #(sedol %) xs))... |
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 ... | #jq | jq | # If your jq includes all/2 then comment out the following definition,
# which is slightly less efficient:
def all(generator; condition):
reduce generator as $i (true; if . then $i | condition else . 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 ... | #Julia | Julia | function selfie(x::Integer)
ds = reverse(digits(x))
if sum(ds) != length(ds) return false end
for (i, d) in enumerate(ds)
if d != sum(ds .== i - 1) return false end
end
return true
end
@show selfie(2020)
@show selfie(2021)
selfies(x) = for i in 1:x selfie(i) && println(i) end
@time selfies(4000000) |
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... | #Standard_ML | Standard ML |
open List;
val rec selfNumberNr = fn NR =>
let
val rec sumdgt = fn 0 => 0 | n => Int.rem (n, 10) + sumdgt (Int.quot(n ,10));
val rec isSelf = fn ([],l1,l2) => []
| (x::tt,l1,l2) => if exists (fn i=>i=x) l1 orelse exists (fn i=>i=x) l2
then ( isSelf (tt,l1,l2)) else x::isSelf (tt,l1,l2) ;
val rec pa... |
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... | #Wren | Wren | var sieve = Fn.new {
var sv = List.filled(2*1e9+9*9+1, false)
var n = 0
var s = [0] * 8
for (a in 0..1) {
for (b in 0..9) {
s[0] = a + b
for (c in 0..9) {
s[1] = s[0] + c
for (d in 0..9) {
s[2] = s[1] + d ... |
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 | ... | #zkl | zkl | class RealSet{
fcn init(fx){ var [const] contains=fx; }
fcn holds(x){ contains(x) }
fcn __opAdd(rs){ RealSet('wrap(x){ contains(x) or rs.contains(x) }) }
fcn __opSub(rs){ RealSet('wrap(x){ contains(x) and not rs.contains(x) }) }
fcn intersection(rs) { RealSet('wrap(x){ contains(x) and rs.contains(x) }) }... |
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... | #Julia | Julia | struct TDPrimes{T<:Integer}
uplim::T
end
Base.start{T<:Integer}(pl::TDPrimes{T}) = 2ones(T, 1)
Base.done{T<:Integer}(pl::TDPrimes{T}, p::Vector{T}) = p[end] > pl.uplim
function Base.next{T<:Integer}(pl::TDPrimes{T}, p::Vector{T})
pr = npr = p[end]
ispr = false
while !ispr
npr += 1
ispr... |
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... | #Kotlin | Kotlin | // version 1.0.6
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
... |
http://rosettacode.org/wiki/Sequence_of_non-squares | Sequence of non-squares | Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
| #Fantom | Fantom |
class Main
{
static Float fn (Int n)
{
n + (0.5f + (n * 1.0f).sqrt).floor
}
static Bool isSquare (Float n)
{
n.sqrt.floor == n.sqrt
}
public static Void main ()
{
(1..22).each |n|
{
echo ("$n is ${fn(n)}")
}
echo ((1..1000000).toList.any |n| { isSquare (fn(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.
| #Forth | Forth | : u>f 0 d>f ;
: f>u f>d drop ;
: fn ( n -- n ) dup u>f fsqrt fround f>u + ;
: test ( n -- ) 1 do i fn . loop ;
23 test \ 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 ok
: square? ( n -- ? ) u>f fsqrt fdup fround f- f0= ;
: test ( n -- ) 1 do i fn square? if cr i . ." fn was square" then loop ... |
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... | #Erlang | Erlang | 2> S = sets:new().
3> Sa = sets:add_element(a, S).
4> Sab = sets:from_list([a, b]).
5> sets:is_element(a, Sa).
true
6> Union = sets:union(Sa, Sab).
7> sets:to_list(Union).
[a,b]
8> Intersection = sets:intersection(Sa, Sab).
9> sets:to_list(Intersection).
[a]
10> Subtract = sets:subtract(Sab, Sa).
11> sets:to_list(Subtr... |
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... | #BCPL | BCPL | get "libhdr"
manifest $( LIMIT = 1000 $)
let sieve(prime,max) be
$( let i = 2
0!prime := false
1!prime := false
for i = 2 to max do i!prime := true
while i*i <= max do
$( if i!prime do
$( let j = i*i
while j <= max do
$( j!prime := false
j := j... |
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... | #VBScript | VBScript |
Function consolidate(s)
sets = Split(s,",")
n = UBound(sets)
For i = 1 To n
p = i
ts = ""
For j = i To 1 Step -1
If ts = "" Then
p = j
End If
ts = ""
For k = 1 To Len(sets(p))
If InStr(1,sets(j-1),Mid(sets(p),k,1)) = 0 Then
ts = ts & Mid(sets(p),k,1)
End If
Next
If Len(ts)... |
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... | #Wren | Wren | import "/set" for Set
var consolidateSets = Fn.new { |sets|
var size = sets.count
var consolidated = List.filled(size, false)
var i = 0
while (i < size - 1) {
if (!consolidated[i]) {
while (true) {
var intersects = 0
for (j in i+1...size) {
... |
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... | #Racket | Racket | #lang racket
(for ([i (in-range 16)])
(for ([j (in-range 6)])
(define n (+ 32 (* j 16) i))
(printf "~a : ~a"
(~a n #:align 'right #:min-width 3)
(~a (match n
[32 "SPC"]
[127 "DEL"]
[_ (integer->char n)]) #:min-width 5)))
(newlin... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #uBasic.2F4tH | uBasic/4tH | Input "Triangle order: ";n
n = 2^n
For y = n - 1 To 0 Step -1
For i = 0 To y
Print " ";
Next
x = 0
For x = 0 Step 1 While ((x + y) < n)
If AND (x,y) Then
Print " ";
Else
Print "* ";
EndIf
Next
Print
Next
End |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Quackery | Quackery | [ over 3 mod 1 = ] is 1? ( n1 n2 --> n1 n2 f )
[ 3 / swap ] is 3/ ( n1 n2 --> n2/3 n1 )
[ true unrot
[ 2dup or while
1? 1? and iff
[ rot not unrot ] done
3/ 3/ again ]
2drop ] is incarpet ( n --> )
[... |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Go | Go | package main
import (
"fmt"
"io/ioutil"
"log"
"strings"
)
func main() {
// read file into memory as one big block
data, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal(err)
}
// copy the block, split it up into words
words := strings.Split(string(data... |
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... | #Visual_FoxPro | Visual FoxPro |
*!* Visual FoxPro natively supports short circuit evaluation
CLEAR
CREATE CURSOR funceval(arg1 L, arg2 L, operation V(3), result L, calls V(10))
*!* Conjunction
INSERT INTO funceval (arg1, arg2, operation) VALUES (.F., .F., "AND")
REPLACE result WITH (a(arg1) AND b(arg2))
INSERT INTO funceval (arg1, arg2, operation) ... |
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... | #Wren | Wren | var a = Fn.new { |bool|
System.print(" a called")
return bool
}
var b = Fn.new { |bool|
System.print(" b called")
return bool
}
var bools = [ [true, true], [true, false], [false, true], [false, false] ]
for (bool in bools) {
System.print("a = %(bool[0]), b = %(bool[1]), op = && :")
a.call... |
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... | #Ruby | Ruby | require 'base64'
require 'net/smtp'
require 'tmail'
require 'mime/types'
class Email
def initialize(from, to, subject, body, options={})
@opts = {:attachments => [], :server => 'localhost'}.update(options)
@msg = TMail::Mail.new
@msg.from = from
@msg.to = to
@msg.subject = subject
@m... |
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... | #Kotlin | Kotlin | // version 1.1.2
fun isSemiPrime(n: Int): Boolean {
var nf = 0
var nn = n
for (i in 2..nn)
while (nn % i == 0) {
if (nf == 2) return false
nf++
nn /= i
}
return nf == 2
}
fun main(args: Array<String>) {
for (v in 1675..1680)
println("$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
... | #COBOL | COBOL | >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. sedol.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT sedol-file ASSIGN "sedol.txt"
ORGANIZATION LINE SEQUENTIAL
FILE STATUS sedol-file-status.
DATA DIVISION.
FILE SECTION.
FD sedol-file.
01 sedol ... |
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 ... | #K | K | sdn: {n~+/'n=/:!#n:0$'$x}'
sdn 1210 2020 2121 21200 3211000 42101000
1 1 0 1 1 1
&sdn@!:1e6
1210 2020 21200 |
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 ... | #Kotlin | Kotlin | // version 1.0.6
fun selfDescribing(n: Int): Boolean {
if (n <= 0) return false
val ns = n.toString()
val count = IntArray(10)
var nn = n
while (nn > 0) {
count[nn % 10] += 1
nn /= 10
}
for (i in 0 until ns.length)
if( ns[i] - '0' != count[i]) return false
retu... |
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... | #Lambdatalk | Lambdatalk |
{def prime
{def prime.rec
{lambda {:m :n}
{if {> {* :m :m} :n}
then :n
else {if {= {% :n :m} 0}
then
else {prime.rec {+ :m 1} :n} }}}}
{lambda {:n}
{prime.rec 2 :n} }}
{map prime {serie 3 100 2}}
-> 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
{map pri... |
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.
| #Fortran | Fortran | PROGRAM NONSQUARES
IMPLICIT NONE
INTEGER :: m, n, nonsqr
DO n = 1, 22
nonsqr = n + FLOOR(0.5 + SQRT(REAL(n))) ! or could use NINT(SQRT(REAL(n)))
WRITE(*,*) nonsqr
END DO
DO n = 1, 1000000
nonsqr = n + FLOOR(0.5 + SQRT(REAL(n)))
m = INT(SQRT(REAL(nonsqr)))
IF (m*m == nonsqr) THEN... |
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... | #F.23 | F# | [<EntryPoint>]
let main args =
// Create some sets (of int):
let s1 = Set.ofList [1;2;3;4;3]
let s2 = Set.ofArray [|3;4;5;6|]
printfn "Some sets (of int):"
printfn "s1 = %A" s1
printfn "s2 = %A" s2
printfn "Set operations:"
printfn "2 ∈ s1? %A" (s1.Contains 2)
printfn "10 ∈ s1? %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... | #Befunge | Befunge | 2>:3g" "-!v\ g30 <
|!`"O":+1_:.:03p>03g+:"O"`|
@ ^ p3\" ":<
2 234567890123456789012345678901234567890123456789012345678901234567890123456789
|
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... | #zkl | zkl | fcn consolidate(sets){ // set are munged if they are read/write
if(sets.len()<2) return(sets);
r,r0 := List(List()),sets[0];
foreach x in (consolidate(sets[1,*])){
i,ni:=x.filter22(r0.holds); //-->(intersection, !intersection)
if(i) r0=r0.extend(ni);
else r.append(x);
}
r[0]=r0;
r
... |
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... | #Raku | Raku | sub glyph ($_) {
when * < 33 { (0x2400 + $_).chr } # display symbol names for invisible glyphs
when 127 { '␡' }
default { .chr }
}
say '{|class="wikitable" style="text-align:center;background-color:hsl(39, 90%, 95%)"';
for (^128).rotor(16) -> @row {
say '|-';
printf(q[|%d<br>0x%02X<br><bi... |
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:
*
* *
* *
* * * *
* *
* * * *
... | #Unlambda | Unlambda | ```ci``s``s`ks``s`k`s``s`kc``s``s``si`kr`k. `k.*k
`k``s``s``s``s`s`k`s``s`ksk`k``s``si`kk`k``s`kkk
`k``s`k`s``si`kk``s`kk``s``s``s``si`kk`k`s`k`s``s`ksk`k`s`k`s`k`si``si`k`ki
`k``s`k`s``si`k`ki``s`kk``s``s``s``si`kk`k`s`k`s`k`si`k`s`k`s``s`ksk``si`k`ki
`k`ki``s`k`s`k`si``s`kkk |
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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #R | R |
## Are x,y inside Sierpinski carpet (and where)? (1-yes, 0-no)
inSC <- function(x, y) {
while(TRUE) {
if(!x||!y) {return(1)}
if(x%%3==1&&y%%3==1) {return(0)}
x=x%/%3; y=y%/%3;
} return(0);
}
## Plotting Sierpinski carpet fractal. aev 4/1/17
## ord - order, fn - file name, ttl - plot title, clr - color... |
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 ... | #Groovy | Groovy | def semordnilapWords(source) {
def words = [] as Set
def semordnilaps = []
source.eachLine { word ->
if (words.contains(word.reverse())) semordnilaps << word
words << word
}
semordnilaps
} |
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... | #zkl | zkl | fcn a(b){self.fcn.println(b); b}
fcn b(b){self.fcn.println(b); b} |
http://rosettacode.org/wiki/Send_email | Send email | Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or f... | #SAS | SAS | filename msg email
to="afriend@someserver.com"
cc="anotherfriend@somecompany.com"
subject="Important message"
;
data _null_;
file msg;
put "Hello, Connected World!";
run; |
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... | #Scala | Scala | import java.util.Properties
import javax.mail.internet.{ InternetAddress, MimeMessage }
import javax.mail.Message.RecipientType
import javax.mail.{ Session, Transport }
/** Mail constructor.
* @constructor Mail
* @param host Host
*/
class Mail(host: String) {
val session = Session.getDefaultInstance(new Prop... |
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... | #Ksh | Ksh |
#!/bin/ksh
# Semiprime - As translated from C
# # Variables:
#
# # Functions:
#
# Function _issemiprime(p2) - return 1 if p2 semiprime, 0 if not
#
function _issemiprime {
typeset _p2 ; integer _p2=$1
typeset _p _f ; integer _p _f=0
for ((_p=2; (_f<2 && _p*_p<=_p2); _p++)); do
while (( _p2 % _p == 0 )); d... |
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... | #Lingo | Lingo | on isSemiPrime (n)
div = 2
cnt = 0
repeat while cnt < 3 and n <> 1
if n mod div = 0 then
n = n / div
cnt = cnt + 1
else
div = div + 1
end if
end repeat
return cnt=2
end |
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
... | #Common_Lisp | Common Lisp | (defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6)))
(assert (<= 0 start end (length sedol)))
(assert (= (- end start) 6))
(loop
:with checksum = 0
:for weight :in '(1 3 1 7 3 9)
:for index :upfrom start
:do (incf checksum (* weight (digit-char-p (char sedol index)... |
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 ... | #Liberty_BASIC | Liberty BASIC | 'adapted from BASIC solution
FOR x = 1 TO 5000000
a$ = TRIM$(STR$(x))
b = LEN(a$)
FOR c = 1 TO b
d$ = MID$(a$, c, 1)
v(VAL(d$)) = v(VAL(d$)) + 1
w(c - 1) = VAL(d$)
NEXT c
r = 0
FOR n = 0 TO 10
IF v(n) = w(n) THEN r = r + 1
v(n) = 0
w(n) = 0
NEXT n
IF r = 11 TH... |
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... | #Liberty_BASIC | Liberty BASIC |
print "Rosetta Code - Sequence of primes by trial division"
print: print "Prime numbers between 1 and 50"
for x=1 to 50
if isPrime(x) then print x
next x
[start]
input "Enter an integer: "; x
if x=0 then print "Program complete.": end
if isPrime(x) then print x; " is prime" else print x; " is not prime"
goto [sta... |
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... | #Lua | Lua | -- Returns true if x is prime, and false otherwise
function isprime (x)
if x < 2 then return false end
if x < 4 then return true end
if x % 2 == 0 then return false end
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
-- Returns table of prime numbe... |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function nonSquare (n As UInteger) As UInteger
Return CUInt(n + Int(0.5 + Sqr(n)))
End Function
Function isSquare (n As UInteger) As Boolean
Dim As UInteger r = CUInt(Sqr(n))
Return n = r * r
End Function
Print "The first 22 numbers generated by the sequence are :"
For i As Integer = 1 To ... |
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... | #Factor | Factor | ( scratchpad ) USE: sets
( scratchpad ) HS{ 2 5 4 3 } HS{ 5 6 7 } union .
HS{ 2 3 4 5 6 7 }
( scratchpad ) HS{ 2 5 4 3 } HS{ 5 6 7 } intersect .
HS{ 5 }
( scratchpad ) HS{ 2 5 4 3 } HS{ 5 6 7 } diff .
HS{ 2 3 4 }
( scratchpad ) HS{ 2 5 4 3 } HS{ 5 6 7 } subset? .
f
( scratchpad ) HS{ 5 6 } HS{ 5 6 7 } subset? .
t
( scr... |
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... | #BQN | BQN | Primes ← {
𝕩≤2 ? ↕0 ; # No primes below 2
p ← 𝕊⌈√n←𝕩 # Initial primes by recursion
b ← 2≤↕n # Initial sieve: no 0 or 1
E ← {↕∘⌈⌾((𝕩×𝕩+⊢)⁼)n} # Multiples of 𝕩 under n, starting at 𝕩×𝕩
/ b E⊸{0¨⌾(𝕨⊸⊏)𝕩}´ p # Cross them out
} |
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... | #Red | Red | Red ["ASCII table"]
repeat i 16 [
repeat j 6 [
n: j - 1 * 16 + i + 31
prin append pad/left n 3 ": "
prin pad switch/default n [
32 ["spc"]
127 ["del"]
] [to-char n] 4
]
prin newline
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.