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/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#MATLAB
MATLAB
function [output] = matrixexponentiation(matrixA, exponent) output = matrixA^(exponent);
Give a code snippet in #MATLAB Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#zkl
zkl
var BN=Import("zklBigNum"), bi=BN(0); // gonna recycle bi primes:=T(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61); var p2,p3; cs:=[[(p1,h3,d); primes; { [2..p1 - 1] }; // list comprehension { [1..h3 + p1 - 1] }, { ((h3 + p1)*(p1 - 1)%d == 0 and ((-p1*p1):mod(_,h3) == d%h3)) },//guard { (p2=1 + (p1 - 1)*(h3...
Give a code snippet in #zkl A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investi...
christopher/rosetta-code
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#D
D
  import std.stdio; import std.format; import std.bigint; import std.math; import std.algorithm;     int sieveLimit = 1300_000;   bool[] notPrime;   void main() { // initialize sieve(sieveLimit);   // output 1 foreach (i; 0..10) writefln("primorial(%d): %d", i, primorial(i));   // output 2 foreach (i; ...
Give a code snippet in #D Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Raku
Raku
my @names = < audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone...
Give a code snippet in #Raku A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the cat...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Forth
Forth
char a dup . \ 97 emit \ a
Give a code snippet in #Forth Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conv...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#ALGOL_68
ALGOL 68
PROC test non continuous = VOID: BEGIN MODE SEQMODE = CHAR; MODE SEQ = [1:0]SEQMODE; MODE YIELDSEQ = PROC(SEQ)VOID;   PROC gen ncs = ( SEQ tail, # To generate subsequences of # SEQ head, # Already generated # BOOL contiguous,# It is st...
Give a code snippet in #ALGOL_68 Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Ring
Ring
  # Project : Undefined values   test() func test x=10 y=20 see islocal("x") + nl + islocal("y") + nl + islocal("z") + nl  
Give a code snippet in #Ring
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Fantom
Fantom
  class Main { static Int gcd (Int a, Int b) { a = a.abs b = b.abs while (b > 0) { t := a a = b b = t % b } return a }   public static Void main() { echo ("GCD of 51, 34 is: " + gcd(51, 34)) } }  
Give a code snippet in #Fantom Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greates...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#BQN
BQN
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} Root ← √ Root1 ← ⋆⟜÷˜ Root2 ← { n 𝕊 a‿prec: 1⊑{ p‿x: ⟨ x ((p × n - 1) + a ÷ p ⋆ n - 1) ÷ n ⟩ } _while_ { p‿x: prec ≤ | p - x } ⟨a, ⌊a÷n⟩; 𝕨 𝕊 𝕩: 𝕨 𝕊 𝕩‿1E¯5 }   •Show 3 Root 5 •Show 3 Root1 5 •Show 3 Root2 5 •Show 3 Root2 5‿1E¯16
Give a code snippet in #BQN Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program loopwhile64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
Give a code snippet in #AArch64_Assembly Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic code declarations define Balls = 80; \maximum number of balls int Bx(Balls), By(Balls), \character cell coordinates of each ball W, I, J, Peg, Dir; [W:= Peek($40, $4A); \get screen width in characters Clear; CrLf(6); CrLf(6); for Peg:= 1...
Give a code snippet in #XPL0 Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#FreeBASIC
FreeBASIC
#Include "crt.bi" 'for rounding only   Type vector Dim As Double element(Any) End Type   Type matrix Dim As Double element(Any,Any) Declare Function inverse() As matrix Declare Function transpose() As matrix private: Declare Function GaussJordan(As vector) As vector End Type   'mult operators O...
Give a code snippet in #FreeBASIC Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coeffici...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#REXX
REXX
if y then @=6 /* Y must be either 0 or 1 */   if t**2>u then x=y /*simple IF with THEN & ELSE. */ else x=-y   if t**2>u then do j=1 for 10; say prime(j); end /*THEN DO loop.*/ else x=-y /*simple ELSE....
Give a code snippet in #REXX Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common c...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#smart_BASIC
smart BASIC
'Single line comments are preceded by a single quote or the command REM   PRINT "Hello" 'Single line comments may follow code   PRINT "Hello" REM You can also use the command REM following code   /* Multi-line comments are surrounded by mirrored slash and asterisk */   /*Multi-line comments do not have to actually hav...
Give a code snippet in #smart_BASIC Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Scheme
Scheme
(define (carpet n) (define (in-carpet? x y) (cond ((or (zero? x) (zero? y)) #t) ((and (= 1 (remainder x 3)) (= 1 (remainder y 3))) #f) (else (in-carpet? (quotient x 3) (quotient y 3)))))   (do ((i 0 (+ i 1))) ((not (< i (expt 3 n)))) (do ((j 0 (+...
Give a code snippet in #Scheme Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # #...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#bc
bc
/* greatest common divisor */ define g(m, n) { auto t   /* Euclid's method */ while (n != 0) { t = m m = n n = t % n } return (m) }   /* least common multiple */ define l(m, n) { auto r   if (m == 0 || n == 0) return (0) r = m * n / g(m, n) if (r < 0) return (-r) return (r) }
Give a code snippet in #bc Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has bo...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#PicoLisp
PicoLisp
(de propdiv (N) (make (for I N (and (=0 (% N I)) (link I)) ) ) ) (de sum? (G L) (cond ((=0 G) T) ((= (car L) G) T) ((cdr L) (if (> (car L) G) (sum? G (cdr L)) (or (sum? (- G (car L)) (cdr L)) (sum? G (cdr L)) ) ) ) ) )...
Give a code snippet in #PicoLisp Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the di...
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...
#K
K
perfect:{(x>2)&x=+/-1_{d:&~x!'!1+_sqrt x;d,_ x%|d}x} perfect 33550336 1   a@&perfect'a:!10000 6 28 496 8128   m:3 10#!30 (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29)   perfect'/: m (0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0)
Give a code snippet in #K 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). ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#PicoLisp
PicoLisp
(de recursiveSearch (Val Lst Len) (unless (=0 Len) (let (N (inc (/ Len 2)) L (nth Lst N)) (cond ((= Val (car L)) Val) ((> Val (car L)) (recursiveSearch Val (cdr L) (- Len N)) ) (T (recursiveSearch Val Lst (dec N))) ) ) ) )
Give a code snippet in #PicoLisp A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secre...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#Ruby
Ruby
  def factorion?(n, base) n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n end   (9..12).each do |base| puts "Base #{base} factorions: #{(1..1_500_000).select{|n| factorion?(n, base)}.join(" ")} " end  
Give a code snippet in #Ruby Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,4...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#Prolog
Prolog
%% collect N elements produced by a generator in a row   take( 0, Next, Z-Z, Next). take( N, Next, [A|B]-Z, NZ):- N>0, !, next(Next,A,Next1), N1 is N-1, take(N1,Next1,B-Z,NZ).   %% a generator provides specific {next} implementation   next( hamm( A2,B,C3,D,E5,F,[H|G] ), H, hamm(X,U,Y,V,Z,W,G) ):- H is min(A2, mi...
Give a code snippet in #Prolog Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming num...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Crystal
Crystal
class String def lookandsay gsub(/(.)\1*/){ |s| s.size.to_s + s[0] } end end   ss = '1' 12.times { puts ss; ss = ss.to_s.lookandsay }
Give a code snippet in #Crystal The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequen...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
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 |...
#Pascal
Pascal
program Factors; var i, number: integer; begin write('Enter a number between 1 and 2147483647: '); readln(number);   for i := 1 to round(sqrt(number)) - 1 do if number mod i = 0 then write (i, ' ', number div i, ' ');   // Check to see if number is a square i := round(sqrt(number)); if i*i = n...
Give a code snippet in #Pascal 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. 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) An Achilles number is a number that is powerful but imperfect. Na...
#Julia
Julia
using Primes   isAchilles(n) = (p = [x[2] for x in factor(n).pe]; all(>(1), p) && gcd(p) == 1)   isstrongAchilles(n) = isAchilles(n) && isAchilles(totient(n))   function teststrongachilles(nachilles = 50, nstrongachilles = 100) # task 1 println("First $nachilles Achilles numbers:") n, found = 0, 0 while...
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at Achilles number. 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) An Achilles number is a number tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   ...
#Rust
Rust
use std::fmt;   enum Direction { RIGHT, UP, LEFT, DOWN } use ulam::Direction::*;   /// Indicates whether an integer is a prime number or not. fn is_prime(a: u32) -> bool { match a { 2 => true, x if x <= 1 || x % 2 == 0 => false, _ => { let max = f64::sqrt(a as f64) as u32; ...
Give a code snippet in #Rust An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is show...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
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 algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Tcl
Tcl
package require Tcl 8.5 package require struct::list   proc gnomesort {a} { set i 1 set j 2 set size [llength $a] while {$i < $size} { if {[lindex $a [expr {$i - 1}]] <= [lindex $a $i]} { set i $j incr j } else { struct::list swap a [expr {$i - 1}]...
Give a code snippet in #Tcl 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 algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ...
#Go
Go
package main   import ( "log" "os" "sync" "time" )   // counting semaphore implemented with a buffered channel type sem chan struct{}   func (s sem) acquire() { s <- struct{}{} } func (s sem) release() { <-s } func (s sem) count() int { return cap(s) - len(s) }   // log package serializes output var...
Give a code snippet in #Go The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, rele...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Clojure
Clojure
(doseq [item collection] (println item))
Give a code snippet in #Clojure Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loo...
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 ...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE}   make do io.put_integer (ethiopian_multiplication (17, 34)) end   ethiopian_multiplication (a, b: INTEGER): INTEGER -- Product of 'a' and 'b'. require a_positive: a > 0 b_positive: b > 0 local x, y: INTEGER do x := a y := b from ...
Give a code snippet in #Eiffel 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#Racket
Racket
#lang racket (require math) (define (proper-divisors n) (drop-right (divisors n) 1)) (for ([n (in-range 1 (add1 10))]) (printf "proper divisors of: ~a\t~a\n" n (proper-divisors n))) (define most-under-20000 (for/fold ([best '(1)]) ([n (in-range 2 (add1 20000))]) (define divs (proper-divisors n)) (if (< (len...
Give a code snippet in #Racket The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divi...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
TaskList = Flatten[ Import["http://rosettacode.org/wiki/Category:Programming_Tasks", "Data"][[1, 1]]]; Print["Task \"", StringReplace[#, "_" -> " "], "\" has ", Length@Select[Import["http://rosettacode.org/wiki/" <> #, "Data"][[1,2]], StringFreeQ[#, __ ~~ "Programming Task" | __ ~~ "Omit"]& ], " example(s)"]& ...
Give a code snippet in #Mathematica.2FWolfram_Language task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count e...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#VBScript
VBScript
  'prints a WScript.StdOut.WriteLine Chr(97)   'prints 97 WScript.StdOut.WriteLine Asc("a")  
Give a code snippet in #VBScript Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). C...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#C.23
C#
  using Microsoft.VisualStudio.TestTools.UnitTesting; using PalindromeDetector.ConsoleApp;   namespace PalindromeDetector.VisualStudioTests { [TestClass] public class VSTests { [TestMethod] public void PalindromeDetectorCanUnderstandPalindrome() { //Microsoft.VisualStudio...
Give a code snippet in #C.23 Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Sparkling
Sparkling
for var i = 10; i >= 0; i-- { print(i); }
Give a code snippet in #Sparkling Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/In...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#D
D
import std.stdio;   void main() { int i = 1024;   while (i > 0) { writeln(i); i >>= 1; } }
Give a code snippet in #D Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward fo...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Liberty_BASIC
Liberty BASIC
'[RC]MD5 'from tsh73's January 2008 code   text$="The quick brown fox jumps over the lazy dog" checkSum$="9e107d9d372bb6826bd81d3542a419d6"   print text$ print checkSum$   test$=md5$(text$)   if test$=checkSum$ then print "passed" print test$ else print "failed" ...
Give a code snippet in #Liberty_BASIC Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm t...
christopher/rosetta-code
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#AppleScript
AppleScript
-- thueMorse :: Int -> [Int] on thueMorse(base) -- Non-finite sequence of Thue-Morse terms for a given base. fmapGen(baseDigitsSumModBase(base), enumFrom(0)) end thueMorse     -- baseDigitsSumModBase :: Int -> Int -> Int on baseDigitsSumModBase(b) script on |λ|(n) script go ...
Give a code snippet in #AppleScript The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Rust
Rust
  // Iterator for the combinations of `arr` with `k` elements with repetitions. // Yields the combinations in lexicographical order. struct CombinationsWithRepetitions<'a, T: 'a> { // source array to get combinations from arr: &'a [T], // length of the combinations k: u32, // current counts of each ...
Give a code snippet in #Rust The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Rust
Rust
fn main() { let mut stack = Vec::new(); stack.push("Element1"); stack.push("Element2"); stack.push("Element3");   assert_eq!(Some(&"Element3"), stack.last()); assert_eq!(Some("Element3"), stack.pop()); assert_eq!(Some("Element2"), stack.pop()); assert_eq!(Some("Element1"), stack.pop()); ...
Give a code snippet in #Rust Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is acc...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#PicoLisp
PicoLisp
(de cal (Year) (prinl "====== " Year " ======") (for Dat (range (date Year 1 1) (date Year 12 31)) (let D (date Dat) (tab (3 3 4 8) (when (= 1 (caddr D)) (get *Mon (cadr D)) ) (caddr D) (day Dat *Day) (when (=0 (% (inc Dat) 7)) ...
Give a code snippet in #PicoLisp Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display wi...
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 ...
#Ada
Ada
  with ada.text_io;use ada.text_io;   procedure ethiopian is function double (n : Natural) return Natural is (2*n); function halve (n : Natural) return Natural is (n/2); function is_even (n : Natural) return Boolean is (n mod 2 = 0);   function mul (l, r : Natural) return Natural is (if l = 0 then 0 elsif...
Give a code snippet in #Ada 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/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Ring
Ring
  load "guilib.ring"   app = new qApp { win = new qWidget() { setWindowTitle("Don't accept Spaces") move(100,100) resize(400,400) new qLineedit(win) { myfilter = new qAllEvents(win) { setkeypressevent("keypress()") ...
Give a code snippet in #Ring Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 Provide a function to find the closest two p...
#Seed7
Seed7
const type: point is new struct var float: x is 0.0; var float: y is 0.0; end struct;   const func float: distance (in point: p1, in point: p2) is return sqrt((p1.x-p2.x)**2+(p1.y-p2.y)**2);   const func array point: closest_pair (in array point: points) is func result var array point: result is 0 tim...
Give a code snippet in #Seed7 This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 Provide a fun...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
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 |...
#OCaml
OCaml
let bitwise a b = Printf.printf "a and b: %d\n" (a land b); Printf.printf "a or b: %d\n" (a lor b); Printf.printf "a xor b: %d\n" (a lxor b); Printf.printf "not a: %d\n" (lnot a); Printf.printf "a lsl b: %d\n" (a lsl b); (* left shift *) Printf.printf "a asr b: %d\n" (a asr b); (* arithmetic right shift *...
Give a code snippet in #OCaml 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#VBScript
VBScript
  arrp = Array("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",_ "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",_ "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD",_ "BADC", "BDAC", "CBDA", "DBCA", "DCAB")   Dim col(4)   'supposes that a complete column have 6 of each letter. target = (6*Asc("A")) + (6*As...
Give a code snippet in #VBScript ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Retro
Retro
: multiply ( nn-n ) * ;
Give a code snippet in #Retro A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "complex.s7i";   const proc: main is func local var complex: a is complex(1.0, 1.0); var complex: b is complex(3.14159, 1.2); begin writeln("a=" <& a digits 5); writeln("b=" <& b digits 5); # addition writeln("a+b=" <& a + b digits 5...
Give a code snippet in #Seed7 A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displayst...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in...
#Maple
Maple
MaxLeftTruncatablePrime := proc(b, $) local i, j, c, p, sdprimes; local tprimes := table(); sdprimes := select(isprime, [seq(1..b-1)]); for p in sdprimes do if assigned(tprimes[p]) then next; end if; i := ilog[b](p)+1; j := 1; do c := j*b^i + p; ...
Give a code snippet in #Maple A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Lua
Lua
Vector = {} function Vector.new( _x, _y, _z ) return { x=_x, y=_y, z=_z } end   function Vector.dot( A, B ) return A.x*B.x + A.y*B.y + A.z*B.z end   function Vector.cross( A, B ) return { x = A.y*B.z - A.z*B.y, y = A.z*B.x - A.x*B.z, z = A.x*B.y - A.y*B.x } end   function Vector.s...
Give a code snippet in #Lua A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numb...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#JavaScript
JavaScript
var str = prompt("Enter a string"); var value = 0; while (value != 75000) { value = parseInt( prompt("Enter the number 75000") ); }
Give a code snippet in #JavaScript In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Java
Java
import java.io.*; import java.net.*; import java.util.*;   public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>();   public ChatServer(int port) { this.port = port; }   public void run() { try { ServerSocket ss = new ServerS...
Give a code snippet in #Java Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#ActionScript
ActionScript
package { import flash.display.Sprite;   public class SumAndProduct extends Sprite { public function SumAndProduct() { var arr:Array = [1, 2, 3, 4, 5]; var sum:int = 0; var prod:int = 1;   for (var i:int = 0; i < arr.length; i++) { sum += arr[i]; prod *= arr[i]; }   trace("Sum: " + s...
Give a code snippet in #ActionScript Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#F.23
F#
  // Palindromic Gapful Numbers . Nigel Galloway: December 3rd., 2020 let rec fN g l=seq{match l with 3->yield! seq{for n in 0L..9L->g*100L+g+n*10L} |4->yield! seq{for n in 0L..9L->g*1000L+g+n*110L} |_->yield! seq{for n in 0L..9L do for i in fN n (l-2)->i*10...
Give a code snippet in #F.23 Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful num...
christopher/rosetta-code
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Objeck
Objeck
  class Cholesky { function : Main(args : String[]) ~ Nil { n := 3; m1 := [25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0]; c1 := Cholesky(m1, n); ShowMatrix(c1, n);   IO.Console->PrintLine();   n := 4; m2 := [18.0, 22.0, 54.0, 42.0, 22.0, 70.0, 86.0, 62.0, 54.0, 86.0, 174.0, 1...
Give a code snippet in #Objeck Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be inter...
christopher/rosetta-code
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree is a self-balancing binary search tree....
#Objective-C
Objective-C
  @implementation AVLTree   -(BOOL)insertWithKey:(NSInteger)key {   if (self.root == nil) { self.root = [[AVLTreeNode alloc]initWithKey:key andParent:nil]; } else {   AVLTreeNode *n = self.root; AVLTreeNode *parent;   while (true) {   if (n.key == key) { ...
Give a code snippet in #Objective-C This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree is...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#PL.2FM
PL/M
100H: BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT$CH: PROCEDURE(C); DECLARE C BYTE; CALL BDOS(2,C); END PRINT$CH; PRINT$STR: PROCEDURE(S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT$STR;   /* PRINT NUMBER */ PRINT$NUM: PROCEDURE(N); DECLARE ...
Give a code snippet in #PL.2FM The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. T...
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#REXX
REXX
call routineName /*no arguments passed to routine.*/ call routineName 50 /*one argument (fifty) passed. */ call routineName 50,60 /*two arguments passed. */ call routineName 50, 60 /*(same as above) */ call routineName 5...
Give a code snippet in #REXX Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. ...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Lambda_Prolog
Lambda Prolog
sig bottles.   type println string -> o. type round int -> o. type bottles_song int -> o.  
Give a code snippet in #Lambda_Prolog Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the w...
christopher/rosetta-code
http://rosettacode.org/wiki/Numeric_error_propagation
Numeric error propagation
If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   σf = σa If   f = a ± b   then...
#Fortran
Fortran
PROGRAM CALCULATE !A distance, with error propagation. REAL X1, Y1, X2, Y2 !The co-ordinates. REAL X1E,Y1E,X2E,Y2E !Their standard deviation. DATA X1, Y1 ,X2, Y2 /100., 50., 200.,100./ !Specified DATA X1E,Y1E,X2E,Y2E/ 1.1, 1.2, 2.2, 2.3/ !Values. REAL DX,DY,D2,D,DXE,DYE,E !Assistan...
Give a code snippet in #Fortran If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then...
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...
#F.23
F#
  // The Name Game. Nigel Galloway: March 28th., 2018 let fN g = let fG α β γ = printfn "%s, %s, bo-%s\nBanana-fana fo-%s\nFee-fi-mo-%s\n%s!" g g α β γ g match g.ToLower().[0] with |'a'|'e'|'i'|'o'|'u' as n -> fG ("b"+(string n)+g.[1..]) ("f"+(string n)+g.[1..]) ("m"+(string n)+g.[1..]) |'b' ...
Give a code snippet in #F.23 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   ...
#Forth
Forth
  43 constant border \ grid size is border x border border border * constant size   variable crawler \ position of the crawler    : set.crawler border ...
Give a code snippet in #Forth An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion
Angles (geometric), normalization and conversion
This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 360 degrees, also shown as 360º ...
#Perl
Perl
use strict; use warnings; use feature 'say'; use POSIX 'fmod';   my $tau = 2 * 4*atan2(1, 1); my @units = ( { code => 'd', name => 'degrees' , number => 360 }, { code => 'g', name => 'gradians', number => 400 }, { code => 'm', name => 'mills' , number => 6400 }, { code => 'r', name => 'radians' , nu...
Give a code snippet in #Perl This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 36...
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclotomic_polynomial
Cyclotomic polynomial
The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and print the order of the first 10...
#Java
Java
  import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap;   public class CyclotomicPolynomial {   @SuppressWarnings("unused") private static int divisions = 0; private static int a...
Give a code snippet in #Java The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and p...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#HicEst
HicEst
DIMENSION upperbound(20), rescaleTo(20), temp(20) upperbound = (.06,.11,.16,.21,.26,.31,.36,.41,.46,.51,.56,.61,.66,.71,.76,.81,.86,.91,.96,1.01) rescaleTo = (.10,.18,.26,.32,.38,.44,.50,.54,.58,.62,.66,.70,.74,.78,.82,.86,.90,.94,.98,1.00)   DO test = 1, 10 value = RAN(0.5, 0.5) temp = value > upperbound PriceF...
Give a code snippet in #HicEst A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and...
christopher/rosetta-code
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#PHP
PHP
    <?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo "";   $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $pla...
Give a code snippet in #PHP Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner i...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Phixmonti
Phixmonti
def *2 2 * enddef def ++ 1 + enddef def composite swap exec swap exec enddef   getid ++ getid *2 3 composite print /# result: 7 #/
Give a code snippet in #Phixmonti Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Nim
Nim
from algorithm import sorted from os import walkPattern from sequtils import toSeq   for path in toSeq(walkPattern("*")).sorted: echo path
Give a code snippet in #Nim Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example ...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is c...
#BBC_BASIC
BBC BASIC
SYS "MessageBox", @hwnd%, "This is a test message", 0, 0  
Give a code snippet in #BBC_BASIC Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign lan...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#jq
jq
{"item": $item, "next": $next}
Give a code snippet in #jq singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element defini...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
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 |...
#PostScript
PostScript
/arithInteger { /x exch def /y exch def x y add = x y sub = x y mul = x y idiv = x y mod = x y exp = } def
Give a code snippet in #PostScript 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 Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#Pascal
Pascal
program Emirp; //palindrome prime 13 <-> 31 {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON} {$OPTIMIZATION REGVAR} {$OPTIMIZATION PEEPHOLE} {$OPTIMIZATION CSE} {$OPTIMIZATION ASMCSE} {$Smartlink ON} {$CODEALIGN proc=32} {$ELSE} {$APPLICATION CONSOLE} {$ENDIF} uses primtrial,sysutils; //IntToStr const...
Give a code snippet in #Pascal An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Excel
Excel
CNZODIAC =LAMBDA(y, APPENDCOLS( APPENDCOLS( APPENDCOLS( CNYEARNAME(y) )( CNYEARELEMENT(y) ) )( CNYEARANIMAL(y) ) )( CNYEARYINYANG(y) ) )     CNYEARANIMAL =LAMBDA(y, LET( shengxiao, { ...
Give a code snippet in #Excel Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities result...
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...
#Prolog
Prolog
primes(N, L) :- numlist(2, N, Xs), sieve(Xs, L).   sieve([H|T], [H|X]) :- H2 is H + H, filter(H, H2, T, R), sieve(R, X). sieve([], []).   filter(_, _, [], []). filter(H, H2, [H1|T], R) :- ( H1 < H2 -> R = [H1|R1], filter(H, H2, T, R1) ; H3 is H2 + H, ...
Give a code snippet in #Prolog 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   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Elixir
Elixir
defmodule Caesar_cipher do defp set_map(map, range, key) do org = Enum.map(range, &List.to_string [&1]) {a, b} = Enum.split(org, key) Enum.zip(org, b ++ a) |> Enum.into(map) end   def encode(text, key) do map = Map.new |> set_map(?a..?z, key) |> set_map(?A..?Z, key) String.graphemes(text) |> E...
Give a code snippet in #Elixir Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z t...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
commandstring = First[$CommandLine] <> " -noprompt -run \"Put[Factorial[20],ToFileName[$TemporaryDirectory,ToString[temp1]]];Quit[]\"" ->"MathKernel -noprompt -run \"Put[Factorial[20],ToFileName[$TemporaryDirectory,ToString[temp1]]];Quit[]\""   Run[commandstring] ->0
Give a code snippet in #Mathematica.2FWolfram_Language Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Print "SPAM" loop } Checkit  
Give a code snippet in #M2000_Interpreter Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/For...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#FurryScript
FurryScript
IsChar('a'); # true IsString("abc"); # true IsString('a'); # false IsChar("a"); # false
Give a code snippet in #FurryScript Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special charact...
christopher/rosetta-code
http://rosettacode.org/wiki/Legendre_prime_counting_function
Legendre prime counting function
The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number. then π(n) ...
#Raku
Raku
use Math::Primesieve;   my $sieve = Math::Primesieve.new;   say "10^$_\t" ~ $sieve.count: exp($_,10) for ^10;   say (now - INIT now) ~ ' elapsed seconds';
Give a code snippet in #Raku The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ...
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...
#REXX
REXX
/* HTTP hello server */ response.1 = 'HTTP/1.1 200 OK' || '0D0A'X, || 'Connection: close' || '0D0A'X, || 'Content-Type: text/html' || '0D0A0D0A'X response.2 = '<!DOCTYPE html>' || '0A'X, || '<html><head><title>Hello, Rosetta</title></head>' || '0A'X, || '<body><h2>Goodbye, World!...
Give a code snippet in #REXX 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 ...
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   ...
#Phix
Phix
with javascript_semantics -- widths and limits for 32/64 bit running (see output below): constant {dsize,w3,w2,limit} = iff(machine_bits()=32?{12,23,37,6} :{18,37,59,7}), -- [atoms on 32-bit have only 53 bits of precision, but 7th ^^^^ requires 59] dfmt = spr...
Give a code snippet in #Phix 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coeffici...
#REXX
REXX
/*REXX program to compute and display (unsigned) Stirling numbers of the first kind.*/ parse arg lim . /*obtain optional argument from the CL.*/ if lim=='' | lim=="," then lim= 12 /*Not specified? Then use the default.*/ olim= lim ...
Give a code snippet in #REXX Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#11l
11l
DefaultDict[String, Int] cnt L(word) re:‘\w+’.find_strings(File(‘135-0.txt’).read().lowercase()) cnt[word]++ print(sorted(cnt.items(), key' wordc -> wordc[1], reverse' 1B)[0.<10])
Give a code snippet in #11l Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what...
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...
#8080_Assembly
8080 Assembly
page: equ 2 ; Store doors in page 2 doors: equ 100 ; 100 doors puts: equ 9 ; CP/M string output org 100h xra a ; Set all doors to zero lxi h,256*page mvi c,doors zero: mov m,a inx h dcr c jnz zero mvi m,'$' ; CP/M string terminator (for easier output later) mov d,a ; D=0 so that DE=E=pass counter mov e,a ; E=...
Give a code snippet in #8080_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#QUACKASM
QUACKASM
1 QUIT
Give a code snippet in #QUACKASM Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local...
#Scheme
Scheme
; Needed in Guile for read-line (use-modules (ice-9 rdelim))   ; Variable used to hold child PID returned from forking (define child #f)   ; Start listening on port 12321 for connections from any address (let ((s (socket PF_INET SOCK_STREAM 0))) (setsockopt s SOL_SOCKET SO_REUSEADDR 1) (bind s AF_INET INADDR_ANY 12...
Give a code snippet in #Scheme Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary t...
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
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 algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C.23
C#
using System;   class Program { public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T> { // sort the array T[] originalArray = (T[]) array.Clone(); Array.Sort(array);   // compare to see if it was originally sorted for (var i = 0; i < originalArray.Length; i++) { ...
Give a code snippet in #C.23 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 algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#C.2B.2B
C++
class MyClass { public: void someMethod(); // member function = method MyClass(); // constructor private: int variable; // member variable = instance variable };   // implementation of constructor MyClass::MyClass(): variable(0) { // here could be more code }   // implementation of member function void MyClas...
Give a code snippet in #C.2B.2B In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the c...
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#J
J
isSemordnilap=: |.&.> (~: *. e.) ] unixdict=: <;._2 freads 'unixdict.txt' #semordnilaps=: ~. /:~"1 (,. |.&.>) (#~ isSemordnilap) unixdict 158
Give a code snippet in #J A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total nu...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Lisp
Lisp
to bottles :n if :n = 0 [output [No more bottles]] if :n = 1 [output [1 bottle]] output sentence :n "bottles end to verse :n print sentence bottles :n [of beer on the wall] print sentence bottles :n [of beer] print [Take one down, pass it around] print sentence bottles :n-1 [of beer on the wall] end for [...
Give a code snippet in #Lisp Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#D
D
import std.stdio; import std.string;   immutable L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"; immutable R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";   enum Mode { ENCRYPT, DECRYPT, }   string exec(string text, Mode mode, bool showSteps = false) { char[] left = L_ALPHABET.dup; char[] right = R_ALPHABET.dup; ...
Give a code snippet in #D Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Icon_and_Unicon
Icon and Unicon
procedure main() factors := primedecomp(2^43-1) # a big int end   procedure primedecomp(n) #: return a list of factors local F,o,x F := []   every writes(o,n|(x := genfactors(n))) do { \o := "*" /o := "=" put(F,x) # build a list of factors to satisfy the task } write() return F end   link factor...
Give a code snippet in #Icon_and_Unicon The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which con...
christopher/rosetta-code
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#Pascal
Pascal
program p196; {$IFDEF FPC} {$R-} {$MODE DELPHI} {$Optimization ON} {$Else} {$APPTYPE console} {$Endif} { nativeUint = LongWord;//Uint64 nativeInt = LongInt;//Int64 }   uses SysUtils,classes;   const cMAXNUM = 100*1000*1000;//100*1000*1000; cMaxCycle = 1500; cChkDigit = 10;//first check lychrel...
Give a code snippet in #Pascal   Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
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 |...
#JavaScript
JavaScript
/* == equal value === equal value and equal type != not equal value !== not equal value or not equal type < lexically ordered before > lexically ordered after */   console.log( "abcd" == "abcd", // true "abcd" === "abcd", // true 123 == "123", // true 123 === "123", // false "ABCD" == "abcd", // false "ABCD" != "abcd",...
Give a code snippet in #JavaScript 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 Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Raku
Raku
my @givens = <ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB>;   my @perms = <A B C D>.permutations.map: *.join;   .say when none(@givens) for @perms;
Give a code snippet in #Raku ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Go
Go
package main   import ( "log" "github.com/jtblin/go-ldap-client" )   func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client....
Give a code snippet in #Go Make sure you Connect to Active Directory
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Verilog
Verilog
  module main; integer number;   initial begin   for(number = 1; number < 100; number = number + 1) begin if (number % 15 == 0) $display("FizzBuzz"); else begin if(number % 3 == 0) $display("Fizz"); else begin if(number % 5 == 0) $display("Buzz"); else $display(number); ...
Give a code snippet in #Verilog Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBu...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#FreeBASIC
FreeBASIC
  Dim As Integer memoria(255), contador = 0 Dim As String codigo, caracter   Input "SUBLEQ> ", codigo   While Instr(codigo, " ") memoria(contador) = Val(Left(codigo, Instr(codigo, " ") - 1)) codigo = Mid(codigo, Instr(codigo, " ") + 1) contador += 1 Wend   memoria(contador) = Val(codigo) contador = 0 Do ...
Give a code snippet in #FreeBASIC Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array o...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Batch_File
Batch File
@echo off for /L %%i in (1,1,100) do call :tester %%i goto :eof   :tester set /a test = %1 %% 15 if %test% NEQ 0 goto :NotFizzBuzz echo FizzBuzz goto :eof   :NotFizzBuzz set /a test = %1 %% 5 if %test% NEQ 0 goto :NotBuzz echo Buzz goto :eof   :NotBuzz set /a test = %1 %% 3 if %test% NEQ 0 goto :Not...
Give a code snippet in #Batch_File Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   Fiz...
christopher/rosetta-code
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#Ursala
Ursala
#import flo   in =   @lrzyCipPX ~|afatPRZaq ~&EZ+fleq~~lrPrbr2G&& ~&B+fleq~~lrPrbl2G!| -& ~&Y+ ~~lrPrbl2G fleq, ^E(fleq@lrrPX,@rl fleq\0.)^/~&lr ^(~&r,times)^/minus@llPrll2X vid+ minus~~rbbI&-
Give a code snippet in #Ursala This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, che...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Java
Java
public class Assertions {   public static void main(String[] args) { int a = 13;   // ... some real code here ...   assert a == 42; // Throws an AssertionError when a is not 42.   assert a == 42 : "Error message"; // Throws an AssertionError when a is not 42, ...
Give a code snippet in #Java Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code