task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #SNOBOL4 | SNOBOL4 | * # Define complex datatype
data('complex(r,i)')
* # Addition
define('addx(x1,x2)a,b,c,d') :(addx_end)
addx a = r(x1); b = i(x1); c = r(x2); d = i(x2)
addx = complex(a + c, b + d) :(return)
addx_end
* # Multiplication
define('multx(x1,x2)a,b,c,d') :(multx_... |
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... | #Standard_ML | Standard ML |
(* Signature for complex numbers *)
signature COMPLEX = sig
type num
val complex : real * real -> num
val negative : num -> num
val plus : num -> num -> num
val minus : num -> num -> num
val times : num -> num -> num
val invert : num -> num
val print_number : num -> unit
end;
(* Actual implementation *)... |
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, ... | #Pascal | Pascal | program ZToZ;
uses
math;
begin
write('0.0 ^ 0 :',IntPower(0.0,0):4:2);
writeln(' 0.0 ^ 0.0 :',Power(0.0,0.0):4: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, ... | #Perl | Perl | print 0 ** 0, "\n";
use Math::Complex;
print cplx(0,0) ** cplx(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 ... | #D | D | import std.stdio, std.traits, std.algorithm, std.math;
enum Content { Beer, Coffee, Milk, Tea, Water,
Danish, English, German, Norwegian, Swedish,
Blue, Green, Red, White, Yellow,
Blend, BlueMaster, Dunhill, PallMall, Prince,
Bird, Cat, Dog, Horse, Zebra }
e... |
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... | #E | E | ? def xml__quasiParser := <import:org.switchb.e.xml.makeXMLQuasiParser>()
> def xpath__quasiParser := xml__quasiParser.xPathQuasiParser()
> null
? def doc := xml`<inventory title="OmniCorp Store #45x10^3">
> <section name="health">
> <item upc="123456789" stock="12">
> <name>Invisibility Cream</name>
> ... |
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.
| #Delphi | Delphi | procedure DrawYinAndYang(Canv: TCanvas; R: TRect);
begin
Canv.Brush.Color := clWhite;
Canv.Pen.Color := clWhite;
Canv.Pie(R.Left, R.Top, R.Right, R.Bottom,
(R.Right + R.Left) div 2, R.Top, (R.Right + R.Left) div 2, R.Bottom);
Canv.Brush.Color := clBlack;
Canv.Pen.Color := clBlack;
Canv.Pie(R.Left, R.Top... |
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... | #CoffeeScript | CoffeeScript | Y = (f) -> g = f( (t...) -> g(t...) ) |
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... | #CoffeeScript | CoffeeScript |
# Calculate a zig-zag pattern of numbers like so:
# 0 1 5
# 2 4 6
# 3 7 8
#
# There are many interesting ways to solve this; we
# try for an algebraic approach, calculating triangle
# areas, so that me minimize space requirements.
zig_zag_value = (x, y, n) ->
upper_triangle_zig_zag = (x, y) ->
# calcu... |
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... | #REXX | REXX | /*REXX program calculates any number of terms in the Yellowstone (permutation) sequence.*/
parse arg m . /*obtain optional argument from the CL.*/
if m=='' | m=="," then m= 30 /*Not specified? Then use the default.*/
!.= 0 ... |
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... | #Ring | Ring |
see "working..." + nl
row = 3
num = 2
numbers = 1:51
first = 2
second = 3
see "Yellowstone numbers are:" + nl
see "1 " + first + " " + second + " "
for n = 4 to len(numbers)
flag1 = 1
flag2 = 1
if first < numbers[n]
min = first
else
min = numbers[n]
... |
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.
| #Raku | Raku |
use Gumbo;
use LWP::Simple;
use XML::Text;
class YahooSearch {
has $!dom;
submethod BUILD (:$!dom) { }
method new($term) {
self.bless(
dom => parse-html(
LWP::Simple.get("http://search.yahoo.com/search?p={ $term }")
)
);
}
method next {
$!dom = parse-html(
LWP::... |
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
... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | s:=ToString[5^4^3^2];
Print[StringTake[s,20]<>"..."<>StringTake[s,-20]<>" ("<>ToString@StringLength@s<>" digits)"]; |
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
... | #MATLAB | MATLAB | >> answer = vpi(5)^(vpi(4)^(vpi(3)^vpi(2)));
>> numDigits = order(answer) + 1
numDigits =
183231
>> [sprintf('%d',leadingdigit(answer,20)) '...' sprintf('%d',trailingdigit(answer,20))]
%First and Last 20 Digits
ans =
62060698786608744707...92256259918212890625 |
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, ... | #Pascal | Pascal |
program ZeckendorfRep_RC;
{$mode objfpc}{$H+}
uses SysUtils;
// Return Zeckendorf representation of the passed-in cardinal.
function ZeckRep( C : cardinal) : string;
var
a, b, rem : cardinal;
j, nrDigits: integer;
begin
// Case C = 0 has to be treated specially
if (C = 0) then begin
result := '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... | #Common_Lisp | Common Lisp | (defun visit-door (doors doornum value1 value2)
"visits a door, swapping the value1 to value2 or vice-versa"
(let ((d (copy-list doors))
(n (- doornum 1)))
(if (eql (nth n d) value1)
(setf (nth n d) value2)
(setf (nth n d) value1))
d))
(defun visit-every (doors num iter value1 value... |
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,... | #Go | Go | package main
import (
"fmt"
)
func main() {
// creates an array of five ints.
// specified length must be a compile-time constant expression.
// this allows compiler to do efficient bounds checking.
var a [5]int
// since length is compile-time constant, len() is a compile time constant
... |
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... | #Stata | Stata | mata
C(2,3)
2 + 3i
a=2+3i
b=1-2*i
a+b
-5 + 3i
a-b
9 + 3i
a*b
-14 - 21i
a/b
-.285714286 - .428571429i
-a
-2 - 3i
1/a
.153846154 - .230769231i
conj(a)
2 - 3i
abs(a)
3.605551275
arg(a)
.9827937232
exp(a)
-7.31511009 + 1.04274366i
log(a)
1.28247468 + .982793723i
end |
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... | #Swift | Swift |
public struct Complex {
public let real : Double
public let imaginary : Double
public init(real inReal:Double, imaginary inImaginary:Double) {
real = inReal
imaginary = inImaginary
}
public static var i : Complex = Complex(real:0, imaginary: 1)
public static var zero : Co... |
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, ... | #Phix | Phix | ?power(0,0)
requires("0.8.4") -- (now fixed/crashes on earlier versions)
include complex.e
complex a = complex_new(0,0),
b = complex_power(a,a)
string sa = complex_sprint(a,true),
sb = complex_sprint(b,true)
printf(1,"%s ^ %s = %s\n",{sa,sa,sb})
|
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, ... | #Phixmonti | Phixmonti | def mypower
dup not if
. sign dup 0 == if . 1 endif
else
power
endif
enddef
0 0 mypower print |
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 ... | #EchoLisp | EchoLisp |
(lib 'hash)
(lib 'amb)
;; return #f or house# for thing/category
;; houses := (0 1 2 3 4)
(define (house-get H category thing houses)
(for/or ((i houses)) #:continue (!equal? (hash-ref (vector-ref H i) category) thing)
i))
;; return house # for thing (eg cat) in category (eq animals)
;; add th... |
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... | #Erlang | Erlang |
-module(xml_xpath).
-include_lib("xmerl/include/xmerl.hrl").
-export([main/0]).
main() ->
XMLDocument =
"<inventory title=\"OmniCorp Store #45x10^3\">
<section name=\"health\">
<item upc=\"123456789\" stock=\"12\">
<name>Invisibility Cream</name>
<price>14.50</... |
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.
| #DWScript | DWScript | type
TColorFuncX = function (x : Integer) : Integer;
type
TSquareBoard = class
Scale : Integer;
Pix : array of array of Integer;
constructor Create(aScale : Integer);
begin
Scale := aScale;
Pix := new Integer[aScale*12+1, aScale*12+1];
end;
method Print;... |
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... | #Common_Lisp | Common Lisp | (defun Y (f)
((lambda (g) (funcall g g))
(lambda (g)
(funcall f (lambda (&rest a)
(apply (funcall g g) a))))))
(defun fac (n)
(funcall
(Y (lambda (f)
(lambda (n)
(if (zerop n)
1
(* n (funcall f (1- n)))))))
n))
(defun fib (n)
(funcall
(Y (lambda (f)
(lambda ... |
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... | #Common_Lisp | Common Lisp | (defun zigzag (n)
(flet ((move (i j)
(if (< j (1- n))
(values (max 0 (1- i)) (1+ j))
(values (1+ i) j))))
(loop with a = (make-array (list n n) :element-type 'integer)
with x = 0
with y = 0
for v from 0 below (* n n)
do (setf (aref a... |
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... | #Ruby | Ruby | def yellow(n)
a = [1, 2, 3]
b = { 1 => true, 2 => true, 3 => true }
i = 4
while n > a.length
if !b[i] && i.gcd(a[-1]) == 1 && i.gcd(a[-2]) > 1
a << i
b[i] = true
i = 4
end
i += 1
end
a
end
p yellow(30) |
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... | #Rust | Rust | // [dependencies]
// num = "0.3"
// plotters = "^0.2.15"
use num::integer::gcd;
use plotters::prelude::*;
use std::collections::HashSet;
fn yellowstone_sequence() -> impl std::iter::Iterator<Item = u32> {
let mut sequence: HashSet<u32> = HashSet::new();
let mut min = 1;
let mut n = 0;
let mut n1 = 0... |
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.
| #Ruby | Ruby | require 'open-uri'
require 'hpricot'
SearchResult = Struct.new(:url, :title, :content)
class SearchYahoo
@@urlinfo = [nil, 'ca.search.yahoo.com', 80, '/search', nil, nil]
def initialize(term)
@term = term
@page = 1
@results = nil
@url = URI::HTTP.build(@@urlinfo)
end
def next_result
... |
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
... | #Maxima | Maxima | block([s, n], s: string(5^4^3^2), n: slength(s), print(substring(s, 1, 21), "...", substring(s, n - 19)), n);
/* 62060698786608744707...92256259918212890625
183231 */ |
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
... | #Nanoquery | Nanoquery | value = str(5^(4^(3^2)))
first20 = value.substring(0,20)
last20 = value.substring(len(value) - 20)
println "The first twenty digits are " + first20
println "The last twenty digits are " + last20
if (first20 = "62060698786608744707") && (last20 = "92256259918212890625")
println "\nThese digits are correct.\n"
end... |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #Nemerle | Nemerle | using System.Console;
using System.Numerics;
using System.Numerics.BigInteger;
module BigInt
{
Main() : void
{
def n = Pow(5, Pow(4, Pow(3, 2) :> int) :> int).ToString();
def len = n.Length;
def first20 = n.Substring(0, 20);
def last20 = n.Substring(len - 20, 20);
ass... |
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, ... | #Perl | Perl | my @fib;
sub fib {
my $n = shift;
return 1 if $n < 2;
return $fib[$n] //= fib($n-1)+fib($n-2);
}
sub zeckendorf {
my $n = shift;
return "0" unless $n;
my $i = 1;
$i++ while fib($i) <= $n;
my $z = '';
while( --$i ) {
$z .= "0", next if fib( $i ) > $n;
$z .= "1";
$n -= fib( $i );
}
r... |
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... | #Component_Pascal | Component Pascal |
MODULE Doors100;
IMPORT StdLog;
PROCEDURE Do*;
VAR
i,j: INTEGER;
closed: ARRAY 101 OF BOOLEAN;
BEGIN
(* initialization of closed to true *)
FOR i := 0 TO LEN(closed) - 1 DO closed[i] := TRUE END;
(* process *)
FOR i := 1 TO LEN(closed) DO;
j := 1;
WHILE j < LEN(closed) DO
IF j MOD i = 0 THEN closed[j]... |
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,... | #Golfscript | Golfscript | [1 2 3]:a; # numeric only array, assigned to a and then dropped
10,:a; # assign to a [0 1 2 3 4 5 6 7 8 9]
a 0= puts # pick element at index 0 (stack: 0)
a 10+puts # append 10 to the end of a
10 a+puts # prepend 10 to a |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #Tcl | Tcl | package require math::complexnumbers
namespace import math::complexnumbers::*
set a [complex 1 1]
set b [complex 3.14159 1.2]
puts [tostring [+ $a $b]] ;# ==> 4.14159+2.2i
puts [tostring [* $a $b]] ;# ==> 1.94159+4.34159i
puts [tostring [pow $a [complex -1 0]]] ;# ==> 0.5-0.4999999999999999i
puts [tostring [- $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, ... | #PHP | PHP | <?php
echo pow(0,0);
echo 0 ** 0; // PHP 5.6+ only
?> |
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, ... | #PicoLisp | PicoLisp |
(** 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, ... | #Pike | Pike | write( 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 ... | #Elixir | Elixir | defmodule ZebraPuzzle do
defp adjacent?(n,i,g,e) do
Enum.any?(0..3, fn x ->
(Enum.at(n,x)==i and Enum.at(g,x+1)==e) or (Enum.at(n,x+1)==i and Enum.at(g,x)==e)
end)
end
defp leftof?(n,i,g,e) do
Enum.any?(0..3, fn x -> Enum.at(n,x)==i and Enum.at(g,x+1)==e end)
end
defp coincident?(n,i,g,e... |
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... | #F.23 | F# |
open System.IO
open System.Xml.XPath
let xml = new StringReader("""
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item ... |
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | : circle ( x y r h -- f )
rot - dup *
rot dup * +
swap dup * swap
< invert
;
: pixel ( r x y -- r c )
2dup 4 pick 6 / 5 pick 2 / negate circle if 2drop '#' exit then
2dup 4 pick 6 / 5 pick 2 / circle if 2drop '.' exit then
2dup 4 pick 2 / 5 pick 2 / negate circle if 2drop '.' exit then
2dup 4 pick 2 / 5 pic... |
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.
| #Forth | Forth | : circle ( x y r h -- f )
rot - dup *
rot dup * +
swap dup * swap
< invert
;
: pixel ( r x y -- r c )
2dup 4 pick 6 / 5 pick 2 / negate circle if 2drop '#' exit then
2dup 4 pick 6 / 5 pick 2 / circle if 2drop '.' exit then
2dup 4 pick 2 / 5 pick 2 / negate circle if 2drop '.' exit then
2dup 4 pick 2 / 5 pic... |
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... | #Crystal | Crystal | require "big"
struct RecursiveFunc(T) # a generic recursive function wrapper...
getter recfnc : RecursiveFunc(T) -> T
def initialize(@recfnc) end
end
struct YCombo(T) # a struct or class needs to be used so as to be generic...
def initialize (@fnc : Proc(T) -> T) end
def fixy
g = -> (x : RecursiveFunc(T... |
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... | #Crystal | Crystal | def zigzag(n)
(seq=(0...n).to_a).product(seq)
.sort_by {|x,y| [x+y, (x+y).even? ? y : -y]}
.map_with_index{|v, i| {v, i}}.sort.map(&.last).each_slice(n).to_a
end
def print_matrix(m)
format = "%#{m.flatten.max.to_s.size}d " * m[0].size
m.each {|row| puts format % row}
end
print_matrix zigzag(5) |
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... | #Tcl | Tcl | proc gcd {a b} {
while {$b} {
lassign [list $b [expr {$a % $b}]] a b
}
return $a
}
proc gen_yellowstones {{maxN 30}} {
set r {}
for {set n 1} {$n <= $maxN} {incr n} {
if {$n <= 3} {
lappend r $n
} else {
## NB: list indices start at 0, not 1.
... |
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.
| #Run_BASIC | Run BASIC | '--------------------------------------------------------------------------
' send this from the server to the clients browser
'--------------------------------------------------------------------------
html "<table border=1 cellpadding=0 cellspacing=0 bgcolor=wheat>"
html "<tr><td align=center colspan=2>Yahoo Search</... |
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.
| #Tcl | Tcl | package require http
proc fix s {
string map {<b>...</b> "" <b> "" </b> "" <wbr> "" "<wbr />" ""} \
[regsub "</a></h3></div>.*" $s ""]
}
proc YahooSearch {term {page 1}} {
# Build the (ugly) scraper URL
append re {<a class="yschttl spt" href=".+?" >(.+?)</a></h3>}
append re {</div><div cla... |
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
... | #NewLisp | NewLisp |
;;; No built-in big integer exponentiation
(define (exp-big x n)
(setq x (bigint x))
(let (y 1L)
(if (= n 0)
1L
(while (> n 1)
(if (odd? n)
(setq y (* x y)))
(setq x (* x x) n (/ n 2)))
(* x y))))
;
;;; task
(define (test)
(local (res)
; drop the "L" at the end
(setq res (0 (- (length re... |
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, ... | #Phix | Phix | function zeckendorf(integer n)
integer r = 0, c
sequence fib = {1,1}
while fib[$]<n do
fib &= fib[$] + fib[$-1]
end while
for i=length(fib) to 2 by -1 do
c = n>=fib[i]
r += r+c
n -= c*fib[i]
end for
return r
end function
for i=0 to 20 do
printf(1,"%2d: %7b\n",{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... | #Coq | Coq | Require Import List.
Fixpoint rep {A} (a : A) n :=
match n with
| O => nil
| S n' => a::(rep a n')
end.
Fixpoint flip (l : list bool) (n k : nat) : list bool :=
match l with
| nil => nil
| cons h t => match k with
| O => (negb h) :: (flip t n n)
| S k' => h :: (... |
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,... | #Groovy | Groovy | def aa = [ 1, 25, 31, -3 ] // list
def a = [0] * 100 // list of 100 zeroes
def b = 1..9 // range notation
def c = (1..10).collect { 2.0**it } // each output element is 2**(corresponding invoking list element)
// There are no true "multi-dimensional" arrays in Groo... |
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... | #TI-83_BASIC | TI-83 BASIC | ■ √(–1)
■ ^2 —1
■ + 1 1 +
■ (1+) * 2 2 + 2*
■ (1+) (2) —2 + 2*
■ —(1+) —1 -
■ 1/(2) —1 -
■ real(1 + 2) 1
■ imag(1 + 2) 2 |
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... | #TI-89_BASIC | TI-89 BASIC | ■ √(–1)
■ ^2 —1
■ + 1 1 +
■ (1+) * 2 2 + 2*
■ (1+) (2) —2 + 2*
■ —(1+) —1 -
■ 1/(2) —1 -
■ real(1 + 2) 1
■ imag(1 + 2) 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, ... | #PL.2FI | PL/I | zhz: Proc Options(Main);
Dcl a dec float(10) Init(1);
Dcl b dec float(10) Init(0);
Put skip list('1**0=',a**b);
Put skip list('0**1=',b**a);
Put skip list('0**0=',b**b);
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, ... | #Plain_English | Plain English | To run:
Start up.
Put 0 into a number.
Raise the number to 0.
Convert the number to a string.
Write the string to the console.
Wait for the escape key.
Shut down. |
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 ... | #Erlang | Erlang |
-module( zebra_puzzle ).
-export( [task/0] ).
-record( house, {colour, drink, nationality, number, pet, smoke} ).
-record( sorted_houses, {house_1s=[], house_2s=[], house_3s=[], house_4s=[], house_5s=[]} ).
task() ->
Houses = [#house{colour=C, drink=D, nationality=N, number=Nr, pet=P, smoke=S} || C <- all_colo... |
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... | #Factor | Factor |
! Get first item element
"""<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>... |
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... | #Gastona | Gastona | #javaj#
<frames> oSal, XML Path sample, 300, 400
#data#
<xml>
//<inventory title="OmniCorp Store #45x10^3">
// <section name="health">
// <item upc="123456789" stock="12">
// <name>Invisibility Cream</name>
// <price>14.50</price>
// <description>Makes ... |
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.
| #Go | Go | package main
import (
"fmt"
"os"
"text/template"
)
var tmpl = `<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="210" height="150">
<symbol id="yy" viewBox="0 0 200 200">
<circle stroke="black" stroke-width="2" fill="white"
cx="10... |
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... | #D | D | import std.stdio, std.traits, std.algorithm, std.range;
auto Y(S, T...)(S delegate(T) delegate(S delegate(T)) f) {
static struct F {
S delegate(T) delegate(F) f;
alias f this;
}
return (x => x(x))(F(x => f((T v) => x(x)(v))));
}
void main() { // Demo code:
auto factorial = Y((int del... |
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... | #D | D | int[][] zigZag(in int n) pure nothrow @safe {
static void move(in int n, ref int i, ref int j)
pure nothrow @safe @nogc {
if (j < n - 1) {
if (i > 0) i--;
j++;
} else
i++;
}
auto a = new int[][](n, n);
int x, y;
foreach (v; 0 .. n ^^ 2) {
... |
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... | #uBasic.2F4tH | uBasic/4tH | Dim @y(30)
@y(0) = 1
@y(1) = 2
@y(2) = 3
For i = 3 To 29
k = 3
Do
k = k + 1
If (FUNC(_gcd(k, @y(i-2))) = 1) + (FUNC(_gcd(k, @y(i-1))) > 1) Then
Continue
EndIf
For j = 0 To i - 1
If @y(j) = k Then Unloop : Continue
Next
@y(i) = k : Break
Loop
Next
For i = 0 To 29
Pri... |
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... | #VBA | VBA |
Function gcd(a As Long, b As Long) As Long
If b = 0 Then
gcd = a
Exit Function
End If
gcd = gcd(b, a Mod b)
End Function
Sub Yellowstone()
Dim i As Long, j As Long, k As Long, Y(1 To 30) As Long
Y(1) = 1
Y(2) = 2
Y(3) = 3
For i = 4 To 30
k = 3
Do
k = k + 1
If gcd(k, Y... |
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.
| #TXR | TXR | #!/usr/bin/txr -f
@(next :args)
@(cases)
@ QUERY
@ PAGE
@(or)
@ (throw error "specify query and page# (from zero)")
@(end)
@(next (open-command "!wget -O - http://search.yahoo.com/search?p=@QUERY\&b=@{PAGE}1 2> /dev/null"))
@(all)
@ (coll)<a class="yschttl spt" href="@URL" @/[^>]+/>@TITLE</a>@(end)
@(and)
@ (coll)... |
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.
| #Wren | Wren | /* yahoo_search_interface.wren */
import "./pattern" for Pattern
class YahooSearch {
construct new(url, title, desc) {
_url = url
_title = title
_desc = desc
}
toString { "URL: %(_url)\nTitle: %(_title)\nDescription: %(_desc)\n" }
}
var CURLOPT_URL = 10002
var CURLOPT_FOLLOWL... |
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
... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols
import java.math.BigInteger
numeric digits 30 -- needed to report the run-time
nanoFactor = 10 ** 9
t1 = System.nanoTime
x = BigInteger.valueOf(5)
x = x.pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValue()).intValue()... |
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
... | #Nim | Nim | import bigints
var x = 5.pow 4.pow 3.pow 2
var s = $x
echo s[0..19]
echo s[s.high - 19 .. s.high]
echo s.len |
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, ... | #Phixmonti | Phixmonti | def Zeckendorf /# n -- #/
0 var i 0 var c 1 1 2 tolist var pattern
true
while
i 8 int>bit reverse
pattern find
not if
c print ":\t" print print nl
dup c == if
false
else
c 1 + var c
true
... |
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, ... | #PHP | PHP |
<?php
$m = 20;
$F = array(1,1);
while ($F[count($F)-1] <= $m)
$F[] = $F[count($F)-1] + $F[count($F)-2];
while ($n = $m--) {
while ($F[count($F)-1] > $n) array_pop($F);
$l = count($F)-1;
print "$n: ";
while ($n) {
if ($n >= $F[$l]) {
$n = $n - $F[$l];
print '1';
} else ... |
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... | #Cowgol | Cowgol | include "cowgol.coh";
var doors: uint8[101]; # one extra so we can start at 1
var pass: @indexof doors;
var door: @indexof doors;
MemZero(&doors as [uint8], @bytesof doors);
pass := 1;
while pass <= 100 loop
door := pass;
while door <= 100 loop
doors[door] := 1-doors[door];
door := 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,... | #GUISS | GUISS | Start,Programs,Lotus 123,Type:Bob[downarrow],Kat[downarrow],Sarah[downarrow] |
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... | #UNIX_Shell | UNIX Shell | typeset -T Complex_t=(
float real=0
float imag=0
function to_s {
print -- "${_.real} + ${_.imag} i"
}
function dup {
nameref other=$1
_=( real=${other.real} imag=${other.imag} )
}
function add {
typeset varname
for varname; do
namere... |
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, ... | #PowerShell | PowerShell | Write-Host "0 ^ 0 = " ([math]::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, ... | #PureBasic | PureBasic |
If OpenConsole()
PrintN("Zero to the zero power is " + Pow(0,0))
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
|
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, ... | #Pyret | Pyret | num-expt(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 ... | #ERRE | ERRE |
PROGRAM ZEBRA_PUZZLE
DIM DRINK$[4],NATION$[4],COLR$[4],SMOKE$[4],ANIMAL$[4]
DIM PERM$[120],X$[4]
PROCEDURE PERMUTATION(X$[]->X$[],OK)
LOCAL I%,J%
FOR I%=UBOUND(X$,1)-1 TO 0 STEP -1 DO
EXIT IF X$[I%]<X$[I%+1]
END FOR
IF I%<0 THEN OK=FALSE EXIT PROCEDURE END IF
J%=UBOUND(X$,1)
WHILE ... |
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... | #Go | Go | package main
import (
"encoding/xml"
"fmt"
"log"
"os"
)
type Inventory struct {
XMLName xml.Name `xml:"inventory"`
Title string `xml:"title,attr"`
Sections []struct {
XMLName xml.Name `xml:"section"`
Name string `xml:"name,attr"`
Items []struct {
XMLName xml.Name `xml:"item"`
Nam... |
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.
| #Haskell | Haskell | {-# LANGUAGE NoMonomorphismRestriction #-}
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
yinyang = lw 0 $
perim # lw 0.003 <>
torus white black # xform id <>
torus black white # xform negate <>
clipBy perim base
where perim = arc 0 (360 :: Deg) # scale ... |
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... | #Delphi | Delphi | program Y;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
YCombinator = class sealed
class function Fix<T> (F: TFunc<TFunc<T, T>, TFunc<T, T>>): TFunc<T, T>; static;
end;
TRecursiveFuncWrapper<T> = record // workaround required because of QC #101272 (http://qc.embarcadero.com/wc/qcmain.aspx?d=101272)
ty... |
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... | #E | E | /** Missing scalar multiplication, but we don't need it. */
def makeVector2(x, y) {
return def vector {
to x() { return x }
to y() { return y }
to add(other) { return makeVector2(x + other.x(), y + other.y()) }
to clockwise() { return makeVector2(-y, x) }
}
}
/** Bugs: (1) The printing is speciali... |
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... | #Vlang | Vlang | fn gcd(xx int, yy int) int {
mut x := xx
mut y := yy
for y != 0 {
x, y = y, x%y
}
return x
}
fn yellowstone(n int) []int {
mut m := map[int]bool{}
mut a := []int{len: n+1}
for i in 1..4 {
a[i] = i
m[i] = true
}
mut min := 4
for c := 4; c <= n; c++ {
... |
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... | #Wren | Wren | import "/math" for Int
var yellowstone = Fn.new { |n|
var m = {}
var a = List.filled(n + 1, 0)
for (i in 1..3) {
a[i] = i
m[i] = true
}
var min = 4
for (c in 4..n) {
var i = min
while (true) {
if (!m[i] && Int.gcd(a[c-1], i) == 1 && Int.gcd(a[c-2], 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
... | #OCaml | OCaml | open Num
open Str
open String
let () =
let answer = (Int 5) **/ (Int 4) **/ (Int 3) **/ (Int 2) in
let answer_string = string_of_num answer in
Printf.printf "has %d digits: %s ... %s\n"
(length answer_string)
(first_chars answer_string 20)
(last_chars answer_strin... |
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
... | #Oforth | Oforth | import: mapping
5 4 3 2 pow pow pow >string dup left( 20 ) . dup right( 20 ) . size . |
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, ... | #Picat | Picat | go =>
foreach(Num in 0..20)
zeckendorf_cp(Num,X,F),
Nums = [F[I] : I in 1..X.length, X[I] = 1],
printf("%2d %6s %w\n",Num, rep(X),Nums),
end,
nl.
zeckendorf_cp(Num, X,F) =>
F = get_fibs(Num).reverse(),
N = F.length,
X = new_list(N),
X :: 0..1,
% From the task description:
% """
% For... |
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, ... | #PicoLisp | PicoLisp | (de fib (N)
(let Fibs (1 1)
(while (>= N (+ (car Fibs) (cadr Fibs)))
(push 'Fibs (+ (car Fibs) (cadr Fibs))) )
(uniq Fibs) ) )
(de zecken1 (N)
(make
(for I (fib N)
(if (> I N)
(link 0)
(link 1)
(dec 'N I) ) ) ) )
(de zecken2 (N)
(make
... |
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... | #Crystal | Crystal | doors = Array.new(100, false)
1.upto(100) do |i|
i.step(by: i, to: 100) do |j|
doors[j - 1] = !doors[j - 1]
end
end
doors.each_with_index do |open, i|
puts "Door #{i + 1} is #{open ? "open" : "closed"}"
end |
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,... | #GW-BASIC | GW-BASIC | 10 DATA 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
20 DIM A(9) ' Array with size 10 (9 is maximum subscript), all elements are set to 0
30 FOR I = 0 TO 9
40 READ A(I) ' Initialize by reading data
50 NEXT I
60 PRINT A(4) ' Get 4th element of array
70 A(4) = 400 ' Set 4th element of array
80 PRINT A(4)
|
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... | #Ursala | Ursala | u = 3.785e+00-1.969e+00i
v = 9.545e-01-3.305e+00j
#cast %jL
examples =
<
complex..add (u,v),
complex..mul (u,v),
complex..sub (0.,u),
complex..div (1.,v)> |
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... | #VBA | VBA |
Public Type Complex
re As Double
im As Double
End Type
Function CAdd(a As Complex, b As Complex) As Complex
CAdd.re = a.re + b.re
CAdd.im = a.im + b.im
End Function
Function CSub(a As Complex, b As Complex) As Complex
CSub.re = a.re - b.re
CSub.im = a.im - b.im
End Function
Function CMul... |
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, ... | #Python | Python | from decimal import Decimal
from fractions import Fraction
from itertools import product
zeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)]
for i, j in product(zeroes, repeat=2):
try:
ans = i**j
except:
ans = '<Exception raised>'
print(f'{i!r:>15} ** {j!r:<15} = ... |
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, ... | #QB64 | QB64 | Print 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 ... | #F.23 | F# |
(*Here I solve the Zebra puzzle using Plain Changes, definitely a challenge to some campanoligist to solve it using Grandsire Doubles.
Nigel Galloway: January 27th., 2017 *)
type N = |English=0 |Swedish=1|Danish=2 |German=3|Norwegian=4
type I = |Tea=0 |Coffee=1 |Milk=2 |Beer=3 |Water=4
type G = |Dog=0 ... |
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... | #Groovy | Groovy | def inventory = new XmlSlurper().parseText("<inventory...") //optionally parseText(new File("inv.xml").text)
def firstItem = inventory.section.item[0] //1. first item
inventory.section.item.price.each { println it } //2. print each price
def allNamesArray = inventory.section.item.n... |
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... | #Haskell | Haskell | import Data.List
import Control.Arrow
import Control.Monad
takeWhileIncl :: (a -> Bool) -> [a] -> [a]
takeWhileIncl _ [] = []
takeWhileIncl p (x:xs)
| p x = x : takeWhileIncl p xs
| otherwise = [x]
getmultiLineItem n = takeWhileIncl(not.isInfixOf ("</" ++ n)). dropWh... |
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.
| #Icon_and_Unicon | Icon and Unicon | link graphics
procedure main()
YinYang(100)
YinYang(40,"blue","yellow","white")
WDone() # quit on Q/q
end
procedure YinYang(R,lhs,rhs,bg) # draw YinYang with radius of R pixels and ...
/lhs := "white" # left hand side
/rhs := "black" # right hand side
/bg := "grey" ... |
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... | #Dhall | Dhall | let const
: ∀(b : Type) → ∀(a : Type) → a → b → a
= λ(r : Type) → λ(a : Type) → λ(x : a) → λ(y : r) → x
let fac
: ∀(n : Natural) → Natural
= λ(n : Natural) →
let factorial =
λ(f : Natural → Natural → Natural) →
λ(n : Natural) →
λ(i : Natural) →
... |
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... | #Elena | Elena | import extensions;
extension op : IntNumber
{
zigzagMatrix()
{
auto result := IntMatrix.allocate(self, self);
int i := 0;
int j := 0;
int d := -1;
int start := 0;
int end := self*self - 1;
while (start < end)
{
result.setAt(i, j, ... |
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... | #Elixir | Elixir | defmodule RC do
require Integer
def zigzag(n) do
fmt = "~#{to_char_list(n*n-1) |> length}w "
(for x <- 1..n, y <- 1..n, do: {x,y})
|> Enum.sort_by(fn{x,y}->{x+y, if(Integer.is_even(x+y), do: y, else: x)} end)
|> Enum.with_index |> Enum.sort
|> Enum.each(fn {{_x,y},i} ->
:io.form... |
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.