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/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
... | #COBOL | COBOL | identification division.
program-id. arbitrary-precision-integers.
remarks. Uses opaque libgmp internals that are built into libcob.
data division.
working-storage section.
01 gmp-number.
05 mp-alloc usage binary-long.
05 mp-size usage b... |
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:
################# #############
################## ################
#################... | #JavaScript | JavaScript | function Point(x, y) {
this.x = x;
this.y = y;
}
var ZhangSuen = (function () {
function ZhangSuen() {
}
ZhangSuen.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, ... | #EchoLisp | EchoLisp |
;; special fib's starting with 1 2 3 5 ...
(define (fibonacci n)
(+ (fibonacci (1- n)) (fibonacci (- n 2))))
(remember 'fibonacci #(1 2))
(define-constant Φ (// (1+ (sqrt 5)) 2))
(define-constant logΦ (log Φ))
;; find i : fib(i) >= n
(define (iFib n)
(floor (// (log (+ (* n Φ) 0.5)) logΦ)))
;; left trim ze... |
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... | #Burlesque | Burlesque |
blsq ) 10ro2?^
{1 4 9 16 25 36 49 64 81 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,... | #Eiffel | Eiffel |
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
-- initialize the array, index starts at 1 (not zero) and prefill everything with the letter z
create my_static_array.make_filled ("z", 1, 50)
my_static_array.put ("a", 1)
my_stati... |
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... | #Pascal | Pascal | program complexDemo(output);
const
{ I experienced some hiccups with -1.0 using GPC (GNU Pascal Compiler) }
negativeOne = -1.0;
type
line = string(80);
{ as per task requirements wrap arithmetic operations into separate functions }
function sum(protected x, y: complex): complex;
begin
sum := x + y
end;
func... |
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... | #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ -2 n->v rot
factors witheach
[ n->v 1/v v+ ]
v0= ] is perfect ( n -> b )
19 bit times [ i^ perfect if [ i^ echo cr ] ] |
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... | #Smalltalk | Smalltalk | agm:y
"return the arithmetic-geometric mean agm(x, y)
of the receiver (x) and the argument, y.
See https://en.wikipedia.org/wiki/Arithmetic-geometric_mean"
|ai an gi gn epsilon delta|
ai := (self + y) / 2.
gi := (self * y) sqrt.
epsilon := self ulp.
[
an := (ai + gi) / 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, ... | #Frink | Frink | println[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, ... | #FutureBasic | FutureBasic | window 1
print 0^0
HandleEvents |
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, ... | #Gambas | Gambas | Public Sub Main()
Print 0 ^ 0
End |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Zig_Zag is
type Matrix is array (Positive range <>, Positive range <>) of Natural;
function Zig_Zag (Size : Positive) return Matrix is
Data : Matrix (1..Size, 1..Size);
I, J : Integer := 1;
begin
Data (1, 1) := 0;
for Element in 1..... |
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... | #Arturo | Arturo | yellowstone: function [n][
result: new [1 2 3]
present: new [1 2 3]
start: new 4
while [n > size result][
candidate: new start
while ø [
if all? @[
not? contains? present candidate
1 = gcd @[candidate last result]
1 <> gcd @[can... |
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... | #AutoHotkey | AutoHotkey | A := [], in_seq := []
loop 30 {
n := A_Index
if n <=3
A[n] := n, in_seq[n] := true
else while true
{
s := A_Index
if !in_seq[s] && relatively_prime(s, A[n-1]) && !relatively_prime(s, A[n-2])
{
A[n] := s
in_seq[s] := true
break
... |
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 ... | #Racket | Racket | #lang racket
(require parser-tools/yacc
parser-tools/lex
(prefix-in ~ parser-tools/lex-sre))
(define-tokens value-tokens (NUM))
(define-empty-tokens op-tokens (OPEN CLOSE + - * / EOF NEG))
(define lex
(lexer [(eof) 'EOF]
[whitespace (lex input-port)]
[(~or "+" "-" "*" "/") (... |
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 ... | #Raku | Raku | sub ev (Str $s --> Numeric) {
grammar expr {
token TOP { ^ <sum> $ }
token sum { <product> (('+' || '-') <product>)* }
token product { <factor> (('*' || '/') <factor>)* }
token factor { <unary_minus>? [ <parens> || <literal> ] }
token unary_minus { '-' }
token paren... |
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... | #Julia | Julia | import Base.*, Base.+, Base.-, Base./, Base.show, Base.!=, Base.==, Base.<=, Base.<, Base.>, Base.>=, Base.divrem
const z0 = "0"
const z1 = "1"
const flipordered = (z1 < z0)
mutable struct Z s::String end
Z() = Z(z0)
Z(z::Z) = Z(z.s)
pairlen(x::Z, y::Z) = max(length(x.s), length(y.s))
tolen(x::Z, n::Int) = (s = x... |
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... | #Kotlin | Kotlin | // version 1.1.51
class Zeckendorf(x: String = "0") : Comparable<Zeckendorf> {
var dVal = 0
var dLen = 0
private fun a(n: Int) {
var i = n
while (true) {
if (dLen < i) dLen = i
val j = (dVal shr (i * 2)) and 3
when (j) {
0, 1 -> retur... |
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 ... | #jq | jq | # The factors, sorted
def factors:
. as $num
| reduce range(1; 1 + sqrt|floor) as $i
([];
if ($num % $i) == 0 then
($num / $i) as $r
| if $i == $r then . + [$i] else . + [$i, $r] end
else .
end
| sort) ;
# If the input is a sorted array of distinct non-negative... |
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 ... | #Julia | Julia | using Primes
function factorize(n)
f = [one(n)]
for (p, x) in factor(n)
f = reduce(vcat, [f*p^i for i in 1:x], init=f)
end
f
end
function cansum(goal, list)
if goal == 0 || list[1] == goal
return true
elseif length(list) > 1
if list[1] > goal
return cansu... |
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
... | #Common_Lisp | Common Lisp | (let ((s (format () "~s" (expt 5 (expt 4 (expt 3 2))))))
(format t "~a...~a, length ~a" (subseq s 0 20)
(subseq s (- (length s) 20)) (length s))) |
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
... | #D | D | void main() {
import std.stdio, std.bigint, std.conv;
auto s = text(5.BigInt ^^ 4 ^^ 3 ^^ 2);
writefln("5^4^3^2 = %s..%s (%d digits)", s[0..20], s[$-20..$], s.length);
} |
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:
################# #############
################## ################
#################... | #Julia | Julia |
const pixelstring =
"00000000000000000000000000000000" *
"01111111110000000111111110000000" *
"01110001111000001111001111000000" *
"01110000111000001110000111000000" *
"01110001111000001110000000000000" *
"01111111110000001110000000000000" *
"01110111100000001110000111000000" *
"01110011110011101111001111011100" *
"0... |
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, ... | #Elena | Elena | import system'routines;
import system'collections;
import system'text;
import extensions;
extension op
{
fibonacci()
{
if (self < 2)
{
^ self
}
else
{
^ (self - 1).fibonacci() + (self - 2).fibonacci()
};
}
zeckendorf()
{
... |
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... | #BQN | BQN | swch ← ≠´{100⥊1«𝕩⥊0}¨1+↕100
¯1↓∾{𝕩∾@+10}¨•Fmt¨⟨swch,/swch⟩ |
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,... | #Elena | Elena | var staticArray := new int[]{1, 2, 3}; |
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... | #Perl | Perl | use Math::Complex;
my $a = 1 + 1*i;
my $b = 3.14159 + 1.25*i;
print "$_\n" foreach
$a + $b, # addition
$a * $b, # multiplication
-$a, # negation
1 / $a, # multiplicative inverse
~$a; # complex conjugate |
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... | #Racket | Racket |
-> (* 1/7 14)
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... | #SQL | SQL | WITH
rec (rn, a, g, diff) AS (
SELECT 1, 1, 1/SQRT(2), 1 - 1/SQRT(2)
FROM dual
UNION ALL
SELECT rn + 1, (a + g)/2, SQRT(a * g), (a + g)/2 - SQRT(a * g)
FROM rec
WHERE diff > 1e-38
)
SELECT *
FROM rec
WHERE diff <= 1e-38
; |
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... | #Standard_ML | Standard ML |
fun agm(a, g) = let
fun agm'(a, g, eps) =
if Real.abs(a-g) < eps then
a
else
agm'((a+g)/2.0, Math.sqrt(a*g), eps)
in agm'(a, g, 1e~15)
end;
|
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, ... | #Go | Go | package main
import (
"fmt"
"math"
"math/big"
"math/cmplx"
)
func main() {
fmt.Println("float64: ", math.Pow(0, 0))
var b big.Int
fmt.Println("big integer:", b.Exp(&b, &b, nil))
fmt.Println("complex: ", cmplx.Pow(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, ... | #Groovy | Groovy | println 0**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... | #Agena | Agena | # zig-zag matrix
makeZigZag := proc( n :: number ) :: table is
local move := proc( x :: number, y :: number, upRight :: boolean ) is
if y = n then
upRight := not upRight;
x := x + 1
elif x = 1 then
upRight := not upRight;
y := y + 1
else
... |
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... | #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct lnode_t {
struct lnode_t *prev;
struct lnode_t *next;
int v;
} Lnode;
Lnode *make_list_node(int v) {
Lnode *node = malloc(sizeof(Lnode));
if (node == NULL) {
return NULL;
}
node->v = v;
node->prev = NU... |
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 ... | #REXX | REXX | /*REXX program evaluates an infix─type arithmetic expression and displays the result.*/
nchars = '0123456789.eEdDqQ' /*possible parts of a number, sans ± */
e='***error***'; $=" "; doubleOps= '&|*/'; z= /*handy─dandy variables.*/
parse arg x 1 ox1; if x='' then call serr "... |
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... | #Nim | Nim | type Zeckendorf = object
dVal: Natural
dLen: Natural
const
Dig = ["00", "01", "10"]
Dig1 = ["", "1", "10"]
# Forward references.
func b(z: var Zeckendorf; pos: Natural)
func inc(z: var Zeckendorf)
func a(z: var Zeckendorf; n: Natural) =
var i = n
while true:
if z.dLen < i: z.dLen = i
let j... |
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 ... | #Kotlin | Kotlin | import java.util.ArrayList
import kotlin.math.sqrt
object ZumkellerNumbers {
@JvmStatic
fun main(args: Array<String>) {
var n = 1
println("First 220 Zumkeller numbers:")
run {
var count = 1
while (count <= 220) {
if (isZumkeller(n)) {
... |
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
... | #Dart | Dart | import 'dart:math' show pow;
int fallingPowers(int base) =>
base == 1 ? 1 : pow(base, fallingPowers(base - 1));
void main() {
final exponent = fallingPowers(4),
s = BigInt.from(5).pow(exponent).toString();
print('First twenty: ${s.substring(0, 20)}');
print('Last twenty: ${s.substring(s.len... |
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
... | #dc | dc | [5432.dc]sz
5 4 3 2 ^ ^ ^ sy [y = 5 ^ 4 ^ 3 ^ 2]sz
ly Z sc [c = length of y]sz
[ First 20 digits: ]P ly 10 lc 20 - ^ / p sz [y / (10 ^ (c - 20))]sz
[ Last 20 digits: ]P ly 10 20 ^ % p sz [y % (10 ^ 20)]sz
[Number of digits: ]P lc p sz |
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:
################# #############
################## ################
#################... | #Kotlin | Kotlin | // version 1.1.2
class Point(val x: Int, val y: Int)
val image = arrayOf(
" ",
" ################# ############# ",
" ################## ################ ",
" ################### #######... |
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, ... | #Elixir | Elixir | defmodule Zeckendorf do
def number do
Stream.unfold(0, fn n -> zn_loop(n) end)
end
defp zn_loop(n) do
bin = Integer.to_string(n, 2)
if String.match?(bin, ~r/11/), do: zn_loop(n+1), else: {bin, n+1}
end
end
Zeckendorf.number |> Enum.take(21) |> Enum.with_index
|> Enum.each(fn {zn, i} -> IO.puts "... |
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... | #C | C | #include <stdio.h>
int main()
{
char is_open[100] = { 0 };
int pass, door;
/* do the 100 passes */
for (pass = 0; pass < 100; ++pass)
for (door = pass; door < 100; door += pass+1)
is_open[door] = !is_open[door];
/* output the result */
for (door = 0; door < 100; ++door)
printf("door #%d ... |
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,... | #Elixir | Elixir | ret = {:ok, "fun", 3.1415} |
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... | #Phix | Phix | -- demo\rosetta\ArithComplex.exw
with javascript_semantics
include complex.e
complex a = complex_new(1,1), -- (or just {1,1})
b = complex_new(3.14159,1.25),
c = complex_new(1,0),
d = complex_new(0,1)
printf(1,"a = %s\n",{complex_sprint(a)})
printf(1,"b = %s\n",{complex_sprint(b)})
printf(1,"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... | #Raku | Raku | (2..2**19).hyper.map: -> $candidate {
my $sum = 1 / $candidate;
for 2 .. ceiling(sqrt($candidate)) -> $factor {
if $candidate %% $factor {
$sum += 1 / $factor + 1 / ($candidate / $factor);
}
}
if $sum.nude[1] == 1 {
say "Sum of reciprocal factors of $candidate = $sum ... |
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... | #Stata | Stata | mata
real scalar agm(real scalar a, real scalar b) {
real scalar c
do {
c=0.5*(a+b)
b=sqrt(a*b)
a=c
} while (a-b>1e-15*a)
return(0.5*(a+b))
}
agm(1,1/sqrt(2))
end |
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... | #Swift | Swift | import Darwin
enum AGRError : Error {
case undefined
}
func agm(_ a: Double, _ g: Double, _ iota: Double = 1e-8) throws -> Double {
var a = a
var g = g
var a1: Double = 0
var g1: Double = 0
guard a * g >= 0 else {
throw AGRError.undefined
}
while abs(a - g) > iota {
a1 = (a + g) / 2
g1 = sqrt(a * ... |
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, ... | #GW-BASIC | GW-BASIC | 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, ... | #Haskell | Haskell | import Data.Complex
main = do
print $ 0 ^ 0
print $ 0.0 ^ 0
print $ 0 ^^ 0
print $ 0 ** 0
print $ (0 :+ 0) ^ 0
print $ (0 :+ 0) ** (0 :+ 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... | #ALGOL_68 | ALGOL 68 | PROC zig zag = (INT n)[,]INT: (
PROC move = (REF INT i, j)VOID: (
IF j < n THEN
i := ( i <= 1 | 1 | i-1 );
j +:= 1
ELSE
i +:= 1
FI
);
[n, n]INT a;
INT x:=LWB a, y:=LWB a;
FOR v FROM 0 TO n**2-1 DO
a[y, x] := v;
IF ODD (x... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <numeric>
#include <set>
template <typename integer>
class yellowstone_generator {
public:
integer next() {
n2_ = n1_;
n1_ = n_;
if (n_ < 3) {
++n_;
} else {
for (n_ = min_; !(sequence_.count(n_) == 0
&& std::gcd(... |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program yahoosearch64.s */
/* access RosettaCode.org and data extract */
/* use openssl for access to port 443 */
/* test openssl : package libssl-dev */
/*******************************************/
/* Constantes file */
/************... |
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 ... | #Ruby | Ruby | $op_priority = {"+" => 0, "-" => 0, "*" => 1, "/" => 1}
class TreeNode
OP_FUNCTION = {
"+" => lambda {|x, y| x + y},
"-" => lambda {|x, y| x - y},
"*" => lambda {|x, y| x * y},
"/" => lambda {|x, y| x / y}}
attr_accessor :info, :left, :right
def initialize(info)
@info = info
end
def ... |
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... | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Zeckendorf_arithmetic
use warnings;
for ( split /\n/, <<END ) # test cases
1 + 1
10 + 10
10100 + 1010
10100 - 1010
10100 * 1010
100010 * 100101
10100 / 1010
101000 / 1000
100001000001 / 100010
100001000001 / 100101
END
{
my ($left, $... |
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 ... | #Lobster | Lobster | import std
// Derived from Julia and Python versions
def get_divisors(n: int) -> [int]:
var i = 2
let d = [1, n]
let limit = sqrt(n)
while i <= limit:
if n % i == 0:
let j = n / i
push(d,i)
if i != j:
push(d,j)
i += 1
return d
... |
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 ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[ZumkellerQ]
ZumkellerQ[n_] := Module[{d = Divisors[n], t, ds, x},
ds = Total[d];
If[Mod[ds, 2] == 1,
False
,
t = CoefficientList[Product[1 + x^i, {i, d}], x];
t[[1 + ds/2]] > 0
]
];
i = 1;
res = {};
While[Length[res] < 220,
r = ZumkellerQ[i];
If[r, AppendTo[res, i]];
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
... | #Delphi | Delphi |
program Arbitrary_precision_integers;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Velthuis.BigIntegers;
var
value: BigInteger;
result: string;
begin
value := BigInteger.pow(3, 2);
value := BigInteger.pow(4, value.AsInteger);
value := BigInteger.pow(5, value.AsInteger);
result := value.tostring;
... |
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
... | #E | E | ? def value := 5**(4**(3**2)); null
? def decimal := value.toString(10); null
? decimal(0, 20)
# value: "62060698786608744707"
? decimal(decimal.size() - 20)
# value: "92256259918212890625"
? decimal.size()
# value: 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:
################# #############
################## ################
#################... | #Lua | Lua | function zhangSuenThin(img)
local dirs={
{ 0,-1},
{ 1,-1},
{ 1, 0},
{ 1, 1},
{ 0, 1},
{-1, 1},
{-1, 0},
{-1,-1},
{ 0,-1},
}
local black=1
local white=0
function A(x, y)
local c=0
local current=img[y+dirs[1][2... |
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, ... | #F.23 | F# | let fib = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (1,2)
let zeckendorf n =
if n = 0 then ["0"]
else
let folder k state =
let (n, z) = (fst state), (snd state)
if n >= k then (n - k, "1" :: z)
else (n, "0" :: z)
let fb = fib |> Seq.takeWhile (fun 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... | #C.23 | C# | namespace ConsoleApplication1
{
using System;
class Program
{
static void Main(string[] args)
{
bool[] doors = new bool[100];
//Close all doors to start.
for (int d = 0; d < 100; d++) doors[d] = false;
//For each pass...
for (in... |
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,... | #Erlang | Erlang |
%% Create a fixed-size array with entries 0-9 set to 'undefined'
A0 = array:new(10).
10 = array:size(A0).
%% Create an extendible array and set entry 17 to 'true',
%% causing the array to grow automatically
A1 = array:set(17, true, array:new()).
18 = array:size(A1).
%% Read back a stored value
t... |
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... | #PicoLisp | PicoLisp | (load "@lib/math.l")
(de addComplex (A B)
(cons
(+ (car A) (car B)) # Real
(+ (cdr A) (cdr B)) ) ) # Imag
(de mulComplex (A B)
(cons
(-
(*/ (car A) (car B) 1.0)
(*/ (cdr A) (cdr B) 1.0) )
(+
(*/ (car A) (cdr B) 1.0)
(*/ (cdr A) (car B) 1.0)... |
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... | #PL.2FI | PL/I | /* PL/I complex numbers may be integer or floating-point. */
/* In this example, the variables are floating-pint. */
/* For integer variables, change 'float' to 'fixed binary' */
declare (a, b) complex float;
a = 2+5i;
b = 7-6i;
put skip list (a+b);
put skip list (a - b);
put skip list (a*b);
put skip list (... |
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... | #REXX | REXX | /*REXX program implements a reasonably complete rational arithmetic (using fractions).*/
L=length(2**19 - 1) /*saves time by checking even numbers. */
do j=2 by 2 to 2**19 - 1; s=0 /*ignore unity (which can't be perfect)*/
mostDivs=eDivs(j); @= ... |
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... | #Tcl | Tcl | proc agm {a b} {
set old_b [expr {$b<0?inf:-inf}]
while {$a != $b && $b != $old_b} {
set old_b $b
lassign [list [expr {0.5*($a+$b)}] [expr {sqrt($a*$b)}]] a b
}
return $a
}
puts [agm 1 [expr 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... | #TI-83_BASIC | TI-83 BASIC | 1→A:1/sqrt(2)→G
While abs(A-G)>e-15
(A+G)/2→B
sqrt(AG)→G:B→A
End
A |
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, ... | #HolyC | HolyC | F64 a = 0 ` 0;
Print("0 ` 0 = %5.3f\n", a); |
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, ... | #Icon_and_Unicon | Icon and Unicon | procedure main()
write(0^0)
end |
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... | #ALGOL_W | ALGOL W | begin % zig-zag matrix %
% z is returned holding a zig-zag matrix of order n, z must be at least n x n %
procedure makeZigZag ( integer value n
; integer array z( *, * )
) ;
begin
procedure move ;
begin
if y = n then begin
... |
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... | #D | D | import std.numeric;
import std.range;
import std.stdio;
class Yellowstone {
private bool[int] sequence_;
private int min_ = 1;
private int n_ = 0;
private int n1_ = 0;
private int n2_ = 0;
public this() {
popFront();
}
public bool empty() {
return false;
}
... |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program yahoosearch.s */
/* access RosettaCode.org and data extract */
/* use openssl for access to port 443 */
/* test openssl : package libssl-dev */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for t... |
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 ... | #Rust | Rust | //! Simple calculator parser and evaluator
/// Binary operator
#[derive(Debug)]
pub enum Operator {
Add,
Substract,
Multiply,
Divide
}
/// A node in the tree
#[derive(Debug)]
pub enum Node {
Value(f64),
SubNode(Box<Node>),
Binary(Operator, Box<Node>,Box<Node>),
}
/// parse a string i... |
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... | #Phix | Phix | with javascript_semantics
sequence fib = {1,1}
function zeckendorf(atom n)
-- Same as Zeckendorf_number_representation#Phix
atom r = 0
while fib[$]<n do
fib &= fib[$] + fib[$-1]
end while
integer k = length(fib)
while k>2 and n<fib[k] do
k -= 1
end while
for i=k to 2 by... |
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 ... | #Nim | Nim | import math, strutils
template isEven(n: int): bool = (n and 1) == 0
template isOdd(n: int): bool = (n and 1) != 0
func getDivisors(n: int): seq[int] =
result = @[1, n]
for i in 2..sqrt(n.toFloat).int:
if n mod i == 0:
let j = n div i
result.add i
if i != j: result.add j
func isPartS... |
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 ... | #Pascal | Pascal | program zumkeller;
//https://oeis.org/A083206/a083206.txt
{$IFDEF FPC}
{$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$COPERATORS ON}
// {$O+,I+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils
{$IFDEF WINDOWS},Windows{$ENDIF}
;
//######################################################################
//prime decom... |
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
... | #EchoLisp | EchoLisp |
;; to save space and time, we do'nt stringify Ω = 5^4^3^2 ,
;; but directly extract tail and head and number of decimal digits
(lib 'bigint) ;; arbitrary size integers
(define e10000 (expt 10 10000)) ;; 10^10000
(define (last-n big (n 20))
(string-append "..." (number->string (modulo big (expt 10 n)))))
(defi... |
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:
################# #############
################## ################
#################... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | nB[mat_] := Delete[mat // Flatten, 5] // Total;
nA[mat_] := Module[{l},
l = Flatten[mat][[{2, 3, 6, 9, 8, 7, 4, 1, 2}]];
Total[Map[If[#[[1]] == 0 && #[[2]] == 1, 1, 0] &,
Partition[l, 2, 1]]]
];
iW1[mat_] :=
Module[{l = Flatten[mat]},
If[Apply[Times, l[[{2, 6, 8}]]] + Apply[Times, l[[{4, 6, 8}... |
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:
################# #############
################## ################
#################... | #Nim | Nim | import math, sequtils, strutils
type
Bit = 0..1
BitMatrix = seq[seq[Bit]] # Two-dimensional array of 0/1.
Neighbors = array[2..9, Bit] # Neighbor values.
const Symbols = [Bit(0): '.', Bit(1): '#']
func toBitMatrix(s: openArray[string]): BitMatrix =
## Convert an array of 01 strings into a BitMatrix... |
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, ... | #Factor | Factor | USING: formatting kernel locals make math sequences ;
:: fib<= ( n -- seq )
1 2 [ [ dup n <= ] [ 2dup + [ , ] 2dip ] while drop , ]
{ } make ;
:: zeck ( n -- str )
0 :> s! n fib<= <reversed>
[ dup s + n <= [ s + s! 49 ] [ drop 48 ] if ] "" map-as ;
21 <iota> [ dup zeck "%2d: %6s\n" printf ] each |
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, ... | #Forth | Forth | : fib<= ( n -- n )
>r 0 1 BEGIN dup r@ <= WHILE tuck + REPEAT drop rdrop ;
: z. ( n -- )
dup fib<= dup . -
BEGIN ?dup WHILE
dup fib<= dup [char] + emit space . -
REPEAT ;
: tab 9 emit ;
: zeckendorf ( -- )
21 0 DO
cr i 2 .r tab i z.
LOOP ; |
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... | #C.2B.2B | C++ | #include <iostream>
int main()
{
bool is_open[100] = { false };
// do the 100 passes
for (int pass = 0; pass < 100; ++pass)
for (int door = pass; door < 100; door += pass+1)
is_open[door] = !is_open[door];
// output the result
for (int door = 0; door < 100; ++door)
std::cout << "door #" <<... |
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,... | #ERRE | ERRE | DIM A%[100] ! integer array
DIM S$[50] ! string array
DIM R[50] ! real array
DIM R#[70] ! long real array
|
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... | #Pop11 | Pop11 | lvars a = 1.0 +: 1.0, b = 2.0 +: 5.0 ;
a+b =>
a*b =>
1/a =>
a-b =>
a-a =>
a/b =>
a/a =>
;;; The same, but using exact values
1 +: 1 -> a;
2 +: 5 -> b;
a+b =>
a*b =>
1/a =>
a-b =>
a-a =>
a/b =>
a/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... | #Ruby | Ruby |
for candidate in 2 .. 2**19
sum = Rational(1, candidate)
for factor in 2 .. Integer.sqrt(candidate)
if candidate % factor == 0
sum += Rational(1, factor) + Rational(1, candidate / factor)
end
end
if sum.denominator == 1
puts "Sum of recipr. factors of %d = %d exactly %s" %
[candid... |
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... | #UNIX_Shell | UNIX Shell | function agm {
float a=$1 g=$2 eps=${3:-1e-11} tmp
while (( abs(a-g) > eps )); do
print "debug: a=$a\tg=$g"
tmp=$(( (a+g)/2.0 ))
g=$(( sqrt(a*g) ))
a=$tmp
done
echo $a
}
agm $((1/sqrt(2))) 1 |
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... | #VBA | VBA | Private Function agm(a As Double, g As Double, Optional tolerance As Double = 0.000000000000001) As Double
Do While Abs(a - g) > tolerance
tmp = a
a = (a + g) / 2
g = Sqr(tmp * g)
Debug.Print a
Loop
agm = a
End Function
Public Sub main()
Debug.Print agm(1, 1 / Sqr(2))
End... |
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, ... | #J | J | 0 ^ 0
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, ... | #Java | Java | System.out.println(Math.pow(0, 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... | #APL | APL | zz ← {⍵⍴⎕IO-⍨⍋⊃,/{(2|⍴⍵):⌽⍵⋄⍵}¨(⊂w)/¨⍨w{↓⍵∘.=⍨∪⍵}+/[1]⍵⊤w←⎕IO-⍨⍳×/⍵} ⍝ General zigzag (any rectangle)
zzSq ← {zz,⍨⍵} ⍝ Square zigzag
zzSq 5
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24 |
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... | #Delphi | Delphi |
program Yellowstone_sequence;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Generics.Collection,
Boost.Process;
function gdc(x, y: Integer): Integer;
begin
while y <> 0 do
begin
var tmp := x;
x := y;
y := tmp mod y;
end;
Result := x;
end;
function Yellowstone(n: Integer): TArray<Int... |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #AutoHotkey | AutoHotkey | test:
yahooSearch("test", 1)
yahooSearch("test", 2)
return
yahooSearch(query, page)
{
global
start := ((page - 1) * 10) + 1
filedelete, search.txt
urldownloadtofile, % "http://search.yahoo.com/search?p=" . query
. "&b=" . start, search.txt
fileread, content, search.txt
reg = <a class="yschttl spt" href=... |
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 ... | #Scala | Scala |
package org.rosetta.arithmetic_evaluator.scala
object ArithmeticParser extends scala.util.parsing.combinator.RegexParsers {
def readExpression(input: String) : Option[()=>Int] = {
parseAll(expr, input) match {
case Success(result, _) =>
Some(result)
case other =>
println(other)
... |
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... | #PicoLisp | PicoLisp | (seed (in "/dev/urandom" (rd 8)))
(de unpad (Lst)
(while (=0 (car Lst))
(pop 'Lst) )
Lst )
(de numz (N)
(let Fibs (1 1)
(while (>= N (+ (car Fibs) (cadr Fibs)))
(push 'Fibs (+ (car Fibs) (cadr Fibs))) )
(make
(for I (uniq Fibs)
(if (> I N)
(lin... |
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... | #Python | Python | import copy
class Zeckendorf:
def __init__(self, x='0'):
q = 1
i = len(x) - 1
self.dLen = int(i / 2)
self.dVal = 0
while i >= 0:
self.dVal = self.dVal + (ord(x[i]) - ord('0')) * q
q = q * 2
i = i -1
def a(self, n):
i = n
... |
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 ... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory <is_prime divisor_sum divisors vecsum forcomb lastfor>;
sub in_columns {
my($columns, $values) = @_;
my @v = split ' ', $values;
my $width = int(80/$columns);
printf "%${width}d"x$columns."\n", @v[$_*$columns .. -1+(1+$_)*$columns] for 0..-1+@v/... |
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
... | #Elixir | Elixir | defmodule Arbitrary do
def pow(_,0), do: 1
def pow(b,e) when e > 0, do: pow(b,e,1)
defp pow(b,1,acc), do: acc * b
defp pow(b,p,acc) when rem(p,2)==0, do: pow(b*b,div(p,2),acc)
defp pow(b,p,acc), do: pow(b,p-1,acc*b)
def test do
s = pow(5,pow(4,pow(3,2))) |> to_string
l = String.length(s)
pre... |
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
... | #Emacs_Lisp | Emacs Lisp | (let* ((integer-width (* 65536 16)) ; raise bignum limit from 65536 bits to avoid overflow error
(answer (number-to-string (expt 5 (expt 4 (expt 3 2)))))
(length (length answer)))
(message "%s has %d digits"
(if (> length 40)
(format "%s...%s"
(substring answer 0 20)
(subst... |
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:
################# #############
################## ################
#################... | #Perl | Perl | use List::Util qw(sum min);
$source = <<'END';
............................................................
..#################...................#############.........
..##################...............################.........
..###################............##################.........
..########.....#######........ |
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, ... | #Fortran | Fortran | F(N) = ((1 + SQRT(5))**N - (1 - SQRT(5))**N)/(SQRT(5)*2**N) |
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.