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/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #Nim | Nim |
import complex
var a: Complex = (1.0,1.0)
var b: Complex = (3.1415,1.2)
echo("a : " & $a)
echo("b : " & $b)
echo("a + b: " & $(a + b))
echo("a * b: " & $(a * b))
echo("1/a : " & $(1/a))
echo("-a : " & $(-a))
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #Oberon-2 | Oberon-2 |
MODULE Complex;
IMPORT Files,Out;
TYPE
Complex* = POINTER TO ComplexDesc;
ComplexDesc = RECORD
r-,i-: REAL;
END;
PROCEDURE (CONST x: Complex) Add*(CONST y: Complex): Complex;
BEGIN
RETURN New(x.r + y.r,x.i + y.i)
END Add;
PROCEDURE (CONST x: Complex) Sub*(CONST y: C... |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Fur... | #Perl | Perl | use bigrat;
foreach my $candidate (2 .. 2**19) {
my $sum = 1 / $candidate;
foreach my $factor (2 .. sqrt($candidate)+1) {
if ($candidate % $factor == 0) {
$sum += 1 / $factor + 1 / ($candidate / $factor);
}
}
if ($sum->denominator() == 1) {
print "Sum of recipr. fac... |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Relation | Relation |
function agm(x,y)
set a = x
set g = y
while abs(a - g) > 0.00000000001
set an = (a + g)/2
set gn = sqrt(a * g)
set a = an
set g = gn
set i = i + 1
end while
set result = g
end function
set x = 1
set y = 1/sqrt(2)
echo (x + y)/2
echo sqrt(x+y)
echo agm(x,y)
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #REXX | REXX | /*REXX program calculates the AGM (arithmetic─geometric mean) of two (real) numbers. */
parse arg a b digs . /*obtain optional numbers from the C.L.*/
if digs=='' | digs=="," then digs= 120 /*No DIGS specified? Then use default.*/
numeric digits digs ... |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #EchoLisp | EchoLisp |
;; trying the 16 combinations
;; all return the integer 1
(lib 'bigint)
(define zeroes '(integer: 0 inexact=float: 0.000 complex: 0+0i bignum: #0))
(for* ((z1 zeroes) (z2 zeroes)) (write (expt z1 z2)))
→ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Eiffel | Eiffel | print (0^0) |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The ... | #Pascal | Pascal | sub ev
# Evaluates an arithmetic expression like "(1+3)*7" and returns
# its value.
{my $exp = shift;
# Delete all meaningless characters. (Scientific notation,
# infinity, and not-a-number aren't supported.)
$exp =~ tr {0-9.+-/*()} {}cd;
return ev_ast(astize($exp));}
{my $balanced_paren_regex;
$balanced_... |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like bin... | #C.23 | C# | using System;
using System.Text;
namespace ZeckendorfArithmetic {
class Zeckendorf : IComparable<Zeckendorf> {
private static readonly string[] dig = { "00", "01", "10" };
private static readonly string[] dig1 = { "", "1", "10" };
private int dVal = 0;
private int dLen = 0;
... |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ... | #C.2B.2B | C++ | #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <numeric>
using namespace std;
// Returns n in binary right justified with length passed and padded with zeroes
const uint* binary(uint n, uint length);
// Returns the sum of the binary ordered subset of rank r... |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #Alore | Alore | def Main()
var len as Int
var result as Str
result = Str(5**4**3**2)
len = result.length()
Print(len)
Print(result[:20])
Print(result[len-20:])
end |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #Arturo | Arturo | num: to :string 5^4^3^2
print [first.n: 20 num ".." last.n: 20 num "=>" size num "digits"] |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
#################... | #Go | Go | package main
import (
"bytes"
"fmt"
"strings"
)
var in = `
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011... |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, ... | #CLU | CLU | % Get list of distinct Fibonacci numbers up to N
fibonacci = proc (n: int) returns (array[int])
list: array[int] := array[int]$[]
a: int := 1
b: int := 2
while a <= n do
array[int]$addh(list,a)
a, b := b, a+b
end
return(list)
end fibonacci
% Find the Zeckendorf representation o... |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Befunge | Befunge | >"d">:00p1-:>:::9%\9/9+g2%!\:9v
$.v_^#!$::$_^#`"c":+g00p+9/9\%<
::<_@#`$:\*:+55:+1p27g1g+9/9\%9
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available,... | #Dyalect | Dyalect | //Dyalect supports dynamic arrays
var empty = []
var xs = [1, 2, 3]
//Add elements to an array
empty.Add(0)
empty.AddRange(xs)
//Access array elements
var x = xs[2]
xs[2] = x * x |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #OCaml | OCaml | open Complex
let print_complex z =
Printf.printf "%f + %f i\n" z.re z.im
let () =
let a = { re = 1.0; im = 1.0 }
and b = { re = 3.14159; im = 1.25 } in
print_complex (add a b);
print_complex (mul a b);
print_complex (inv a);
print_complex (neg a);
print_complex (conj a) |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Fur... | #Phix | Phix | with javascript_semantics
without warning -- (several unused routines in this code)
constant NUM = 1, DEN = 2
type frac(object r)
return sequence(r) and length(r)=2 and integer(r[NUM]) and integer(r[DEN])
end type
function normalise(object n, atom d=0)
if sequence(n) then
{n,d} = n
end if
... |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Ring | Ring |
decimals(9)
see agm(1, 1/sqrt(2)) + nl
see agm(1,1/pow(2,0.5)) + nl
func agm agm,g
while agm
an = (agm + g)/2
gn = sqrt(agm*g)
if fabs(agm-g) <= fabs(an-gn) exit ok
agm = an
g = gn
end
return gn
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Ruby | Ruby | # The flt package (http://flt.rubyforge.org/) is useful for high-precision floating-point math.
# It lets us control 'context' of numbers, individually or collectively -- including precision
# (which adjusts the context's value of epsilon accordingly).
require 'flt'
include Flt
BinNum.Context.precision = 512 # def... |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Elena | Elena | import extensions;
public program()
{
console.printLine("0^0 is ",0.power:0)
} |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Elixir | Elixir |
:math.pow(0,0)
|
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The ... | #Perl | Perl | sub ev
# Evaluates an arithmetic expression like "(1+3)*7" and returns
# its value.
{my $exp = shift;
# Delete all meaningless characters. (Scientific notation,
# infinity, and not-a-number aren't supported.)
$exp =~ tr {0-9.+-/*()} {}cd;
return ev_ast(astize($exp));}
{my $balanced_paren_regex;
$balanced_... |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like bin... | #C.2B.2B | C++ | // For a class N which implements Zeckendorf numbers:
// I define an increment operation ++()
// I define a comparison operation <=(other N)
// I define an addition operation +=(other N)
// I define a subtraction operation -=(other N)
// Nigel Galloway October 28th., 2012
#include <iostream>
enum class zd {N00,N01,N10,... |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ... | #D | D | import std.algorithm;
import std.stdio;
int[] getDivisors(int n) {
auto divs = [1, n];
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
divs ~= i;
int j = n / i;
if (i != j) {
divs ~= j;
}
}
}
return divs;
}
bool i... |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #bc | bc | /* 5432.bc */
y = 5 ^ 4 ^ 3 ^ 2
c = length(y)
" First 20 digits: "; y / (10 ^ (c - 20))
" Last 20 digits: "; y % (10 ^ 20)
"Number of digits: "; c
quit |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #Bracmat | Bracmat | {?} @(5^4^3^2:?first [20 ? [-21 ?last [?length)&str$(!first "..." !last "\nlength " !length)
{!} 62060698786608744707...92256259918212890625
length 183231
S 2,46 sec |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
#################... | #Groovy | Groovy | def zhangSuen(text) {
def image = text.split('\n').collect { line -> line.collect { it == '#' ? 1 : 0} }
def p2, p3, p4, p5, p6, p7, p8, p9
def step1 = { (p2 * p4 * p6 == 0) && (p4 * p6 * p8 == 0) }
def step2 = { (p2 * p4 * p8 == 0) && (p2 * p6 * p8 == 0) }
def reduce = { step ->
def toWhite... |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, ... | #Common_Lisp | Common Lisp | (defun zeckendorf (n)
"returns zeckendorf integer of n (see OEIS A003714)"
(let ((fib '(2 1)))
;; extend Fibonacci sequence long enough
(loop while (<= (car fib) n) do
(push (+ (car fib) (cadr fib)) fib))
(loop with r = 0 for f in fib do
(setf r (* 2 r))
(when (>= n f) (setf n (- n f))
... |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Blade | Blade | var doors = [false] * 100
for i in 0..100 {
iter var j = i; j < 100; j += i + 1 {
doors[j] = !doors[j]
}
var state = doors[i] ? 'open' : 'closed'
echo 'Door ${i + 1} is ${state}'
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available,... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | #create a new list
local :l []
#add something to it
push-to l "Hi"
#add something else to it
push-to l "Boo"
#the list could also have been built up this way:
local :l2 [ "Hi" "Boo" ]
#this prints 2
!print len l
#this prints Hi
!print get-from l 0
#this prints Boo
!print pop-from l
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #Octave | Octave | z1 = 1.5 + 3i;
z2 = 1.5 + 1.5i;
disp(z1 + z2); % 3.0 + 4.5i
disp(z1 - z2); % 0.0 + 1.5i
disp(z1 * z2); % -2.25 + 6.75i
disp(z1 / z2); % 1.5 + 0.5i
disp(-z1); % -1.5 - 3i
disp(z1'); % 1.5 - 3i
disp(abs(z1)); % 3.3541 = sqrt(z1*z1')
disp(z1 ^ z2); % -1.10248 - 0.38306i
disp( exp(z1) ); % ... |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Fur... | #PicoLisp | PicoLisp | (load "@lib/frac.l")
(for (N 2 (> (** 2 19) N) (inc N))
(let (Sum (frac 1 N) Lim (sqrt N))
(for (F 2 (>= Lim F) (inc F))
(when (=0 (% N F))
(setq Sum
(f+ Sum
(f+ (frac 1 F) (frac 1 (/ N F))) ) ) ) )
(when (= 1 (cdr Sum))
(prinl
... |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Run_BASIC | Run BASIC | print agm(1, 1/sqr(2))
print agm(1,1/2^.5)
print using("#.############################",agm(1, 1/sqr(2)))
function agm(agm,g)
while agm
an = (agm + g)/2
gn = sqr(agm*g)
if abs(agm-g) <= abs(an-gn) then exit while
agm = an
g = gn
wend
end function |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Rust | Rust | // Accepts two command line arguments
// cargo run --name agm arg1 arg2
fn main () {
let mut args = std::env::args();
let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap();
let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap();
let resul... |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Emacs_Lisp | Emacs Lisp | (expt 0 0) |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #ERRE | ERRE |
.....
PRINT(0^0)
.....
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #F.23 | F# | > let z = 0.**0.;;
val z : float = 1.0 |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, gi... | #11l | 11l | F zigzag(n)
F compare(xy)
V (x, y) = xy
R (x + y, I (x + y) % 2 {-y} E y)
V xs = 0 .< n
R Dict(enumerate(sorted((multiloop(xs, xs, (x, y) -> (x, y))), key' compare)), (n, index) -> (index, n))
F printzz(myarray)
V n = Int(myarray.len ^ 0.5 + 0.5)
V xs = 0 .< n
print((xs.map(y -> @xs.map(... |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The ... | #Phix | Phix | -- demo\rosetta\Arithmetic_evaluation.exw
with javascript_semantics
sequence opstack = {} -- atom elements are literals,
-- sequence elements are subexpressions
-- on completion length(opstack) should be 1
object token
constant op_p_p = 1 -- 1: ex... |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like bin... | #D | D | import std.stdio;
int inv(int a) {
return a ^ -1;
}
class Zeckendorf {
private int dVal;
private int dLen;
private void a(int n) {
auto i = n;
while (true) {
if (dLen < i) dLen = i;
auto j = (dVal >> (i * 2)) & 3;
switch(j) {
case... |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ... | #F.23 | F# |
// Zumkeller numbers: Nigel Galloway. May 16th., 2021
let rec fG n g=match g with h::_ when h>=n->h=n |h::t->fG n t || fG(n-h) t |_->false
let fN g=function n when n&&&1=1->false
|n->let e=n/2-g in match compare e 0 with 0->true
|1->let l=[1..... |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #C | C | #include <gmp.h>
#include <stdio.h>
#include <string.h>
int main()
{
mpz_t a;
mpz_init_set_ui(a, 5);
mpz_pow_ui(a, a, 1 << 18); /* 2**18 == 4**9 */
int len = mpz_sizeinbase(a, 10);
printf("GMP says size is: %d\n", len);
/* because GMP may report size 1 too big; see doc */
char *s = mpz_get_str(0, 10, a);
... |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #C.23 | C# | using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
static class Program {
static void Main() {
BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));
string result = n.ToString();
Debug.Assert(result.Length == 183231);
... |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
#################... | #Haskell | Haskell | import Data.Array
import qualified Data.List as List
data BW = Black | White
deriving (Eq, Show)
type Index = (Int, Int)
type BWArray = Array Index BW
toBW :: Char -> BW
toBW '0' = White
toBW '1' = Black
toBW ' ' = White
toBW '#' = Black
toBW _ = error "toBW: illegal char"
toBWArray :: [String] -> BWA... |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, ... | #Cowgol | Cowgol | include "cowgol.coh";
sub zeckendorf(n: uint32, buf: [uint8]): (r: [uint8]) is
var fibs: uint32[] := {
0,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,
2584,4181,6765,10946,17711,28657,46368,75025,121393,
196418,317811,514229,832040,1346269,2178309,3524578,
5702887,9227465,1493... |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #BlitzMax | BlitzMax | Graphics 640,480
i=1
While ((i*i)<=100)
a$=i*i
DrawText a$,10,20*i
Print i*i
i=i+1
Wend
Flip
WaitKey |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available,... | #E | E | ? def empty := []
# value: []
? def numbers := [1,2,3,4,5]
# value: [1, 2, 3, 4, 5]
? numbers.with(6)
# value: [1, 2, 3, 4, 5, 6]
? numbers + [4,3,2,1]
# value: [1, 2, 3, 4, 5, 4, 3, 2, 1] |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #Oforth | Oforth | Object Class new: Complex(re, im)
Complex method: re @re ;
Complex method: im @im ;
Complex method: initialize := im := re ;
Complex method: << '(' <<c @re << ',' <<c @im << ')' <<c ;
0 1 Complex new const: I
Complex method: ==(c -- b )
c re @re == c im @im == and ;
Complex method: norm -- f
@r... |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #Ol | Ol |
(define A 0+1i) ; manually entered numbers
(define B 1+0i)
(print (+ A B))
; <== 1+i
(print (- A B))
; <== -1+i
(print (* A B))
; <== 0+i
(print (/ A B))
; <== 0+i
(define C (complex 2/7 -3)) ; functional way
(print "real part of " C " is " (car C))
; <== real part of 2/7-3i is 2/7
(print "imaginary p... |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Fur... | #PL.2FI | PL/I | *process source attributes xref or(!);
arat: Proc Options(main);
/*--------------------------------------------------------------------
* Rational Arithmetic
* (Mis)use the Complex data type to represent fractions
* real(x) is used as numerator
* imag(x) is used as denominator
* Output:
* a=-3/7 b=9/2
* a*b=-2... |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Scala | Scala |
def agm(a: Double, g: Double, eps: Double): Double = {
if (math.abs(a - g) < eps) (a + g) / 2
else agm((a + g) / 2, math.sqrt(a * g), eps)
}
agm(1, math.sqrt(2)/2, 1e-15)
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Scheme | Scheme |
(define agm
(case-lambda
((a0 g0) ; call again with default value for tolerance
(agm a0 g0 1e-8))
((a0 g0 tolerance) ; called with three arguments
(do ((a a0 (* (+ a g) 1/2))
(g g0 (sqrt (* a g))))
((< (abs (- a g)) tolerance) a)))))
(display (agm 1 (/ 1 (sqrt 2)))) (newline)
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Factor | Factor | USING: math.functions.private ; ! ^complex
0 0 ^
C{ 0 0 } C{ 0 0 } ^complex |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Falcon | Falcon |
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
x = 0
y = 0
z = x**y
> "z=", z
|
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, gi... | #360_Assembly | 360 Assembly | * Zig-zag matrix 15/08/2015
ZIGZAGMA CSECT
USING ZIGZAGMA,R12 set base register
LR R12,R15 establish addressability
LA R9,N n : matrix size
LA R6,1 i=1
LA R7,1 j=1
LR ... |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural n... | #11l | 11l | T YellowstoneGenerator
min_ = 1
n_ = 0
n1_ = 0
n2_ = 0
Set[Int] sequence_
F next()
.n2_ = .n1_
.n1_ = .n_
I .n_ < 3
.n_++
E
.n_ = .min_
L !(.n_ !C .sequence_ & gcd(.n1_, .n_) == 1 & gcd(.n2_, .n_) > 1)
.n_++
.sequence_.add(.n_)
... |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The ... | #Picat | Picat | main =>
print("Enter an expression: "),
Str = read_line(),
Exp = parse_term(Str),
Res is Exp,
printf("Result = %w\n", Res).
|
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The ... | #PicoLisp | PicoLisp | (de ast (Str)
(let *L (str Str "")
(aggregate) ) )
(de aggregate ()
(let X (product)
(while (member (car *L) '("+" "-"))
(setq X (list (intern (pop '*L)) X (product))) )
X ) )
(de product ()
(let X (term)
(while (member (car *L) '("*" "/"))
(setq X (list (intern (p... |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like bin... | #Elena | Elena | import extensions;
const dig = new string[]{"00","01","10"};
const dig1 = new string[]{"","1","10"};
sealed struct ZeckendorfNumber
{
int dVal;
int dLen;
clone()
= ZeckendorfNumber.newInternal(dVal,dLen);
cast n(string s)
{
int i := s.Length - 1;
int q := 1;
... |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like bin... | #Go | Go | package main
import (
"fmt"
"strings"
)
var (
dig = [3]string{"00", "01", "10"}
dig1 = [3]string{"", "1", "10"}
)
type Zeckendorf struct{ dVal, dLen int }
func NewZeck(x string) *Zeckendorf {
z := new(Zeckendorf)
if x == "" {
x = "0"
}
q := 1
i := len(x) - 1
z.dL... |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ... | #Factor | Factor | USING: combinators grouping io kernel lists lists.lazy math
math.primes.factors memoize prettyprint sequences ;
MEMO: psum? ( seq n -- ? )
{
{ [ dup zero? ] [ 2drop t ] }
{ [ over length zero? ] [ 2drop f ] }
{ [ over last over > ] [ [ but-last ] dip psum? ] }
[
[ [ but... |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ... | #Go | Go | package main
import "fmt"
func getDivisors(n int) []int {
divs := []int{1, n}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs = append(divs, j)
}
}
}
return divs
}
func sum(... |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #C.2B.2B | C++ | #include <iostream>
#include <boost/multiprecision/gmp.hpp>
#include <string>
namespace mp = boost::multiprecision;
int main(int argc, char const *argv[])
{
// We could just use (1 << 18) instead of tmpres, but let's point out one
// pecularity with gmp and hence boost::multiprecision: they won't accept
... |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #Ceylon | Ceylon | import ceylon.whole {
wholeNumber,
two
}
shared void run() {
value five = wholeNumber(5);
value four = wholeNumber(4);
value three = wholeNumber(3);
value bigNumber = five ^ four ^ three ^ two;
value firstTwenty = "62060698786608744707";
value lastTwenty = "92256259918212890625"... |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
#################... | #J | J | isBlackPx=: '1'&=;._2 NB. boolean array of black pixels
toImage=: [: , LF ,.~ '01' {~ ] NB. convert to original representation
frameImg=: 0 ,. 0 , >:@$ {. ] NB. adds border of 0's to image
neighbrs=: 1 :'(1 1 ,: 3 3)&(u;._3)' NB. applies verb u to neighbourhoods
Bdry=: 1 2 5 8 7 6 3 0 1 ... |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, ... | #Crystal | Crystal | def zeckendorf(n)
return 0 if n.zero?
fib = [1, 2]
while fib[-1] < n; fib << fib[-2] + fib[-1] end
digit = ""
fib.reverse_each do |f|
if f <= n
digit, n = digit + "1", n - f
else
digit += "0"
end
end
digit.to_i
end
(0..20).each { |i| puts "%3d: %8d" % [i, zeckendorf(i)] } |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #BlooP | BlooP |
DEFINE PROCEDURE ''DIVIDE'' [A,B]:
BLOCK 0: BEGIN
IF A < B, THEN:
QUIT BLOCK 0;
CELL(0) <= 1;
OUTPUT <= 1;
LOOP AT MOST A TIMES:
BLOCK 2: BEGIN
IF OUTPUT * B = A, THEN:
QUIT BLOCK 0;
OUTPUT <= OUTPUT + 1;
IF OUTPUT * B > A, THEN:
BLOCK 3: BEGIN
OUTPUT <= CELL(0);
QUIT BLO... |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available,... | #EasyLang | EasyLang | len f[] 3
for i range len f[]
f[i] = i
.
f[] &= 3
for i range len f[]
print f[i]
. |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #ooRexx | ooRexx | c1 = .complex~new(1, 2)
c2 = .complex~new(3, 4)
r = 7
say "c1 =" c1
say "c2 =" c2
say "r =" r
say "-c1 =" (-c1)
say "c1 + r =" c1 + r
say "c1 + c2 =" c1 + c2
say "c1 - r =" c1 - r
say "c1 - c2 =" c1 - c2
say "c1 * r =" c1 * r
say "c1 * c2 =" c1 ... |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Fur... | #Prolog | Prolog |
divisor(N, Div) :-
Max is floor(sqrt(N)),
between(1, Max, D),
divmod(N, D, _, 0),
(Div = D; Div is N div D, Div =\= D).
divisors(N, Divs) :-
setof(M, divisor(N, M), Divs).
recip(A, B) :- B is 1 rdiv A.
sumrecip(N, A) :-
divisors(N, [1 | Ds]),
maplist(recip, Ds, As),
sum_list(As, ... |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const func float: agm (in var float: a, in var float: g) is func
result
var float: agm is 0.0;
local
const float: iota is 1.0E-7;
var float: a1 is 0.0;
var float: g1 is 0.0;
begin
if a * g < 0.0 then
raise RANGE_ERR... |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #SequenceL | SequenceL | import <Utilities/Math.sl>;
agm(a, g) :=
let
iota := 1.0e-15;
arithmeticMean := 0.5 * (a + g);
geometricMean := sqrt(a * g);
in
a when abs(a-g) < iota
else
agm(arithmeticMean, geometricMean);
main := agm(1.0, 1.0 / sqrt(2)); |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Fermat | Fermat | 0^0 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Forth | Forth | 0e 0e f** f. |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, gi... | #Action.21 | Action! | DEFINE MAX_SIZE="10"
DEFINE MAX_MATRIX_SIZE="100"
INT FUNC Index(BYTE size,x,y)
RETURN (x+y*size)
PROC PrintMatrix(BYTE ARRAY a BYTE size)
BYTE i,j,v
FOR j=0 TO size-1
DO
FOR i=0 TO size-1
DO
v=a(Index(size,i,j))
IF v<10 THEN
Print(" ")
ELSE
Print(" ")
FI
... |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural n... | #Action.21 | Action! | BYTE FUNC Gcd(BYTE a,b)
BYTE tmp
IF a<b THEN
tmp=a a=b b=tmp
FI
WHILE b#0
DO
tmp=a MOD b
a=b b=tmp
OD
RETURN (a)
BYTE FUNC Contains(BYTE ARRAY a BYTE len,value)
BYTE i
FOR i=0 TO len-1
DO
IF a(i)=value THEN
RETURN (1)
FI
OD
RETURN (0)
PROC Generate(BYTE ARRAY seq ... |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural n... | #Ada | Ada | with Ada.Text_IO;
with Ada.Containers.Ordered_Sets;
procedure Yellowstone_Sequence is
generic -- Allow more than one generator, but must be instantiated
package Yellowstones is
function Next return Integer;
function GCD (Left, Right : Integer) return Integer;
end Yellowstones;
package bo... |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The ... | #Pop11 | Pop11 | /* Scanner routines */
/* Uncomment the following to parse data from standard input
vars itemrep;
incharitem(charin) -> itemrep;
*/
;;; Current symbol
vars sym;
define get_sym();
itemrep() -> sym;
enddefine;
define expect(x);
lvars x;
if x /= sym then
printf(x, 'Error, expected %p\n');
... |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The ... | #Prolog | Prolog | % Lexer
numeric(X) :- 48 =< X, X =< 57.
not_numeric(X) :- 48 > X ; X > 57.
lex1([], []).
lex1([40|Xs], ['('|Ys]) :- lex1(Xs, Ys).
lex1([41|Xs], [')'|Ys]) :- lex1(Xs, Ys).
lex1([43|Xs], ['+'|Ys]) :- lex1(Xs, Ys).
lex1([45|Xs], ['-'|Ys]) :- lex1(Xs, Ys).
lex1([42|Xs], ['*'|Ys]) :- lex1(Xs, Ys).
lex1([47|Xs], [... |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like bin... | #Haskell | Haskell | {-# LANGUAGE LambdaCase #-}
import Data.List (find, mapAccumL)
import Control.Arrow (first, second)
-- Generalized Fibonacci series defined for any Num instance, and for Zeckendorf numbers as well.
-- Used to build Zeckendorf tables.
fibs :: Num a => a -> a -> [a]
fibs a b = res
where
res = a : b : zipWith (+)... |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ... | #Haskell | Haskell | import Data.List (group, sort)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes (primeFactors)
-------------------- ZUMKELLER NUMBERS -------------------
isZumkeller :: Int -> Bool
isZumkeller n =
let ds = divisors n
m = sum ds
in ( even m
&& let half = div m 2
in elem... |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #Clojure | Clojure | (defn exp [n k] (reduce * (repeat k n)))
(def big (->> 2 (exp 3) (exp 4) (exp 5)))
(def sbig (str big))
(assert (= "62060698786608744707" (.substring sbig 0 20)))
(assert (= "92256259918212890625" (.substring sbig (- (count sbig) 20))))
(println (count sbig) "digits")
(println (str (.substring sbig 0 20) ".."
... |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #CLU | CLU | start_up = proc ()
% Get bigint versions of 5, 4, 3 and 2
five: bigint := bigint$i2bi(5)
four: bigint := bigint$i2bi(4)
three: bigint := bigint$i2bi(3)
two: bigint := bigint$i2bi(2)
% Calculate 5**4**3**2
huge_no: bigint := five ** four ** three ** two
% Turn answer into string
h... |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
#################... | #Java | Java | import java.awt.Point;
import java.util.*;
public class ZhangSuen {
final static String[] image = {
" ",
" ################# ############# ",
" ################## ################ ",
... |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, ... | #D | D | import std.stdio, std.range, std.algorithm, std.functional;
void main() {
size_t
.max
.iota
.filter!q{ !(a & (a >> 1)) }
.take(21)
.binaryReverseArgs!writefln("%(%b\n%)");
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Bracmat | Bracmat | ( 100doors-tbl
= door step
. tbl$(doors.101) { Create an array. Indexing is 0-based. Add one extra for addressing element nr. 100 }
& 0:?step
& whl
' ( 1+!step:~>100:?step { ~> means 'not greater than', i.e. 'less than or equal' }
& 0:?door
& whl
' ( !step+!door:~>100... |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available,... | #EGL | EGL |
array int[10]; //optionally, add a braced list of values. E.g. array int[10]{1, 2, 3};
array[1] = 42;
SysLib.writeStdout(array[1]);
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #OxygenBasic | OxygenBasic |
'COMPLEX OPERATIONS
'=================
type tcomplex double x,y
class Complex
'============
has tcomplex
static sys i,pp
static tcomplex accum[32]
def operands
tcomplex*a,*b
@a=@accum+i
if pp then
@b=@a+sizeof accum
pp=0
else
@b=@this
end if
end def
method "load"()
operands
a... |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #PARI.2FGP | PARI/GP | add(a,b)=a+b;
mult(a,b)=a*b;
neg(a)=-a;
inv(a)=1/a; |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Fur... | #Python | Python | from fractions import Fraction
for candidate in range(2, 2**19):
sum = Fraction(1, candidate)
for factor in range(2, int(candidate**0.5)+1):
if candidate % factor == 0:
sum += Fraction(1, factor) + Fraction(1, candidate // factor)
if sum.denominator == 1:
print("Sum of recipr. factors of %d = %d e... |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Sidef | Sidef | func agm(a, g) {
loop {
var (a1, g1) = ((a+g)/2, sqrt(a*g))
[a1,g1] == [a,g] && return a
(a, g) = (a1, g1)
}
}
say agm(1, 1/sqrt(2)) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Sinclair_ZX81_BASIC | Sinclair ZX81 BASIC | 10 LET A=1
20 LET G=1/SQR 2
30 GOSUB 100
40 PRINT AGM
50 STOP
100 LET A0=A
110 LET A=(A+G)/2
120 LET G=SQR (A0*G)
130 IF ABS(A-G)>.00000001 THEN GOTO 100
140 LET AGM=A
150 RETURN |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Fortran | Fortran |
program zero
double precision :: i, j
double complex :: z1, z2
i = 0.0D0
j = 0.0D0
z1 = (0.0D0,0.0D0)
z2 = (0.0D0,0.0D0)
write(*,*) 'When integers are used, we have 0^0 = ', 0**0
write(*,*) 'When double precision numbers are used, we have 0.0^0.0 = ', i**j
write(*,*) 'When complex numbers are used, we have (0.0+0.0i)... |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Print "0 ^ 0 ="; 0 ^ 0
Sleep |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, gi... | #ActionScript | ActionScript |
package
{
public class ZigZagMatrix extends Array
{
private var height:uint;
private var width:uint;
public var mtx:Array = [];
public function ZigZagMatrix(size:uint)
{
this.height = size;
this.width = size;
this.mtx = [];
for (var i:uint... |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural n... | #ALGOL_68 | ALGOL 68 | BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the #
# subsequent members are the lowest number coprime to the previous one #
# and not coprime to the one before that, that haven't appeared in the #
# sequence yet #
... |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The ... | #Python | Python | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval... |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like bin... | #Java | Java | import java.util.List;
public class Zeckendorf implements Comparable<Zeckendorf> {
private static List<String> dig = List.of("00", "01", "10");
private static List<String> dig1 = List.of("", "1", "10");
private String x;
private int dVal = 0;
private int dLen = 0;
public Zeckendorf() {
... |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ... | #Java | Java |
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ZumkellerNumbers {
public static void main(String[] args) {
int n = 1;
System.out.printf("First 220 Zumkeller numbers:%n");
for ( int count = 1 ; count <= 220 ; n += 1 ) {
if ( isZ... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.