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/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... | #Sidef | Sidef | for n in (1 .. 2**19) {
var frac = 0
n.divisors.each {|d|
frac += 1/d
}
if (frac.is_int) {
say "Sum of reciprocal divisors of #{n} = #{frac} exactly #{
frac == 2 ? '- perfect!' : ''
}"
}
} |
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, ... | #Lua | Lua | 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, ... | #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
x=0
y=0
Print x**y=1, x^y=1 ' True True
}
Checkit
|
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, ... | #Maple | Maple | 0^0 |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives ... | #AutoHotkey | AutoHotkey | REM The names (only used for printing the results):
DIM Drink$(4), Nation$(4), Colr$(4), Smoke$(4), Animal$(4)
Drink$() = "Beer", "Coffee", "Milk", "Tea", "Water"
Nation$() = "Denmark", "England", "Germany", "Norway", "Sweden"
Colr$() = "Blue", "Green", "Red", "White", "Yellow"
Sm... |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program xpathXml.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ NBMAXELEMENTS, 100
/*******************************************/
/* Structures */... |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program yingyang.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/*****************************************... |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat... | #ATS | ATS |
(* ****** ****** *)
//
#include "share/atspre_staload.hats"
//
(* ****** ****** *)
//
fun
myfix
{a:type}
(
f: lazy(a) -<cloref1> a
) : lazy(a) = $delay(f(myfix(f)))
//
val
fact =
myfix{int-<cloref1>int}
(
lam(ff) => lam(x) => if x > 0 then x * !ff(x-1) else 1
)
(* ****** ****** *)
//
implement main0 () = println! ("... |
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... | #AutoHotkey | AutoHotkey | n = 5 ; size
v := x := y := 1 ; initial values
Loop % n*n { ; for every array element
a_%x%_%y% := v++ ; assign the next index
If ((x+y)&1) ; odd diagonal
If (x < n) ; while inside the square
y -=... |
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... | #JavaScript | JavaScript | (() => {
'use strict';
// yellowstone :: Generator [Int]
function* yellowstone() {
// A non finite stream of terms in the
// Yellowstone permutation of the natural numbers.
// OEIS A098550
const nextWindow = ([p2, p1, rest]) => {
const [rp2, rp1] = [p2, p1].map(... |
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.
| #Icon_and_Unicon | Icon and Unicon | link printf,strings
procedure main()
YS := YahooSearch("rosettacode")
every 1 to 2 do { # 2 pages
YS.readnext()
YS.showinfo()
}
end
class YahooSearch(urlpat,page,response) #: class for Yahoo Search
method readnext() #: read the next page of search results
self.page +:= 1 # can't find as... |
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 ... | #TXR | TXR | @(next :args)
@(define space)@/ */@(end)
@(define mulop (nod))@\
@(local op)@\
@(space)@\
@(cases)@\
@{op /[*]/}@(bind nod @(intern op *user-package*))@\
@(or)@\
@{op /\//}@(bind (nod) @(list 'trunc))@\
@(end)@\
@(space)@\
@(end)
@(define addop (nod))@\
@(local op)@(space)@{op /[+\-]/}@(s... |
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 ... | #Ursala | Ursala | #import std
#import nat
#import flo
lex = ~=' '*~F+ rlc both -=digits # separate into tokens
parse = # build a tree
--<';'>; @iNX ~&l->rh ^/~< cases~&lhh\~&lhPNVrC {
'*/': ^|C/~&hNV associate '*/',
'+-': ^|C/~&hNV associate '*/+-',
');': @r ~&htitBPC+ associate '*/+-'}
associate "ops" = ~&tihdh2B-... |
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... | #Vlang | Vlang | import strings
const (
dig = ["00", "01", "10"]
dig1 = ["", "1", "10"]
)
struct Zeckendorf {
mut:
d_val int
d_len int
}
fn new_zeck(xx string) Zeckendorf {
mut z := Zeckendorf{}
mut x := xx
if x == "" {
x = "0"
}
mut q := 1
mut i := x.len - 1
z.d_len = i / 2
... |
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... | #Wren | Wren | import "/trait" for Comparable
class Zeckendorf is Comparable {
static dig { ["00", "01", "10"] }
static dig1 { ["", "1", "10"] }
construct new(x) {
var q = 1
var i = x.count - 1
_dLen = (i / 2).floor
_dVal = 0
while (i >= 0) {
_dVal = _dVal + (x[i].b... |
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 ... | #Ring | Ring |
load "stdlib.ring"
see "working..." + nl
see "The first 220 Zumkeller numbers are:" + nl
permut = []
zumind = []
zumodd = []
limit = 19305
num1 = 0
num2 = 0
for n = 2 to limit
zumkeller = []
zumList = []
permut = []
calmo = []
zumind = []
num = 0
nold = 0
for m = 1 to n
i... |
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 ... | #Ruby | Ruby | class Integer
def divisors
res = [1, self]
(2..Integer.sqrt(self)).each do |n|
div, mod = divmod(n)
res << n << div if mod.zero?
end
res.uniq.sort
end
def zumkeller?
divs = divisors
sum = divs.sum
return false unless sum.even? && sum >= self*2
half = sum / 2
ma... |
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
... | #Frink | Frink | a = 5^4^3^2
as = "$a" // Coerce to string
println["Length=" + length[as] + ", " + left[as,20] + "..." + right[as,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
... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | n:=5^(4^(3^2));;
s := String(n);;
m := Length(s);
# 183231
s{[1..20]};
# "62060698786608744707"
s{[m-19..m]};
# "92256259918212890625" |
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
... | #GAP | GAP | n:=5^(4^(3^2));;
s := String(n);;
m := Length(s);
# 183231
s{[1..20]};
# "62060698786608744707"
s{[m-19..m]};
# "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:
################# #############
################## ################
#################... | #Ruby | Ruby | class ZhangSuen
NEIGHBOUR8 = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]] # 8 neighbors
CIRCULARS = NEIGHBOUR8 + [NEIGHBOUR8.first] # P2, ... P9, P2
def initialize(str, black="#")
s1 = str.each_line.map{|line| line.chomp.each_char.map{|c| c==black ? 1 : 0}}
s2 = s1.map{|l... |
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, ... | #Java | Java | import java.util.*;
class Zeckendorf
{
public static String getZeckendorf(int n)
{
if (n == 0)
return "0";
List<Integer> fibNumbers = new ArrayList<Integer>();
fibNumbers.add(1);
int nextFib = 2;
while (nextFib <= n)
{
fibNumbers.add(nextFib);
nextFib += fibNumbers.get(fi... |
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... | #CLIPS | CLIPS | (deffacts initial-state
(door-count 100)
)
(deffunction toggle
(?state)
(switch ?state
(case "open" then "closed")
(case "closed" then "open")
)
)
(defrule create-doors-and-visits
(door-count ?count)
=>
(loop-for-count (?num 1 ?count) do
(assert (door ?num "closed"))
(assert (visit-fro... |
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,... | #Forth | Forth | create MyArray 1 , 2 , 3 , 4 , 5 , 5 cells allot
here constant MyArrayEnd
30 MyArray 7 cells + !
MyArray 7 cells + @ . \ 30
: .array MyArrayEnd MyArray do I @ . cell +loop ; |
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... | #REXX | REXX | /*REXX program demonstrates how to support some math functions for complex numbers. */
x = '(5,3i)' /*define X ─── can use I i J or j */
y = "( .5, 6j)" /*define Y " " " " " " " */
say ' addition: ' x " + ... |
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... | #Slate | Slate | 54 / 7.
20 reciprocal.
(5 / 6) reciprocal.
(5 / 6) as: Float. |
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, ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | 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, ... | #MATLAB_.2F_Octave | MATLAB / Octave | 0^0
complex(0,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, ... | #Maxima | Maxima | 0^0; |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives ... | #BBC_BASIC | BBC BASIC | REM The names (only used for printing the results):
DIM Drink$(4), Nation$(4), Colr$(4), Smoke$(4), Animal$(4)
Drink$() = "Beer", "Coffee", "Milk", "Tea", "Water"
Nation$() = "Denmark", "England", "Germany", "Norway", "Sweden"
Colr$() = "Blue", "Green", "Red", "White", "Yellow"
Sm... |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #AutoHotkey | AutoHotkey | FileRead, inventory, xmlfile.xml
RegExMatch(inventory, "<item.*?</item>", item1)
MsgBox % item1
pos = 1
While, pos := RegExMatch(inventory, "<price>(.*?)</price>", price, pos + 1)
MsgBox % price1
While, pos := RegExMatch(inventory, "<name>.*?</name>", name, pos + 1)
names .= name . "`n"
MsgBox % names |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #Bracmat | Bracmat | {Retrieve the first "item" element}
( nestML$(get$("doc.xml",X,ML))
: ?
( inventory
. ?,? (section.?,? ((item.?):?item) ?) ?
)
?
& out$(toML$!item)
)
{Perform an action on each "price" element (print it out)}
( nestML$(get$("doc.xml",X,ML))
: ?
( inventory
. ?
... |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #Asymptote | Asymptote | unitsize(1 inch);
fill(scale(6)*unitsquare, invisible);
picture yinyang(pair center, real radius) {
picture p;
fill(p, unitcircle, white);
fill(p, arc(0, S, N) -- cycle, black);
fill(p, circle(N/2, 1/2), white);
fill(p, circle(S/2, 1/2), black);
fill(p, circle(N/2, 1/5), black);
fill(p, ... |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat... | #BlitzMax | BlitzMax | SuperStrict
'Boxed type so we can just use object arrays for argument lists
Type Integer
Field val:Int
Function Make:Integer(_val:Int)
Local i:Integer = New Integer
i.val = _val
Return i
End Function
End Type
'Higher-order function type - just a procedure attached to a scope
Type Func Abstract
Method ap... |
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... | #AutoIt | AutoIt |
#include <Array.au3>
$Array = ZigZag(5)
_ArrayDisplay($Array)
Func ZigZag($int)
Local $av_array[$int][$int]
Local $x = 1, $y = 1
For $I = 0 To $int ^ 2 -1
$av_array[$x-1][$y-1] = $I
If Mod(($x + $y), 2) = 0 Then ;Even
if ($y < $int) Then
$y += 1
Else
$x += 2
EndIf
if ($x > 1) Then $x -= 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... | #jq | jq |
# jq optimizes the recursive call of _gcd in the following:
def gcd(a;b):
def _gcd:
if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end;
[a,b] | _gcd ;
# emit the yellowstone sequence as a stream
def yellowstone:
1,2,3,
({ a: [2, 3], # the last two items only
b:... |
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... | #Julia | Julia | using Plots
function yellowstone(N)
a = [1, 2, 3]
b = Dict(1 => 1, 2 => 1, 3 => 1)
start = 4
while length(a) < N
inseries = true
for i in start:typemax(Int)
if haskey(b, i)
if inseries
start += 1
end
else
... |
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.
| #Java | Java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.M... |
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 ... | #Wren | Wren | import "/pattern" for Pattern
/* if string is empty, returns zero */
var toDoubleOrZero = Fn.new { |s|
var n = Num.fromString(s)
return n ? n : 0
}
var multiply = Fn.new { |s|
var b = s.split("*").map { |t| toDoubleOrZero.call(t) }.toList
return (b[0] * b[1]).toString
}
var divide = Fn.new { |s|
... |
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 ... | #Rust | Rust |
use std::convert::TryInto;
/// Gets all divisors of a number, including itself
fn get_divisors(n: u32) -> Vec<u32> {
let mut results = Vec::new();
for i in 1..(n / 2 + 1) {
if n % i == 0 {
results.push(i);
}
}
results.push(n);
results
}
/// Calculates whether the ... |
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 ... | #Sidef | Sidef | func is_Zumkeller(n) {
return false if n.is_prime
return false if n.is_square
var sigma = n.sigma
# n must have an even abundance
return false if (sigma.is_odd || (sigma < 2*n))
# true if n is odd and has an even abundance
return true if n.is_odd # conjecture
var divisors = ... |
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
... | #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(2)
x = x.Exp(big.NewInt(3), x, nil)
x = x.Exp(big.NewInt(4), x, nil)
x = x.Exp(big.NewInt(5), x, nil)
str := x.String()
fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
len(str),
str[:20],
str[len(str)-20:],
)
} |
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:
################# #############
################## ################
#################... | #Sidef | Sidef | class ZhangSuen(str, black="1") {
const NEIGHBOURS = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]] # 8 neighbors
const CIRCULARS = (NEIGHBOURS + [NEIGHBOURS.first]) # P2, ... P9, P2
has r = 0
has image = [[]]
method init {
var s1 = str.lines.map{|line| line.chars.map... |
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, ... | #JavaScript | JavaScript | (() => {
'use strict';
const main = () =>
unlines(
map(n => concat(zeckendorf(n)),
enumFromTo(0, 20)
)
);
// zeckendorf :: Int -> String
const zeckendorf = n => {
const go = (n, x) =>
n < x ? (
Tuple(n, '0')
... |
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... | #Clojure | Clojure | (defn doors []
(let [doors (into-array (repeat 100 false))]
(doseq [pass (range 1 101)
i (range (dec pass) 100 pass) ]
(aset doors i (not (aget doors i))))
doors))
(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n))
(defn print-open-doors []
(pr... |
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,... | #Fortran | Fortran | integer a (10) |
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... | #RLaB | RLaB |
>> x = sqrt(-1)
0 + 1i
>> y = 10 + 5i
10 + 5i
>> z = 5*x-y
-10 + 0i
>> isreal(z)
1
|
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... | #Smalltalk | Smalltalk | st> 54/7
54/7
st> 54/7 + 1
61/7
st> 54/7 < 50
true
st> 20 reciprocal
1/20
st> (5/6) reciprocal
6/5
st> (5/6) asFloat
0.8333333333333334
|
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, ... | #Mercury | Mercury | :- module zero_to_the_zero_power.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module float, int, integer, list, string.
main(!IO) :-
io.format(" int.pow(0, 0) = %d\n", [i(pow(0, 0))], !IO),
io.format("integer.pow(zero, zero) = %s\n",
[s... |
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, ... | #Microsoft_Small_Basic | Microsoft Small Basic | TextWindow.WriteLine(Math.Power(0,0)) |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives ... | #Bracmat | Bracmat | ( (English Swede Dane Norwegian German,)
(red green white yellow blue,(red.English.))
(dog birds cats horse zebra,(dog.?.Swede.))
( tea coffee milk beer water
, (tea.?.?.Dane.) (coffee.?.green.?.)
)
( "Pall Mall" Dunhill Blend "Blue Master" Prince
, ("Blue Master".beer.?.... |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #C | C |
#include <libxml/parser.h>
#include <libxml/xpath.h>
xmlDocPtr getdoc (char *docname) {
xmlDocPtr doc;
doc = xmlParseFile(docname);
return doc;
}
xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){
xmlXPathContextPtr context;
xmlXPathObjectPtr result;
context = xmlXPathNewContext(doc);
re... |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #AutoHotkey | AutoHotkey | Yin_and_Yang(50, 50, A_ScriptDir "\YinYang1.png")
Yin_and_Yang(300, 300,A_ScriptDir "\YinYang2.png")
Yin_and_Yang(width, height, fileName
, color1=0xFFFFFFFF, color2=0xFF000000, outlineWidth=1){
pToken := gdip_Startup()
pBitmap := gdip_CreateBitmap(w := width, h := height)
w-=1, h-=1
pGraphics:= gdip_Graph... |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat... | #Bracmat | Bracmat | (λx.x)y |
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... | #AWK | AWK |
# syntax: GAWK -f ZIG-ZAG_MATRIX.AWK [-v offset={0|1}] [size]
BEGIN {
# offset: "0" prints 0 to size^2-1 while "1" prints 1 to size^2
offset = (offset == "") ? 0 : offset
size = (ARGV[1] == "") ? 5 : ARGV[1]
if (offset !~ /^[01]$/) { exit(1) }
if (size !~ /^[0-9]+$/) { exit(1) }
width = length(siz... |
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... | #Kotlin | Kotlin | fun main() {
println("First 30 values in the yellowstone sequence:")
println(yellowstoneSequence(30))
}
private fun yellowstoneSequence(sequenceCount: Int): List<Int> {
val yellowstoneList = mutableListOf(1, 2, 3)
var num = 4
val notYellowstoneList = mutableListOf<Int>()
var yellowSize = 3
... |
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.
| #Julia | Julia | """ Rosetta Code Yahoo search task. https://rosettacode.org/wiki/Yahoo!_search_interface """
using EzXML
using HTTP
using Logging
const pagesize = 7
const URI = "https://search.yahoo.com/search?fr=opensearch&pz=$pagesize&"
struct SearchResults
title::String
content::String
url::String
end
mutable st... |
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.
| #Kotlin | Kotlin | // version 1.2.0
import java.net.URL
val rx = Regex("""<div class=\"yst result\">.+?<a href=\"(.*?)\" class=\"\">(.*?)</a>.+?class="abstract ellipsis">(.*?)</p>""")
class YahooResult(var title: String, var link: String, var text: String) {
override fun toString() = "\nTitle: $title\nLink : $link\nText : $te... |
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 ... | #zkl | zkl | Compiler.Parser.parseText("(1+3)*7").dump();
Compiler.Parser.parseText("1+3*7").dump(); |
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 ... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 PRINT "Use integer numbers and signs"'"+ - * / ( )"''
20 LET s$="": REM last symbol
30 LET pc=0: REM parenthesis counter
40 LET i$="1+2*(3+(4*5+6*7*8)-9)/10"
50 PRINT "Input = ";i$
60 FOR n=1 TO LEN i$
70 LET c$=i$(n)
80 IF c$>="0" AND c$<="9" THEN GO SUB 170: GO TO 130
90 IF c$="+" OR c$="-" THEN GO SUB 200: GO TO ... |
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 ... | #Standard_ML | Standard ML |
exception Found of string ;
val divisors = fn n =>
let
val rec divr = fn ( c, divlist ,i) =>
if c <2*i then c::divlist
else divr (if c mod i = 0 then (c,i::divlist,i+1) else (c,divlist,i+1) )
in
divr (n,[],1)
end;
val subsetSums = fn M => fn input =>
let
val getnrs = fn (v,x) => ... |
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 ... | #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public var isZumkeller: Bool {
let divs = factors(sorted: false)
let sum = divs.reduce(0, +)
guard sum & 1 != 1 else {
return false
}
guard self & 1 != 1 else {
let abundance = sum - 2*self
return abundance > 0 && 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
... | #Golfscript | Golfscript | 5 4 3 2??? # Calculate 5^(4^(3^2))
`.. # Convert to string and make two copies
20<p # Print the first 20 digits
-20>p # Print the last 20 digits
,p # Print the length |
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
... | #Groovy | Groovy | def bigNumber = 5G ** (4 ** (3 ** 2)) |
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
... | #Haskell | Haskell | main :: IO ()
main = do
let y = show (5 ^ 4 ^ 3 ^ 2)
let l = length y
putStrLn
("5**4**3**2 = " ++
take 20 y ++ "..." ++ drop (l - 20) y ++ " and has " ++ show l ++ " 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:
################# #############
################## ################
#################... | #Swift | Swift | import UIKit
// testing examples
let beforeTxt = """
1100111
1100111
1100111
1100111
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1111110
0000000
"""
let smallrc01 = """
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
0111000011100000111000011100... |
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, ... | #jq | jq | def zeckendorf:
def fibs($n):
# input: [f(i-2), f(i-1)]
[1,1] | [recurse(select(.[1] < $n) | [.[1], add]) | .[1]] ;
# Emit an array of 0s and 1s corresponding to the Zeckendorf encoding
# $f should be the relevant Fibonacci numbers in increasing order.
def loop($f):
[ recurse(. as [$n, $ix]
... |
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, ... | #Julia | Julia | function zeck(n)
n <= 0 && return 0
fib = [2,1]; while fib[1] < n unshift!(fib,sum(fib[1:2])) end
dig = Int[]; for f in fib f <= n ? (push!(dig,1); n = n-f;) : push!(dig,0) end
return dig[1] == 0 ? dig[2:end] : dig
end |
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... | #CLU | CLU | start_up = proc ()
max = 100
po: stream := stream$primary_output()
open: array[bool] := array[bool]$fill(1, max, false)
for pass: int in int$from_to(1, max) do
for door: int in int$from_to_by(pass, max, pass) do
open[door] := ~open[door]
end
end
for door: int in a... |
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,... | #FreeBASIC | FreeBASIC | ' compile with: FBC -s console.
' compile with: FBC -s console -exx to have boundary checks.
Dim As Integer a(5) ' from s(0) to s(5)
Dim As Integer num = 1
Dim As String s(-num To num) ' s1(-1), s1(0) and s1(1)
Static As UByte c(5) ' create a array with 6 elements (0 to 5)
'dimension array and initializing it ... |
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... | #Ruby | Ruby |
# Four ways to write complex numbers:
a = Complex(1, 1) # 1. call Kernel#Complex
i = Complex::I # 2. use Complex::I
b = 3.14159 + 1.25 * i
c = '1/2+3/4i'.to_c # 3. Use the .to_c method from String, result ((1/2)+(3/4)*i)
c = 1.0/2+3/4i # (0.5-(3/4)*i)
# Operations:
puts a + b ... |
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... | #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public func gcd(with other: Self) -> Self {
var gcd = self
var b = other
while b != 0 {
(gcd, b) = (b, gcd % b)
}
return gcd
}
@inlinable
public func lcm(with other: Self) -> Self {
let g = gcd(with: other)
retu... |
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, ... | #min | min | 0 0 pow puts |
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, ... | #MiniScript | MiniScript | print "The result of zero to the zero power is " + 0^0 |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives ... | #C | C | #include <stdio.h>
#include <string.h>
enum HouseStatus { Invalid, Underfull, Valid };
enum Attrib { C, M, D, A, S };
// Unfilled attributes are represented by -1
enum Colors { Red, Green, White, Yellow, Blue };
enum Mans { English, Swede, Dane, German, Norwegian };
enum Drinks { Tea, Coffee, Milk, Beer, Water };... |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #C.23 | C# | XmlReader XReader;
// Either read the xml from a string ...
XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>"));
// ... or read it from the file system.
XReader = XmlReader.Create("xmlfile.xml");
// Create a XPathDocument object (which implements the IXPathNavigable interface)
// whi... |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #AWK | AWK |
# syntax: GAWK -f YIN_AND_YANG.AWK
# converted from PHL
BEGIN {
yin_and_yang(16)
yin_and_yang(8)
exit(0)
}
function yin_and_yang(radius, black,white,scale_x,scale_y,sx,sy,x,y) {
black = "#"
white = "."
scale_x = 2
scale_y = 1
for (sy = radius*scale_y; sy >= -(radius*scale_y); sy--) {
... |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat... | #C | C | #include <stdio.h>
#include <stdlib.h>
/* func: our one and only data type; it holds either a pointer to
a function call, or an integer. Also carry a func pointer to
a potential parameter, to simulate closure */
typedef struct func_t *func;
typedef struct func_t {
func (*fn) (func, fu... |
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... | #BBC_BASIC | BBC BASIC | Size% = 5
DIM array%(Size%-1,Size%-1)
i% = 1
j% = 1
FOR e% = 0 TO Size%^2-1
array%(i%-1,j%-1) = e%
IF ((i% + j%) AND 1) = 0 THEN
IF j% < Size% j% += 1 ELSE i% += 2
IF i% > 1 i% -= 1
ELSE
IF i% < Size% i% += 1 ELSE j% += 2
IF... |
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... | #Lua | Lua | function gcd(a, b)
if b == 0 then
return a
end
return gcd(b, a % b)
end
function printArray(a)
io.write('[')
for i,v in pairs(a) do
if i > 1 then
io.write(', ')
end
io.write(v)
end
io.write(']')
return nil
end
function removeAt(a, i)
lo... |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Manipulate[
Column[Flatten[
StringCases[
StringCases[
URLFetch[
"http://search.yahoo.com/search?p=" <> query <> "&b=" <>
ToString@page], "<ol" ~~ ___ ~~ "</ol>"],
"<a" ~~ Shortest[__] ~~ "class=\"yschttl spt\" href=\"" ~~
Shortest[url__] ~~ "\"" ~~ Shortest[__] ~~ ">" ~~
Sh... |
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.
| #Nim | Nim | import httpclient, strutils, htmlparser, xmltree, strtabs
const
PageSize = 7
YahooURLPattern = "https://search.yahoo.com/search?fr=opensearch&b=$$#&pz=$#&p=".format(PageSize)
type
SearchResult = ref object
url, title, content: string
SearchInterface = ref object
client: HttpClient
urlPattern: string... |
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function GetDivisors(n As Integer) As List(Of Integer)
Dim divs As New List(Of Integer) From {
1, n
}
Dim i = 2
While i * i <= n
If n Mod i = 0 Then
Dim j = n \ i
divs.Add(i)
If i <> j Then
... |
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
... | #Hoon | Hoon |
=+ big=(pow 5 (pow 4 (pow 3 2)))
=+ digits=(lent (skip <big> |=(a/* ?:(=(a '.') & |))))
[digits (div big (pow 10 (sub digits 20))) (mod big (pow 10 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
... | #Icon_and_Unicon | Icon and Unicon | procedure main()
x := 5^4^3^2
write("done with computation")
x := string(x)
write("5 ^ 4 ^ 3 ^ 2 has ",*x," digits")
write("The first twenty digits are ",x[1+:20])
write("The last twenty digits are ",x[0-:20])
end |
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:
################# #############
################## ################
#################... | #Tcl | Tcl | # -*- coding: utf-8 -*-
set data {
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
0111000111101110011... |
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, ... | #Klingphix | Klingphix | include ..\Utilitys.tlhy
:listos
%i$ "" !i$
len [ get tostr $i$ chain !i$ ] for drop
$i$
;
:Zeckendorf %n !n
%i 0 !i %c 0 !c
[
$i 8 itob listos
"11" find not (
[ ( $c ":" 9 tochar ) lprint tonum ? $c 1 + !c ]
[drop]
) if
$i 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, ... | #Kotlin | Kotlin | // version 1.0.6
const val LIMIT = 46 // to stay within range of signed 32 bit integer
val fibs = fibonacci(LIMIT)
fun fibonacci(n: Int): IntArray {
if (n !in 2..LIMIT) throw IllegalArgumentException("n must be between 2 and $LIMIT")
val fibs = IntArray(n)
fibs[0] = 1
fibs[1] = 1
for (i in 2 un... |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. 100Doors.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Current-n PIC 9(3).
01 StepSize PIC 9(3).
01 DoorTable.
02 Doors PIC 9(1) OCCURS 100 TIMES.
88 ClosedDoor VALUE ZERO.
01 ... |
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,... | #Frink | Frink |
a = new array
a@0 = 10
a@1 = 20
println[a@1]
b = [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... | #Rust | Rust | extern crate num;
use num::complex::Complex;
fn main() {
// two valid forms of definition
let a = Complex {re:-4.0, im: 5.0};
let b = Complex::new(1.0, 1.0);
println!(" a = {}", a);
println!(" b = {}", b);
println!(" a + b = {}", a + b);
println!(" a * b = {}", a * b);
pr... |
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... | #Scala | Scala | package org.rosettacode
package object ArithmeticComplex {
val i = Complex(0, 1)
implicit def fromDouble(d: Double) = Complex(d)
implicit def fromInt(i: Int) = Complex(i.toDouble)
}
package ArithmeticComplex {
case class Complex(real: Double = 0.0, imag: Double = 0.0) {
def this(s: String) =
... |
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... | #Tcl | Tcl | namespace eval rat {}
proc rat::new {args} {
if {[llength $args] == 0} {
set args {0}
}
lassign [split {*}$args] n d
if {$d == 0} {
error "divide by zero"
}
if {$d < 0} {
set n [expr {-1 * $n}]
set d [expr {abs($d)}]
}
return [normalize $n $d]
}
proc r... |
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, ... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | Сx ^ x^y С/П |
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, ... | #Nanoquery | Nanoquery | 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, ... | #Neko | Neko | /**
Zero to the zeroth power, in Neko
*/
var math_pow = $loader.loadprim("std@math_pow", 2)
$print(math_pow(0, 0), "\n") |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives ... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;
public enum Colour { Red, Green, White, Yellow, Blue }
public enum Nationality { Englishman, Swede, Dane, Norwegian,German }
public enum Pet { Dog, Birds, Cats, Horse, Zebra }
public enum Drink { Coffee,... |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #C.2B.2B | C++ | #include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>
#include <libxml/xpath.h>
#ifndef LIBXML_XPATH_ENABLED
# ... |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #BASIC | BASIC | pi=3.141592
s=.5
xp=320:yp=100:size=150
GOSUB DrawYY
xp=500:yp=40:size=50
GOSUB DrawYY
END
DrawYY:
CIRCLE (xp,yp),size,,,,s
CIRCLE (xp,yp+size/4),size/8,,,,s
CIRCLE (xp,yp-size/4),size/8,,,,s
CIRCLE (xp,yp+size/4),size/2,,.5*pi,1.5*pi,s
CIRCLE (xp,yp-size/4),size/2,,1.5*pi,2*pi,s
CIRCLE (xp,yp-size/... |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #BCPL | BCPL | get "libhdr"
let circle(x, y, c, r) = (r*r) >= (x/2) * (x/2) + (y-c) * (y-c)
let pixel(x, y, r) =
circle(x, y, -r/2, r/6) -> '#',
circle(x, y, r/2, r/6) -> '.',
circle(x, y, -r/2, r/2) -> '.',
circle(x, y, r/2, r/2) -> '#',
circle(x, y, 0, r) -> x<0 -> '.', '#',
' '
let yinyang(r) ... |
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.