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
response_seed
stringclasses
1 value
instruction_seed
stringlengths
27
14.4k
_source
stringclasses
1 value
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Maple
Maple
sumDigits := proc( num ) local digits, number_to_string, i; number_to_string := convert( num, string ); digits := [ seq( convert( h, decimal, hex ), h in seq( parse( i ) , i in number_to_string ) ) ]; return add( digits ); end proc: sumDigits( 1234 ); sumDigits( "fe" );
Give a code snippet in #Maple Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#PHP
PHP
<?php function halve($x) { return floor($x/2); }   function double($x) { return $x*2; }   function iseven($x) { return !($x & 0x1); }   function ethiopicmult($plier, $plicand, $tutor) { if ($tutor) echo "ethiopic multiplication of $plier and $plicand\n"; $r = 0; while($plier >= 1) { if ( !iseven($plier)...
Give a code snippet in #PHP Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wri...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Shen
Shen
  (define encodeGlyphs ACC 0 _ -> ACC ACC N [Glyph Value | Rest] -> (encodeGlyphs (@s ACC Glyph) (- N Value) [Glyph Value | Rest]) where (>= N Value) ACC N [Glyph Value | Rest] -> (encodeGlyphs ACC N Rest) )   (define encodeRoman N -> (encodeGlyphs "" N ["M" 1000 "CM" 900 "D" 500 "CD" 400 "C" 100 "XC" 90 "L" 50...
Give a code snippet in #Shen Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a valu...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#D
D
import std.conv; import std.exception; import std.range; import std.stdio; import std.string;   void main() { foreach (size_t i, dstring line; File("days_of_week.txt").lines) { line = chomp(line); if (!line.empty) { auto days = line.split; enforce(days.length==7, text("There ...
Give a code snippet in #D The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#Harbour
Harbour
  PROCEDURE Main() LOCAL a1 := { "a", "b", "c" }, ; a2 := { "A", "B", "C", "D" }, ; // the last element "D" of this array will be ignored a3 := { 1, 2, 3 } LOCAL e1, e2, e3   FOR EACH e1, e2, e3 IN a1, a2, a3 Qout( e1 + e2 + hb_ntos( e3 ) ) NEXT RETURN  
Give a code snippet in #Harbour Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this ex...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Go
Go
package main   import "fmt"   func main() { fmt.Println(mode([]int{2, 7, 1, 8, 2})) fmt.Println(mode([]int{2, 7, 1, 8, 2, 8})) }   func mode(a []int) []int { m := make(map[int]int) for _, v := range a { m[v]++ } var mode []int var n int for k, v := range m { switch { ...
Give a code snippet in #Go Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possi...
christopher/rosetta-code
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...
#Axiom
Axiom
(open,closed,change,open?) := (true,false,not,test); doors := bits(100,closed); for i in 1..#doors repeat for j in i..#doors by i repeat doors.j := change doors.j [i for i in 1..#doors | open? doors.i]  
Give a code snippet in #Axiom 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, .....
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Crystal
Crystal
# Method to calculate sum of Float64 array def sum(array : Array(Float64)) res = 0 array.each do |n| res += n end res end   # Method to calculate which char appears how often def histogram(source : String) hist = {} of Char => Int32 l = 0 source.each_char do |e| if !hist.has_key? e hist[e] =...
Give a code snippet in #Crystal Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary)...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Red
Red
>>str1: "Hello" >>str2: append str1 " World" >> print str2 Hello World >> print str1 Hello World
Give a code snippet in #Red String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string liter...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int I, X, Y, W, H; [Cursor(10, 13); \set cursor to arbitrary location on screen I:= ChIn(1); \wait for keystroke (no echo to display) ChOut(0, $08\BS\); \backspace moves one position right I:= ChIn(1); X:= Peek($40, $50); \get cursor loca...
Give a code snippet in #XPL0 Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (witho...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning
Terminal control/Cursor positioning
Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
#AutoHotkey
AutoHotkey
DllCall( "AllocConsole" ) ; create a console if not launched from one hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )   DllCall("SetConsoleCursorPosition", UPtr, hConsole, UInt, (6 << 16) | 3) WriteConsole(hConsole, "Hello")   MsgBox   WriteConsole(hConsole, text){ VarSetCapacity(out, 16) If DllCall( "Write...
Give a code snippet in #AutoHotkey Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Mercury
Mercury
:- module guess. :- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module random, string.   main(!IO) :- time(Time, !IO), random.init(Time, Rand), random.random(1, 10, N, Rand, _), main(from_int(N) ++ "\n", !IO).   :- pred main(string::i...
Give a code snippet in #Mercury Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#Clojure
Clojure
(ns inverted-index.core (:require [clojure.set :as sets] [clojure.java.io :as io]))   (def pattern #"\w+") ; Java regex for a raw term: here a substring of alphanums (defn normalize [match] (.toLowerCase match)) ; normalization of a raw term   (defn term-seq [text] (map normalize (re-seq pattern text...
Give a code snippet in #Clojure An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / ...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#XPL0
XPL0
include c:\cxpl\stdlib; char Dict(10,10); int Entries;   proc AddEntry(Letter, Greek); \Insert entry into associative array char Letter, Greek; [Dict(Entries,0):= Letter; StrCopy(Greek, @Dict(Entries,1)); Entries:= Entries+1; \(limit checks ignored for simplicity) ];   func Lookup(Greek); \Giv...
Give a code snippet in #XPL0 Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, E...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Euphoria
Euphoria
  include std/console.e include std/math.e   atom x = 0   loop do x += 1 ?x until(mod(x,6)) = 0 end loop   if getc(0) then end if  
Give a code snippet in #Euphoria Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#BASIC
BASIC
DIM i AS Integer DIM row AS Integer DIM nrows AS Integer DIM values(100) AS Integer   INPUT "Number of rows: "; nrows values(1) = 1 PRINT TAB((nrows)*3);" 1" FOR row = 2 TO nrows PRINT TAB((nrows-row)*3+1); FOR i = row TO 1 STEP -1 values(i) = values(i) + values(i-1) ...
Give a code snippet in #BASIC Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#PicoLisp
PicoLisp
(de modinv (A B) (let (B0 B X0 0 X1 1 Q 0 T1 0) (while (< 1 A) (setq Q (/ A B) T1 B B (% A B) A T1 T1 X0 X0 (- X1 (* Q X0)) X1 T1 ) ) (if (lt0 X1) (+ X1 B0) X1) ) )   (println (modinv 42 2017) )   (bye)
Give a code snippet in #PicoLisp From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#PicoLisp
PicoLisp
(de accu1 (Var Key) (if (assoc Key (val Var)) (con @ (inc (cdr @))) (push Var (cons Key 1)) ) Key ) (de factor (N) (let (R NIL D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N) ) (while (>= M D) (if (=0 (% N D)) (setq M (sqrt (...
Give a code snippet in #PicoLisp Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#FreeBASIC
FreeBASIC
'Graphic fast Fourier transform demo, 'press any key for the next image. '131072 samples: the FFT is fast indeed.   'screen resolution const dW = 800, dH = 600 '-------------------------------------- type samples declare constructor (byval p as integer)   'sw = 0 forward transform 'sw = 1 reverse transform dec...
Give a code snippet in #FreeBASIC Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the m...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Ruby
Ruby
use std::collections::HashMap; use std::env; use std::fs::File; use std::io::prelude::*; use std::io::stdin; use std::num::Wrapping;   fn main() { let args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("Usage: {} [path] (--debug)", args[0]); return; }   let src: Vec<char>...
Give a code snippet in #Ruby Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly impleme...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always ...
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de hidato (Lst) (let Grid (grid (length (maxi length Lst)) (length Lst)) (mapc '((G L) (mapc '((This Val) (nond (Val (with (: 0 1 1) (con (: 0 1))) # Cut off west ...
Give a code snippet in #PicoLisp The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always con...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#C.2B.2B
C++
#include <iostream> #include <sstream>   class Vector3D { public: Vector3D(double x, double y, double z) { this->x = x; this->y = y; this->z = z; }   double dot(const Vector3D& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; }   Vector3D operator-(const Vector3D& rhs) const { return Vector3D(x - r...
Give a code snippet in #C.2B.2B Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector o...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Arturo
Arturo
n: random 1 10 while ø [ try? [ num: to :integer input "Guess the number: " n case [num] when? [=n][print "\tWell Guessed! :)", exit] when? [>n][print "\tHigher than the target..."] when? [<n][print "\tLess than the target..."] else [] ] else -...
Give a code snippet in #Arturo Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: h...
christopher/rosetta-code
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algor...
#REXX
REXX
/* REXX (required by some interpreters) */ Numeric Digits 1000000 ttest ='[(10, 13), (56, 101), (1030, 10009), (44402, 100049)]' Do While pos('(',ttest)>0 Parse Var ttest '(' n ',' p ')' ttest r = tonelli(n, p) Say "n =" n "p =" p Say " roots :" r (p - r) End Exit   legendre: Procedure Parse Arg a,...
Give a code snippet in #REXX This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number th...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Pop11
Pop11
define reverse_string(s); lvars i, l = length(s); for i from l by -1 to 1 do s(i); endfor; consstring(l); enddefine;
Give a code snippet in #Pop11 Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
christopher/rosetta-code
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,...
#VBScript
VBScript
'Arrays - VBScript - 08/02/2021 'create a static array Dim a(3) ' 4 items : a(0), a(1), a(2), a(3) 'assign a value to elements For i = 1 To 3 a(i) = i * i Next 'and retrieve elements buf="" For i = 1 To 3 buf = buf & a(i) & " " Next WScript.Echo buf   'create ...
Give a code snippet in #VBScript 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 re...
christopher/rosetta-code
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...
#Arturo
Arturo
zigzag: function [n][ result: map 1..n 'x -> map 1..n => 0   x: 1, y: 1, v: 0, d: 1   while [v < n^2][ if? all? @[1 =< x x =< n 1 =< y y =< n][ set get result (y-1) (x-1) v x: x + d, y: y - d, v: v + 1 ] else[if? x > n [x: n, y: y + 2, d: neg d] el...
Give a code snippet in #Arturo 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 en...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#Racket
Racket
  #lang racket (define (reduce e) (match e [(? number? a) a] [(list '+ (? number? a) (? number? b)) (+ a b)] [(list '- (? number? a) (? number? b)) (- a b)] [(list '- (? number? a)) (- a)] [(list '* (? number? a) (? number? b)) (* a b)] [(list '/ (? number...
Give a code snippet in #Racket Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing ...
christopher/rosetta-code
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Lasso
Lasso
define dint => type { data private value   public oncreate(value::integer) => { fail_if(#value < 1,#value+' less than 1 ') fail_if(#value > 10,#value+' greater than 10') .value = #value }   public +(rhs::integer) => dint(.value + #rhs) public -(rhs::integer) => dint(.value - #rhs) public *(rhs::int...
Give a code snippet in #Lasso Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
christopher/rosetta-code
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#Phix
Phix
with javascript_semantics constant circles = {{ 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.249589...
Give a code snippet in #Phix Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#XPL0
XPL0
func Chowla(N); \Return sum of divisors int N, Div, Sum, Quot; [Div:= 2; Sum:= 0; loop [Quot:= N/Div; if Quot < Div then quit; if Quot = Div and rem(0) = 0 then \N is a square [Sum:= Sum+Quot; quit]; if rem(0) = 0 then Sum:= Sum + Div + Quot; Div:= D...
Give a code snippet in #XPL0 Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs ...
#Phix
Phix
function spermutations(integer p, integer i) -- -- generate the i'th permutation of [1..p]: -- first obtain the appropriate permutation of [1..p-1], -- then insert p/move it down k(=0..p-1) places from the end. -- sequence res integer k = mod(i-1,2*p) if k>=p then k=2*p-1-k end if if p>1 then ...
Give a code snippet in #Phix Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#OCaml
OCaml
print_string "Goodbye, World!"
Give a code snippet in #OCaml Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Stand...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algor...
#Scala
Scala
object CombSort extends App { val ia = Array(28, 44, 46, 24, 19, 2, 17, 11, 25, 4) val ca = Array('X', 'B', 'E', 'A', 'Z', 'M', 'S', 'L', 'Y', 'C')   def sorted[E](input: Array[E])(implicit ord: Ordering[E]): Array[E] = { import ord._ var gap = input.length var swapped = true while (gap > 1 || swa...
Give a code snippet in #Scala Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare s...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Applesoft_BASIC
Applesoft BASIC
100 W = 8 110 H = 8 120 BA = 24576 130 HIMEM: 8192 140 D$ = CHR$ (4) 150 M$ = CHR$ (13) 160 P6$ = "P6" + M$ + STR$ (W) + " " + STR$ (H) + M$ + "255" + M$ 170 FOR I = 1 TO LEN (P6$) 180 POKE BA + I - 1, ASC ( MID$ (P6$,I,1)) 190 NEXT I 200 BB = BA + I - 1 210 BL = (BB + W * H * 3) - BA 220 C = ...
Give a code snippet in #Applesoft_BASIC Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
christopher/rosetta-code
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...
#Raku
Raku
class Turtle { my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1]; my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc.   has @.loc = 0,0; has $.dir = 0; has %.world; has $.maxegg; has $.range-x; has $.range-y;   method turn-...
Give a code snippet in #Raku 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 enco...
christopher/rosetta-code
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  
Give a code snippet in #M2000_Interpreter 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Cowgol
Cowgol
include "cowgol.coh";   const AMOUNT := 15; typedef I is uint16;   sub divisors(n: I): (count: I) is var i: I := 1; count := 0;   while i*i <= n loop if n%i == 0 then if n/i == i then count := count + 1; else count := count + 2; en...
Give a code snippet in #Cowgol Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors S...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#11l
11l
F processString(input) [Char = Int] charMap V dup = Char("\0") V index = 0 V pos1 = -1 V pos2 = -1 L(key) input index++ I key C charMap dup = key pos1 = charMap[key] pos2 = index L.break charMap[key] = index V unique = I dup == Char("\0") {‘yes’...
Give a code snippet in #11l Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Euphoria
Euphoria
function to_gray(sequence image) sequence color for i = 1 to length(image) do for j = 1 to length(image[i]) do color = and_bits(image[i][j], {#FF0000,#FF00,#FF}) / {#010000,#0100,#01} -- unpack color triple image[i][j] = floor(0.2126*colo...
Give a code snippet in #Euphoria Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversi...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Microsoft_Small_Basic
Microsoft Small Basic
  n = 12 For j = 1 To n - 1 TextWindow.CursorLeft = (j - 1) * 4 + (3 - Text.GetLength(j)) TextWindow.Write(j) TextWindow.Write(" ") EndFor TextWindow.CursorLeft = (n - 1) * 4 + (3 - Text.GetLength(n)) TextWindow.Write(n) TextWindow.WriteLine("") For j = 0 To n - 1 TextWindow.Write("----") EndFor TextWindow.Writ...
Give a code snippet in #Microsoft_Small_Basic Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Go
Go
package main   import ( "fmt" "strings" )   var ( dig = [3]string{"00", "01", "10"} dig1 = [3]string{"", "1", "10"} )   type Zeckendorf struct{ dVal, dLen int }   func NewZeck(x string) *Zeckendorf { z := new(Zeckendorf) if x == "" { x = "0" } q := 1 i := len(x) - 1 z.dL...
Give a code snippet in #Go 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 f...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Clojure
Clojure
(def evals '((. "abcd" startsWith "ab") (. "abcd" endsWith "zn") (. "abab" contains "bb") (. "abab" contains "ab") (. "abab" indexOf "bb") (let [loc (. "abab" indexOf "ab")] (. "abab" indexOf "ab" (dec loc)))))   user> (for [i evals] [i (eval i)]) ([(. "abcd" startsWith "ab") true]...
Give a code snippet in #Clojure Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Genie
Genie
[indent=4]   init str:string = "Hello,How,Are,You,Today" words:array of string[] = str.split(",") joined:string = string.joinv(".", words) print joined
Give a code snippet in #Genie Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks re...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Name_Game
The Name Game
Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like this: Gary, Gary, bo-bary...
#PowerShell
PowerShell
  ## Clear Host from old Ouput Clear-Host   $Name = Read-Host "Please enter your name" $Char = ($name.ToUpper())[0] IF (($Char -eq "A") -or ($Char -eq "E") -or ($Char -eq "I") -or ($Char -eq "O") -or ($Char -eq "U")) { Write-Host "$Name, $Name, bo-b$($Name.ToLower())" } else { IF ($Char -eq "B") { ...
Give a code snippet in #PowerShell Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would b...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Swift
Swift
extension BinaryInteger { @inlinable public func factors(sorted: Bool = true) -> [Self] { let maxN = Self(Double(self).squareRoot()) var res = Set<Self>()   for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 { res.insert(factor) res.insert(self / factor) }   ...
Give a code snippet in #Swift An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alter...
christopher/rosetta-code
http://rosettacode.org/wiki/Object_serialization
Object serialization
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o...
#Perl
Perl
{ package Greeting; sub new { my $v = "Hello world!\n"; bless \$v, shift; }; sub stringify { ${shift()}; }; }; { package Son::of::Greeting; use base qw(Greeting); # inherit methods sub new { # overwrite method of super class my $v = "Hello world from Juni...
Give a code snippet in #Perl Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Component_Pascal
Component Pascal
  MODULE Hello; IMPORT Out;   PROCEDURE Do*; BEGIN Out.String("Hello world!"); Out.Ln END Do; END Hello.
Give a code snippet in #Component_Pascal Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Stand...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#TorqueScript
TorqueScript
$string = "alphaBETA"; $upperCase = strUpr($string); $lowerCase = strLwr($string);
Give a code snippet in #TorqueScript Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper i...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#PureBasic
PureBasic
#answerSize = 4 Structure history answer.s bulls.i cows.i EndStructure   Procedure evaluateGuesses(*answer.history, List remainingGuesses.s()) Protected i, cows, bulls   ForEach remainingGuesses() bulls = 0: cows = 0 For i = 1 To #answerSize If Mid(remainingGuesses(), i, 1) = Mid(*answer\answer...
Give a code snippet in #PureBasic Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only t...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
LastSundays[year_] := Table[Last@ DayRange[{year, i}, DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i, 12}] LastSundays[2013]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-2...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#Vlang
Vlang
fn analyze(s string) { chars := s.runes() le := chars.len println("Analyzing $s which has a length of $le:") if le > 1 { for i in 1..le{ if chars[i] != chars[i-1] { println(" Not all characters in the string are the same.") println(" '${chars[i]}' (0...
Give a code snippet in #Vlang Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mastermind
Mastermind
Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may be repeated in the code The (...
#Go
Go
package main   import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" )   func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number o...
Give a code snippet in #Go Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#Fortran
Fortran
subroutine easter(year,month,day) c Easter sunday c c Input c year c Output c month c day c c See: c Jean Meeus, "Astronomical Formulae for Calculators", c 4th edition, Willmann-Bell, 1988, p.31 implicit integer(a-z) a=mod(year,19) b=year/100 c=mod(year,100) d=b/4 e=mod(b...
Give a code snippet in #Fortran Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   ye...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#MiniScript
MiniScript
for i in range(1,5) s = "" for j in range(1, i) s = s + "*" end for print s end for
Give a code snippet in #MiniScript “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract st...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#QB64
QB64
  'Task 'Take a combined set of elements and apply a function to each element. 'UDT Type Friend Names As String * 8 Surnames As String * 8 Age As Integer End Type   Dim Friends(1 To 6) As Friend Restore FillArray SearchForAdult Friends(), LBound(friends), UBound(friends)   End   Data "John","Beoz",13,"Will"...
Give a code snippet in #QB64 Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Python
Python
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r ...
Give a code snippet in #Python Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenie...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Action.21
Action!
PROC Generate(BYTE ARRAY seq INT POINTER count INT minCount,maxVal) INT i   seq(0)=1 seq(1)=1 count^=2 i=1 WHILE count^<minCount OR seq(count^-1)#maxVal AND seq(count^-2)#maxVal DO seq(count^)=seq(i-1)+seq(i) seq(count^+1)=seq(i) count^==+2 i==+1 OD RETURN   PROC PrintSeq(BYTE ARRAY seq INT count)...
Give a code snippet in #Action.21 For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered m...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#D
D
import std.stdio, std.random;   void main() { while (true) { int r = uniform(0, 20); write(r, " "); if (r == 10) break; write(uniform(0, 20), " "); } }
Give a code snippet in #D Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If t...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Raku
Raku
subset Palindrom of Str where { .flip eq $_ given .comb(/\w+/).join.lc }   my @tests = q:to/END/.lines; A man, a plan, a canal: Panama. My dog has fleas Madam, I'm Adam. 1 on 1 In girum imus nocte et consumimur igni END   for @tests { say $_ ~~ Palindrom, "\t", $_ }
Give a code snippet in #Raku A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Quoting_constructs
Quoting constructs
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati...
#zkl
zkl
#<<< text:= " A "; #<<<
Give a code snippet in #zkl Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their ...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#6502_Assembly
6502 Assembly
;DEFINE 0 AS FALSE, $FF as true. False equ 0 True equ 255 Func_A: ;input: accumulator = value to check. 0 = false, nonzero = true. ;output: 0 if false, 255 if true. Also prints the truth value to the screen. ;USAGE: LDA val JSR Func_A BEQ .falsehood load16 z_HL,BoolText_A_True ;lda #<BoolText_A_True sta z_L lda #>...
Give a code snippet in #6502_Assembly Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes consider...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Processing
Processing
fullScreen(); noStroke(); color[] cs = { color(0), // black color(255,0,0), // red color(0,255,0), // green color(255,0,255), // magenta color(0,255,255), // cyan color(255,255,0), // yellow color(255) // white }; for(int i=0; i<7; i++) { fill(cs[i]); rect(i*width/8,0,width/8,height...
Give a code snippet in #Processing Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Common_Lisp
Common Lisp
  ;;Tested using CLISP   (defun VanEck (x) (reverse (VanEckh x 0 0 '(0))))   (defun VanEckh (final index curr lst) (if (eq index final) lst (VanEckh final (+ index 1) (howfar curr lst) (cons curr lst))))   (defun howfar (x lst) (howfarh x lst 0))   (defun howfarh (x lst runningtotal) (cond ((null lst) 0) ((...
Give a code snippet in #Common_Lisp The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term o...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Eratosthenes[n_] := Module[{numbers = Range[n]}, Do[If[numbers[[i]] != 0, Do[numbers[[i j]] = 0, {j, 2, n/i}]], {i, 2, Sqrt[n]}]; Select[numbers, # > 1 &]]   Eratosthenes[100]
Give a code snippet in #Mathematica.2FWolfram_Language This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#BaCon
BaCon
INPUT "Your string: ", s$   IF REGEX(s$, "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$") THEN PRINT "This is a number" ELSE PRINT "Not a number" ENDIF
Give a code snippet in #BaCon Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics A...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#XPL0
XPL0
include xpllib; char A, B, C(80); [A:= "Hello, "; B:= "world!"; StrCopy(C, A); StrCat(C, B); Text(0, C); ]
Give a code snippet in #XPL0 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#AutoHotkey
AutoHotkey
cube := [], counter:=0 while counter<30 { cube[(n := A_Index)**3] := true if !cube[n**2] counter++, res .= n**2 " " else res .= "[" n**2 "] " } MsgBox % Trim(res, " ")
Give a code snippet in #AutoHotkey Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Julia
Julia
  using Combinatorics, StatsBase   namesofline(n) = counts([x[1] for x in integer_partitions(n)])   function centerjustpyramid(n) maxwidth = length(string(namesofline(n))) for i in 1:n s = string(namesofline(i)) println(" " ^ div(maxwidth - length(s), 2), s) end end   centerjustpyramid(25)  ...
Give a code snippet in #Julia This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Racket
Racket
#lang racket (require (planet neil/csv:1:=7) net/url)   (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t))))   (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row)...
Give a code snippet in #Racket CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, cha...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
listener = SocketListen["127.0.0.1:8080", Function[{assoc}, With[{client = assoc["SourceSocket"]}, WriteString[client, "HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"]; Close[client]]]] SystemOpen["http://127.0.0.1:8080"]
Give a code snippet in #Mathematica.2FWolfram_Language The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves...
christopher/rosetta-code
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Haskell
Haskell
import System.Random import qualified Data.Set as S import Text.Printf   findRep :: (Random a, Integral a, RandomGen b) => a -> b -> (a, b) findRep n gen = findRep' (S.singleton 1) 1 gen where findRep' seen len gen' | S.member fx seen = (len, gen'') | otherwise = findRep' (S.insert ...
Give a code snippet in #Haskell Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Scala
Scala
scala> val s1 = Set("John", "Serena", "Bob", "Mary", "Serena") s1: scala.collection.immutable.Set[java.lang.String] = Set(John, Serena, Bob, Mary)   scala> val s2 = Set("Jim", "Mary", "John", "Jim", "Bob") s2: scala.collection.immutable.Set[java.lang.String] = Set(Jim, Mary, John, Bob)   scala> (s1 diff s2) union (s2 d...
Give a code snippet in #Scala Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#AppleScript
AppleScript
display dialog "Goodbye, World!" buttons {"Bye"}
Give a code snippet in #AppleScript Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have b...
#Icon_and_Unicon
Icon and Unicon
link graphics   procedure main()   Delay := 3000   W1 := open("Window 1","g","resize=on","size=400,400","pos=100,100","bg=black","fg=red") | stop("Unable to open window 1") W2 := open("Window 2","g","resize=on","size=400,400","pos=450,450","bg=blue","fg=yellow") | stop("Unable to open window ...
Give a code snippet in #Icon_and_Unicon Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program loop64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.i...
Give a code snippet in #AArch64_Assembly “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstr...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Icon_and_Unicon
Icon and Unicon
procedure main() a := "+-0++0+" write("a = +-0++0+"," = ",cvtFromBT("+-0++0+")) write("b = -436 = ",b := cvtToBT(-436)) c := "+-++-" write("c = +-++- = ",cvtFromBT("+-++-")) d := mul(a,sub(b,c)) write("a(b-c) = ",d," = ",cvtFromBT(d)) end   procedure bTrim(s) return s[upto('+-',s):0] | "...
Give a code snippet in #Icon_and_Unicon Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 +...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
Find palindromic numbers in both binary and ternary bases
Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base 2   base 3   Display   0   ...
#Racket
Racket
#lang racket (require racket/generator)   (define (digital-reverse/base base N) (define (inr n r) (if (zero? n) r (inr (quotient n base) (+ (* r base) (modulo n base))))) (inr N 0))   (define (palindrome?/base base N) (define (inr? n m) (if (= n 0) (= m N) (inr? (quotient n base) (+ (* m b...
Give a code snippet in #Racket Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   ba...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Perl
Perl
my $s = "12345"; $s++;
Give a code snippet in #Perl Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If th...
#Java
Java
  import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;   public class NextHighestIntFromDigits {   public static void main(String[] args) { for ( String s : new String[] {"...
Give a code snippet in #Java Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear ...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#Scheme
Scheme
(define (factors n) (let facs ((l '()) (d 2) (x n)) (cond ((= x 1) (if (null? l) '(1) l)) ((< x (* d d)) (cons x l)) (else (if (= 0 (modulo x d)) (facs (cons d l) d (/ x d)) (facs l (+ 1 d) x))))))   (define (show l) (display (car l)) (if (not (null? (cdr l))) (begin (display " × ") ...
Give a code snippet in #Scheme Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it woul...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   INT FUNC PowerI(INT base,exp) INT res,i   IF exp<0 THEN Break() FI   res=1 FOR i=1 TO exp DO res==*base OD RETURN (res)   PROC PowerR(REAL POINTER base INT exp REAL POINTER res) INT i REAL tmp   IF exp<0 THEN Break() FI   IntToReal(1...
Give a code snippet in #Action.21 Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#PHP
PHP
  define('PRECISION', 13);   function agm($a0, $g0, $tolerance = 1e-10) { // the bc extension deals in strings and cannot convert // floats in scientific notation by itself - hence // this manual conversion t...
Give a code snippet in #PHP This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#C.2B.2B
C++
#include <iostream>   int main () { std::cout << "Hello world!" << std::endl; }
Give a code snippet in #C.2B.2B Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Exam...
#Ruby
Ruby
require 'HLPsolver'   ADJACENT = [[-1, 0], [0, -1], [0, 1], [1, 0]]   board1 = <<EOS 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 ...
Give a code snippet in #Ruby Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end no...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#Fortran
Fortran
function agm(a,b) implicit none double precision agm,a,b,eps,c parameter(eps=1.0d-15) 10 c=0.5d0*(a+b) b=sqrt(a*b) a=c if(a-b.gt.eps*a) go to 10 agm=0.5d0*(a+b) end program test implicit none double precision agm print*,agm(1.0d0,1.0d0/sqr...
Give a code snippet in #Fortran This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#OpenEdge.2FProgress
OpenEdge/Progress
DEFINE VARIABLE print_str AS CHAR NO-UNDO INIT ''. DEFINE VARIABLE X1 AS DECIMAL NO-UNDO INIT 50. DEFINE VARIABLE Y1 AS DECIMAL NO-UNDO INIT 21. DEFINE VARIABLE X AS DECIMAL NO-UNDO. DEFINE VARIABLE Y AS DECIMAL NO-UNDO. DEFINE VARIABLE N AS DECIMAL NO-UNDO. DEFINE VARIABLE I3 AS DECIMAL NO-UNDO. DEFINE VARIABLE R3 AS ...
Give a code snippet in #OpenEdge.2FProgress Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate i...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#Python
Python
def levenshteinDistance(str1, str2): m = len(str1) n = len(str2) d = [[i] for i in range(1, m + 1)] # d matrix rows d.insert(0, list(range(0, n + 1))) # d matrix columns for j in range(1, n + 1): for i in range(1, m + 1): if str1[i - 1] == str2[j - 1]: # Python (string) is ...
Give a code snippet in #Python This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and co...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#PHP
PHP
<? class Foo { function bar(int $x) { } }   $method_names = get_class_methods('Foo'); foreach ($method_names as $name) { echo "$name\n"; $method_info = new ReflectionMethod('Foo', $name); echo $method_info; } ?>
Give a code snippet in #PHP Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#PL.2FI
PL/I
perfect: procedure (n) returns (bit(1)); declare n fixed; declare sum fixed; declare i fixed binary;   sum = 0; do i = 1 to n-1; if mod(n, i) = 0 then sum = sum + i; end; return (sum=n); end perfect;
Give a code snippet in #PL.2FI Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itsel...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#VBA
VBA
Option Explicit Sub Test() Dim h As Object, i As Long, u, v, s Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3   'Iterate on keys For Each s In h.Keys Debug.Print s Next   'Iterate on values For Each s In h.Items Debug.Print s ...
Give a code snippet in #VBA Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compo...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#ABAP
ABAP
with Ada.Float_Text_IO; with Ada.Text_IO; with Ada.Numerics.Discrete_Random; procedure Game_24 is subtype Digit is Character range '1' .. '9'; package Random_Digit is new Ada.Numerics.Discrete_Random (Digit); Exp_Error : exception; Digit_Generator : Random_Digit.Generator; Given_Digits : array (1 .. 4) o...
Give a code snippet in #ABAP The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four dig...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols
Idiomatically determine all the characters that can be used for symbols
Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ...
#Phix
Phix
without js -- file i/o, system_exec, \t and \r chars function run(string ident) integer fn = open("test.exw","w") printf(fn,"object %s",ident) close(fn) return system_exec("p -batch test.exw") end function function check(integer lo, hi) string ok1 = "", ok2 = "" integer ng1 = 0, ng2 = 0 fo...
Give a code snippet in #Phix Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer p...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#Groovy
Groovy
class Cusip { private static Boolean isCusip(String s) { if (s.length() != 9) return false int sum = 0 for (int i = 0; i <= 7; i++) { char c = s.charAt(i)   int v if (c >= ('0' as char) && c <= ('9' as char)) { v = c - 48 } else...
Give a code snippet in #Groovy This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A   CUSIP   is a nine-character alphanumeri...
christopher/rosetta-code
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#MATLAB
MATLAB
function FlippingBitsGame(n) % Play the flipping bits game on an n x n array   % Generate random target array fprintf('Welcome to the Flipping Bits Game!\n') if nargin < 1 n = input('What dimension array should we use? '); end Tar = logical(randi([0 1], n));   % Generate starting array b...
Give a code snippet in #MATLAB The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one mo...
christopher/rosetta-code
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to ...
#BQN
BQN
GCD ← {m 𝕊⍟(0<m←𝕨|𝕩) 𝕨} _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} Sim ← { # Simplify a fraction x𝕊1: 𝕨‿1; 0𝕊y: 0‿𝕩; ⌊𝕨‿𝕩 ÷ 𝕨 GCD 𝕩 } Add ← { # Add two fractions 0‿b 𝕊 𝕩: 𝕩; 𝕨 𝕊 0‿y: 𝕨; a‿b 𝕊 x‿y: ((a×y)+x×b) Sim b×y } Next ← {n‿d: ⌽(2×⌊÷´n‿d)‿1 Add (d-n)‿d} # Next term Cal ← {Next⍟𝕩 1‿1}   •S...
Give a code snippet in #BQN The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (also trivalent, ternary, or trinary...
#REXX
REXX
/*REXX program displays a ternary truth table [true, false, maybe] for the variables */ /*──── and one or more expressions. */ /*──── Infix notation is supported with one character propositional constants. */ /*──── Variables (propositional constants) allo...
Give a code snippet in #REXX This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (also ...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Fortran
Fortran
program to_f_the_ineffable use, intrinsic :: ieee_arithmetic integer :: i real dimension(2) :: y, x = (/ 30, ieee_value(y,ieee_positive_inf) /)   do i = 1, 2 if (ieee_support_datatype(x(i))) then if (ieee_is_finite(x(i))) then print *, 'x(',i,') is finite' else ...
Give a code snippet in #Fortran Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwis...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#D
D
import std.stdio, std.range, std.algorithm, std.typecons, std.conv;   Tuple!(double[], double[]) polyDiv(in double[] inN, in double[] inD) nothrow pure @safe { // Code smell: a function that does two things. static int trimAndDegree(T)(ref T[] poly) nothrow pure @safe @nogc { poly = poly.retro.find!q{ a...
Give a code snippet in #D This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long div...
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Racket
Racket
$ racket -e "(displayln \"Hello World\")" Hello World
Give a code snippet in #Racket Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementat...
christopher/rosetta-code