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/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d ...
#D
D
import std.stdio, std.math;   struct PerlinNoise { private static double fade(in double t) pure nothrow @safe @nogc { return t ^^ 3 * (t * (t * 6 - 15) + 10); }   private static double lerp(in double t, in double a, in double b) pure nothrow @safe @nogc { return a + t * (b - a); }   ...
Give a code snippet in #D The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   m...
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...
#Groovy
Groovy
def decompose = { a -> assert a.size > 0 && a[0].size == a.size def m = a.size def l = [].withEagerDefault { [].withEagerDefault { 0 } } (0..<m).each { i -> (0..i).each { k -> Number s = (0..<k).sum { j -> l[i][j] * l[k][j] } ?: 0 l[i][k] = (i == k) ...
Give a code snippet in #Groovy 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/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Cowgol
Cowgol
include "cowgol.coh";   typedef N is uint8; sub tau(n: N): (total: N) is total := 1; while n & 1 == 0 loop total := total + 1; n := n >> 1; end loop; var p: N := 3; while p*p <= n loop var count: N := 1; while n%p == 0 loop count := count + 1; ...
Give a code snippet in #Cowgol Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Ring
Ring
# Project  : Draw a pixel   load "guilib.ring"   new qapp { win1 = new qwidget() { setwindowtitle("Drawing Pixels") setgeometry(100,100,320,240) label1 = new qlabel(win1) { setgeometry(10,10,300,200) ...
Give a code snippet in #Ring Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Rust
Rust
extern crate luhn_test_of_credit_card_numbers;   use luhn_test_of_credit_card_numbers::luhn_test;   fn validate_isin(isin: &str) -> bool { if !isin.chars().all(|x| x.is_alphanumeric()) || isin.len() != 12 { return false; } if !isin[..2].chars().all(|x| x.is_alphabetic()) || !isin[2..12].char...
Give a code snippet in #Rust The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of ...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#Visual_Basic
Visual Basic
Sub Main() Dim HttpReq As WinHttp.WinHttpRequest ' in the "references" dialog of the IDE, check ' "Microsoft WinHTTP Services, version 5.1" (winhttp.dll) Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2 #Const USE_PROXY = 1 Set HttpReq = New WinHttp.WinHttpRequest HttpReq.Open "GET", "http://rosettacode.org/robot...
Give a code snippet in #Visual_Basic Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#UNIX_Shell
UNIX Shell
printf "ha"%.0s {1..5}
Give a code snippet in #UNIX_Shell Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*"...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#PowerShell
PowerShell
  function Get-BalanceStatus ( $String ) { $Open = 0 ForEach ( $Character in [char[]]$String ) { switch ( $Character ) { "[" { $Open++ } "]" { $Open-- } default { $Open = -1 } } # If Open drops below zero (close bef...
Give a code snippet in #PowerShell Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which ...
christopher/rosetta-code
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid...
#BASIC256
BASIC256
N = 6 : M = 5 : H = 25 : P = 0.2   fastgraphics graphsize N*H,(M+1)*H font "Arial",H/2+1,75 dim f(N,M) # 1 open, 2 mine, 4 expected mine dim s(N,M) # count of mines in a neighborhood   trian1 = {1,1,H-1,1,H-1,H-1} : trian2 = {1,1,1,H-1,H-1,H-1} mine = {2,2, H/2,H/2-2, H-2,2, H/2+2,H/2, H-2,H-2, H/2,H/2+2, 2,H-2, H/2-2,...
Give a code snippet in #BASIC256 There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first co...
christopher/rosetta-code
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Java
Java
public class Tree<T>{ private T value; private Tree<T> left; private Tree<T> right;   public void replaceAll(T value){ this.value = value; if (left != null) left.replaceAll(value); if (right != null) right.replaceAll(value); } }
Give a code snippet in #Java Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some func...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#B4X
B4X
Sub InsertionSort (A() As Int) For i = 1 To A.Length - 1 Dim value As Int = A(i) Dim j As Int = i - 1 Do While j >= 0 And A(j) > value A(j + 1) = A(j) j = j - 1 Loop A(j + 1) = value Next End Sub   Sub Test Dim arr() As Int = Array As Int(34, 23, 54, 123, 543, 123) InsertionSort(arr) For Each i As ...
Give a code snippet in #B4X 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/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Go
Go
package main   import "github.com/fogleman/gg"   var points []gg.Point   const width = 64   func hilbert(x, y, lg, i1, i2 int) { if lg == 1 { px := float64(width-x) * 10 py := float64(width-y) * 10 points = append(points, gg.Point{px, py}) return } lg >>= 1 hilbert(x+i1*l...
Give a code snippet in #Go Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Emacs_Lisp
Emacs Lisp
(defun prime (a) (not (or (< a 2) (cl-loop for x from 2 to (sqrt a) when (zerop (% a x)) return t))))
Give a code snippet in #Emacs_Lisp Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other ...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#Frink
Frink
  frac[p, q] := { a = makeArray[[0]] if p > q { a.push[floor[p / q]] p = p mod q } while p > 1 { d = ceil[q / p] a.push[1/d] [p, q] = [-q mod p, d q] } if p == 1 a.push[1/q] a }   showApproximations[false]   egypt[p, q] := join[" + ", f...
Give a code snippet in #Frink An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (...
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...
#Fortran
Fortran
INTEGER :: i = 1024 DO WHILE (i > 0) WRITE(*,*) i i = i / 2 END DO
Give a code snippet in #Fortran 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/Downw...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. 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 b...
#6502_Assembly
6502 Assembly
define ArrayPointerLo $00  ;define some helpful labels. define ArrayPointerHi $01 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; setArray:  ;Easy6502 doesn't let us define arbitrary bytes so the best option is to fill the range at runtime. lda #$10 ldx #0 loop_setArray: sta $1200,x clc adc #$10 inx cpx #$08 bcc loop_setArr...
Give a code snippet in #6502_Assembly Task Demonstrate a   for-loop   where the step-value is greater than one. 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   L...
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Lua
Lua
  function showTable(tbl) if type(tbl)=='table' then local result = {} for _, val in pairs(tbl) do table.insert(result, showTable(val)) end return '{' .. table.concat(result, ', ') .. '}' else return (tostring(tbl)) end end   function sortTable(op) local tbl = op.table or {} local column = op.column o...
Give a code snippet in #Lua Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexic...
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Wren
Wren
var width = 81 var height = 5   var lines = [[]] * height for (i in 0...height) lines[i] = ["*"] * width   var cantor // recursive so need to declare variable first cantor = Fn.new { |start, len, index| var seg = (len/3).floor if (seg == 0) return for (i in index...height) { for (j in (start+seg)......
Give a code snippet in #Wren Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
christopher/rosetta-code
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are...
#Kotlin
Kotlin
// version 1.1.3   import java.util.Collections.shuffle   enum class Color { RED, GREEN, PURPLE } enum class Symbol { OVAL, SQUIGGLE, DIAMOND } enum class Number { ONE, TWO, THREE } enum class Shading { SOLID, OPEN, STRIPED } enum class Degree { BASIC, ADVANCED }   class Card( val color: Color, val symbo...
Give a code snippet in #Kotlin Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol,...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Prolog
Prolog
  proper_divisors(1, []) :- !. proper_divisors(N, [1|L]) :- FSQRTN is floor(sqrt(N)), proper_divisors(2, FSQRTN, N, L).   proper_divisors(M, FSQRTN, _, []) :- M > FSQRTN, !. proper_divisors(M, FSQRTN, N, L) :- N mod M =:= 0, !, MO is N//M, % must be integer L = [M,MO|L1], % both proper divisors M1 is M+1, prop...
Give a code snippet in #Prolog These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficien...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Elena
Elena
import system'collections;   public program() { var c := nil; // declaring variable. var a := 3; // declaring and initializing variables var b := "my string".Length; long l := 200l; // declaring strongly typed variable auto lst := new List<int>(); ...
Give a code snippet in #Elena Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Gambas
Gambas
Public Sub Main() Dim byCount As Byte Dim sToSave As String   For byCount = 0 To 50 sToSave &= Format(Str(byCount), "00") & " - Charlie was here!" & gb.NewLine Next   File.Save(User.Home &/ "TestFile", sToSave) Print File.Load(User.Home &/ "TestFile")   End
Give a code snippet in #Gambas In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
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) ...
#Axe
Axe
For(I,1,100) !If I^3??I^5 Disp "FIZZBUZZ",i Else!If I^3 Disp "FIZZ",i Else!If I^5 Disp "BUZZ",i Else Disp I▶Dec,i End .Pause to allow the user to actually read the output Pause 1000 End
Give a code snippet in #Axe 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  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
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. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Racket
Racket
  #lang racket   (printf "Enter XY dimensions: ") (define xy (cons (read) (read))) (define array (for/vector ([x (car xy)]) (for/vector ([y (cdr xy)]) 0)))   (printf "Enter a number for the top-left: ") (vector-set! (vector-ref array 0) 0 (read)) (printf "Enter a number for the bottom-right: ") (vector-set! (vector-ref...
Give a code snippet in #Racket 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. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those num...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#Visual_Basic_.NET
Visual Basic .NET
Dim xml = <Students> <Student Name="April"/> <Student Name="Bob"/> <Student Name="Chad"/> <Student Name="Dave"/> <Student Name="Emily"/> </Students>   Dim names = (From node In xml...<Student> Select node.@Name).ToArray   For Each name In ...
Give a code snippet in #Visual_Basic_.NET Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion :newgame set a1=1 set a2=2 set a3=3 set a4=4 set a5=5 set a6=6 set a7=7 set a8=8 set a9=9 set ll=X set /a zz=0 :display1 cls echo Player: %ll% echo %a7%_%a8%_%a9% echo %a4%_%a5%_%a6% echo %a1%_%a2%_%a3% set /p myt=Where would you like to go (choose a number from 1-9 and press e...
Give a code snippet in #Batch_File Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathW...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#PARI.2FGP
PARI/GP
derangements(n)=if(n,round(n!/exp(1)),1); derange(n)={ my(v=[[]],tmp); for(level=1,n, tmp=List(); for(i=1,#v, for(k=1,n, if(k==level, next); for(j=1,level-1,if(v[i][j]==k, next(2))); listput(tmp, concat(v[i],k)) ) ); v=Vec(tmp) ); v }; derange(4) for(n=0,9,print("!"n" = "#derange(n)" = "de...
Give a code snippet in #PARI.2FGP A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Delphi
Delphi
program Binomial;   {$APPTYPE CONSOLE}   function BinomialCoff(N, K: Cardinal): Cardinal; var L: Cardinal;   begin if N < K then Result:= 0 // Error else begin if K > N - K then K:= N - K; // Optimization Result:= 1; L:= 0; while L < K do begin Result:= Result * (N - L); ...
Give a code snippet in #Delphi This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n −...
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#PureBasic
PureBasic
OpenConsole() Procedure is89(x) Repeat s=0 While x : s+ x%10*x%10 : x/10 : Wend If s=89 : ProcedureReturn 1 : EndIf If s=1  : ProcedureReturn 0 : EndIf x=s ForEver EndProcedure   Procedure main() Dim sums(32*81+1) : sums(0)=1 : sums(1)=0   For n=1 To n+1 For i=n*81 To 1 Step -1 For...
Give a code snippet in #PureBasic If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate =...
christopher/rosetta-code
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics Imports System.Runtime.CompilerServices   Module Module1   <Extension()> Sub Init(Of T)(array As T(), value As T) If IsNothing(array) Then Return For i = 0 To array.Length - 1 array(i) = value Next End Sub   Function BellTriangle(n As Integer) ...
Give a code snippet in #Visual_Basic_.NET Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significa...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#BASIC
BASIC
10 LET A$="" 20 IF A$="" THEN PRINT "THE STRING IS EMPTY" 30 IF A$<>"" THEN PRINT "THE STRING IS NOT EMPTY" 40 END
Give a code snippet in #BASIC Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Oth...
christopher/rosetta-code
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Clojure
Clojure
(defn zero [f] identity) (defn succ [n] (fn [f] (fn [x] (f ((n f) x))))) (defn add [n,m] (fn [f] (fn [x] ((m f)((n f) x))))) (defn mult [n,m] (fn [f] (fn [x] ((m (n f)) x)))) (defn power [b,e] (e b))   (defn to-int [c] ((c inc) 0))   (defn from-int [n] (letfn [(countdown [i] (if (zero? i) zero (succ (countdown ...
Give a code snippet in #Clojure Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied ...
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 ...
#Go
Go
  package main   import ( "log" "sort" )   func main() { log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) //false log.Println(jortSort([]int{0, 1, 0, 0, 0, 0})) //false log.Println(jortSort([]int{1, 2, 4, 11, 22, 22})) //true log.Println(jortSort([]int{0, 0, 0, 1, 2, 2})) //true }   func...
Give a code snippet in #Go 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/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Erlang
Erlang
  -module(ternary). -compile(export_all).   test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:...
Give a code snippet in #Erlang Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#PARI.2FGP
PARI/GP
a=""; isEmpty(s)=s=="" \\ Alternately: isEmpty(s)=#s==0 isNonempty(s)=s!="" \\ Alternatively: isNonempty(s)=#s
Give a code snippet in #PARI.2FGP Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. ...
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) ...
#bc
bc
for (i = 1; i <= 100; i++) { w = 0 if (i % 3 == 0) { "Fizz"; w = 1; } if (i % 5 == 0) { "Buzz"; w = 1; } if (w == 0) i if (w == 1) " " } quit
Give a code snippet in #bc 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   ...
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 |...
#C.23
C#
using System;   class Program { static void Main(string[] args) { int a = Convert.ToInt32(args[0]); int b = Convert.ToInt32(args[1]);   Console.WriteLine("{0} + {1} = {2}", a, b, a + b); Console.WriteLine("{0} - {1} = {2}", a, b, a - b); Console.WriteLine("{0} * {1} = {2}...
Give a code snippet in #C.23 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#PowerShell
PowerShell
  $document = [xml]@' <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation...
Give a code snippet in #PowerShell Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp St...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#Nim
Nim
from math import sqrt from sugar import `=>`, `->`   type WriterUnit = (float, string) WriterBind = proc(a: WriterUnit): WriterUnit   proc bindWith(f: (x: float) -> float; log: string): WriterBind = result = (a: WriterUnit) => (f(a[0]), a[1] & log)   func doneWith(x: int): WriterUnit = (x.float, "")   var log...
Give a code snippet in #Nim The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. De...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#REXX
REXX
/*REXX program generates & displays N generations of one─dimensional cellular automata. */ parse arg $ gens . /*obtain optional arguments from the CL*/ if $=='' | $=="," then $=001110110101010 /*Not specified? Then use the default.*/ if gens=='' | gens=="," then gens=40 ...
Give a code snippet in #REXX Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Component_Pascal
Component Pascal
  MODULE OvctGreatestSubsequentialSum; IMPORT StdLog, Strings, Args;   PROCEDURE Gss(iseq: ARRAY OF INTEGER;OUT start, end, maxsum: INTEGER); VAR i,j,sum: INTEGER; BEGIN i := 0; maxsum := 0; start := 0; end := -1; WHILE i < LEN(iseq) - 1 DO sum := 0; j := i; WHILE j < LEN(iseq) -1 DO INC(sum ,iseq[j]); IF ...
Give a code snippet in #Component_Pascal Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all el...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#PowerShell
PowerShell
if ($Host.UI.RawUI.KeyAvailable) { $key = $Host.UI.RawUI.ReadKey() }
Give a code snippet in #PowerShell Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#K
K
  v:v,|v:1+!5 v 1 2 3 4 5 5 4 3 2 1   avg:{(+/x)%#x} sma:{avg'x@(,\!y),(1+!y)+\:!y}   sma[v;5] 1 1.5 2 2.5 3 3.8 4.2 4.2 3.8 3  
Give a code snippet in #K Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a me...
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: matrix is array array integer;   const func matrix: zigzag (in integer: size) is func result var matrix: s is matrix.value; local var integer: i is 1; var integer: j is 1; var integer: d is -1; var integer: max is 0; var integer: n is 0; begin s ...
Give a code snippet in #Seed7 Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to enc...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#Perl
Perl
use autodie;   sub writedat { my ($filename, $x, $y, $xprecision, $yprecision) = @_;   open my $fh, ">", $filename;   for my $i (0 .. $#$x) { printf $fh "%.*g\t%.*g\n", $xprecision||3, $x->[$i], $yprecision||5, $y->[$i]; }   close $fh; }   my @x = (1, 2, 3, 1e11); my @y = map sqrt, @x;   wri...
Give a code snippet in #Perl Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#Yabasic
Yabasic
dim grid(8, 8)   sub placeKings() local r1, r2, c1, c2   do r1 = int(ran(8)) c1 = int(ran(8)) r2 = int(ran(8)) c2 = int(ran(8)) if (r1 <> r2 and abs(r1 - r2) > 1 and abs(c1 - c2) > 1) then grid(r1, c1) = asc("K") grid(r2, c2) = asc("k") ...
Give a code snippet in #Yabasic Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent...
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 ...
#ALGOL_68
ALGOL 68
MODE SORTSTRUCT = CHAR;   PROC inplace gnome sort = (REF[]SORTSTRUCT list)REF[]SORTSTRUCT: BEGIN INT i:=LWB list + 1, j:=LWB list + 2; WHILE i <= UPB list DO IF list[i-1] <= list[i] THEN i := j; j+:=1 ELSE SORTSTRUCT swap = list[i-1]; list[i-1]:= list[i]; list[i]:= swap; i-:=1; IF i=...
Give a code snippet in #ALGOL_68 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#FreeBASIC
FreeBASIC
' version 16-01-2017 ' compile with: fbc -s console   #Define max 30   #Include Once "gmp.bi"   Dim Shared As Mpz_ptr num(max), den(max)   Function Egyptian_fraction(fraction As String, ByRef whole As Integer, range As Integer = 0) As Integer   If InStr(fraction,"/") = 0 Then Print "Not a fraction, program ...
Give a code snippet in #FreeBASIC An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Smalltalk
Smalltalk
foo multipleValuesInto:[:a :b | Transcript show:a; cr. Transcript show:b; cr. ]
Give a code snippet in #Smalltalk Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do ...
#Pascal
Pascal
program project1; //Find the smallest number n to base b, so that n*n includes all //digits of base b {$IFDEF FPC}{$MODE DELPHI}{$ENDIF} uses sysutils; const charSet : array[0..36] of char ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; type tNumtoBase = record ntb_dgt : array[0..31-4] of byte; ...
Give a code snippet in #Pascal Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the sea...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Action.21
Action!
DEFINE PTR="CARD"   BYTE FUNC AtasciiToInternal(CHAR c) BYTE c2   c2=c&$7F IF c2<32 THEN RETURN (c+64) ELSEIF c2<96 THEN RETURN (c-32) FI RETURN (c)   PROC CharOut(CARD x BYTE y CHAR c) BYTE i,j,v PTR addr   addr=$E000+AtasciiToInternal(c)*8; FOR j=0 TO 7 DO v=Peek(addr) i=8 WHIL...
Give a code snippet in #Action.21 Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#ERRE
ERRE
CMD$="REN "+OLDFILENAME$+" "+NEWFILENAME$ SHELL CMD$
Give a code snippet in #ERRE Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rig...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. 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: Def...
#Python
Python
class List: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev   def append(self, data): if self.next == None: self.next = List(data, None, self) return self.next else: return self.next.ap...
Give a code snippet in #Python Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element ...
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#PureBasic
PureBasic
Procedure forward_difference(List a()) If ListSize(a()) <= 1 ClearList(a()): ProcedureReturn EndIf Protected NewList b() CopyList(a(), b()) LastElement(a()): DeleteElement(a()) SelectElement(b(), 1) ForEach a() a() - b(): NextElement(b()) Next EndProcedure   Procedure nth_difference(List a(), L...
Give a code snippet in #PureBasic Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. Li...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Sidef
Sidef
func is_mersenne_prime(p) { return true if (p == 2) var s = 4 var M = (2**p - 1) { s = powmod(s, 2, M)-2 } * (p-2) s == 0 }   Inf.times {|n| if (n.is_prime && is_mersenne_prime(n)) { say "M#{n}" } }
Give a code snippet in #Sidef Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Chapel
Chapel
for i in 1..5 { for 1..i do write('*'); writeln(); }
Give a code snippet in #Chapel “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract struct...
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...
#Z80_Assembly
Z80 Assembly
db "Hello World"
Give a code snippet in #Z80_Assembly 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 charac...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#XProfan
XProfan
  // XProfan can use StringParts, so the results here // are the comma separated positions of the parts or 0 Proc Contains Parameters string content, part var string results = "0" var long posi = 1 posi = InStr(part,content,posi) if posi <> 0 results = str$(posi) repeat posi = InStr(...
Give a code snippet in #XProfan Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#jq
jq
# a and b are assumed to be non-zero integers def gcd(a; b): # subfunction expects [a,b] as input # i.e. a ~ .[0] and b ~ .[1] def rgcd: if .[1] == 0 then .[0] else [.[1], .[0] % .[1]] | rgcd end; [a,b] | rgcd;   # To take advantage of gojq's support for accurate integer division: def idivide...
Give a code snippet in #jq Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as ...
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...
#IS-BASIC
IS-BASIC
100 PROGRAM "Closestp.bas" 110 NUMERIC X(1 TO 10),Y(1 TO 10) 120 FOR I=1 TO 10 130 READ X(I),Y(I) 140 PRINT X(I),Y(I) 150 NEXT 160 LET MN=INF 170 FOR I=1 TO 9 180 FOR J=I+1 TO 10 190 LET DSQ=(X(I)-X(J))^2+(Y(I)-Y(J))^2 200 IF DSQ<MN THEN LET MN=DSQ:LET MINI=I:LET MINJ=J 210 NEXT 220 NEXT 230 PRINT "C...
Give a code snippet in #IS-BASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Julia
Julia
  function primitiven{T<:Integer}(m::T) 1 < m || return T[] m != 2 || return T[1]  !isprime(m) || return T[2:2:m-1] rp = trues(m-1) if isodd(m) rp[1:2:m-1] = false end for p in keys(factor(m)) rp[p:p:m-1] = false end T[1:m-1][rp] end   function pythagoreantripcount{T<:...
Give a code snippet in #Julia A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Nim
Nim
import macros, sequtils, strformat, strutils   const Subscripts: array['0'..'9', string] = ["₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"]   # Modular integer with modulus N. type ModInt[N: static int] = distinct int     #-----------------------------------------------------------------------------------------------...
Give a code snippet in #Nim Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#BASIC256
BASIC256
found = 0 curr = 3   while found < 20 sum = Totient(curr) toti = sum while toti <> 1 toti = Totient(toti) sum += toti end while if sum = curr then print sum found += 1 end if curr += 1 end while end   function GCD(n, d) if n = 0 then return d if d = 0 ...
Give a code snippet in #BASIC256 Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Clojure
Clojure
(ns test-p.core (:require [clojure.math.numeric-tower :as math]))   (defn prime? [a] " Uses trial division to determine if number is prime " (or (= a 2) (and (> a 2) (> (mod a 2) 0) (not (some #(= 0 (mod a %)) (range 3 (inc (int (Math/ceil (math/sqrt a)))) 2)))))) ...
Give a code snippet in #Clojure Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being ...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Lua
Lua
-- Return boolean indicating whether or not n is prime function isPrime (n) if n <= 1 then return false end if n <= 3 then return true end if n % 2 == 0 or n % 3 == 0 then return false end local i = 5 while i * i <= n do if n % i == 0 or n % (i + 2) == 0 then return false end i = i +...
Give a code snippet in #Lua A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preference...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
x=Null;
Give a code snippet in #Mathematica.2FWolfram_Language Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to ...
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...
#AWK
AWK
$ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}' 2 4 6 8
Give a code snippet in #AWK 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/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...
#Bracmat
Bracmat
( list = Afrikaans Ελληνικά עברית മലയാളം ئۇيغۇرچە )
Give a code snippet in #Bracmat 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/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Erlang
Erlang
  -module( zigzag ).   -export( [matrix/1, task/0] ).   matrix( N ) -> {{_X_Y, N}, Proplist} = lists:foldl( fun matrix_as_proplist/2, {{{0, 0}, N}, []}, lists:seq(0, (N * N) - 1) ), [columns( X, Proplist ) || X <- lists:seq(0, N - 1)].   task() -> matrix( 5 ).       columns( Column, Proplist ) -> lists:sort( [Value |...
Give a code snippet in #Erlang Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to en...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Raven
Raven
rebol []
Give a code snippet in #Raven Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. JUMPS-PROGRAM. * Nobody writes like this, of course; but... PROCEDURE DIVISION. * You can jump anywhere you like. START-PARAGRAPH. GO TO AN-ARBITRARY-PARAGRAPH. YET-ANOTHER-PARAGRAPH. ALTER START-PARAGRAPH TO PROCEED TO A-PARAGRAPH-SOMEWHERE. * That's right, folks: we don't ...
Give a code snippet in #COBOL Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom t...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#ALGOL_68
ALGOL 68
BEGIN MODE MWRITER = STRUCT( LONG REAL value , STRING log ); PRIO BIND = 9; OP BIND = ( MWRITER m, PROC( LONG REAL )MWRITER f )MWRITER: ( MWRITER n := f( value OF m ); log OF n := log OF m + log OF n; n );   OP LEN ...
Give a code snippet in #ALGOL_68 The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Groovy
Groovy
def nowMillis = new Date().time println 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis
Give a code snippet in #Groovy Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). T...
#Common_Lisp
Common Lisp
;; *bug* shall have a dynamic binding. (declaim (special *bug*))   (let ((shape "triangle") (*bug* "ant")) (flet ((speak () (format t "~% There is some ~A in my ~A!" *bug* shape))) (format t "~%Put ~A in your ~A..." *bug* shape) (speak)   (let ((shape "circle") (*bug* "cockroach")) (form...
Give a code snippet in #Common_Lisp Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Amazing_Hopper
Amazing Hopper
  #include <hbasic.h>   #define TERM1 1.61803398874989 #define TERM2 -0.61803398874989   #context get Fibonacci number with analitic mode GetArgs(n) get Inv of (M_SQRT5), Mul by( Pow (TERM 1, n), Minus( Pow(TERM 2, n) ) ); then Return\\   #proto fibonacci_recursive(__X__) #synon _fibonacci_recursive ge...
Give a code snippet in #Amazing_Hopper The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience 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 ...
#Pascal
Pascal
PatienceSortTask (Output);   CONST MaxSortSize = 1024; { A power of two. } MaxWinnersSize = (2 * MaxSortSize) - 1;   TYPE PilesArrayType = ARRAY [1 .. MaxSortSize] OF INTEGER; WinnersArrayType = ARRAY [1 .. MaxWinnersSize, 1 .. 2] OF INTEGER;   VAR ExampleNumbers : ARRAY ...
Give a code snippet in #Pascal 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 s...
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...
#ALGOL_60
ALGOL 60
begin integer i; for i:=10 step -1 until 0 do outinteger(i) end
Give a code snippet in #ALGOL_60 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/Inc...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#Scala
Scala
object JewelsStones extends App { def countJewels(s: String, j: String): Int = s.count(i => j.contains(i))   println(countJewels("aAAbbbb", "aA")) println(countJewels("ZZ", "z")) }
Give a code snippet in #Scala Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#SNOBOL4
SNOBOL4
* # Concatenate 2 arrays (vectors) define('cat(a1,a2)i,j') :(cat_end) cat cat = array(prototype(a1) + prototype(a2)) cat1 i = i + 1; cat<i> = a1<i> :s(cat1) cat2 j = j + 1; cat<i - 1 + j> = a2<j> :s(cat2)f(return) cat_end   * # Fill arrays str1 = '1 2 3 4 5'; arr1 = array(5) loop ...
Give a code snippet in #SNOBOL4 Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#MATLAB_.2F_Octave
MATLAB / Octave
datestr(now)
Give a code snippet in #MATLAB_.2F_Octave Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Relat...
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Julia
Julia
using Random, Formatting   function randomplay(n, numprisoners=100) pardoned, indrawer, found = 0, collect(1:numprisoners), false for i in 1:n shuffle!(indrawer) for prisoner in 1:numprisoners found = false for reveal in randperm(numprisoners)[1:div(numprisoners, 2)] ...
Give a code snippet in #Julia The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start o...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#REXX
REXX
leapyear: procedure; parse arg yr return yr//400==0 | (yr//100\==0 & yr//4==0)
Give a code snippet in #REXX Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#ALGOL_68
ALGOL 68
# calculate some details of "Fibonacci Words" #   # fibonacci word 1 = "1" # # fibonacci word 2 = "0" # # 3 = word 2 cat word 1 = "01" # # n = word n-1 cat word n-2 #   # note...
Give a code snippet in #ALGOL_68 The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Word...
christopher/rosetta-code
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.
#Phix
Phix
with javascript_semantics function identity(integer n) sequence res = repeat(repeat(0,n),n) for i=1 to n do res[i][i] = 1 end for return res end function function matrix_mul(sequence a, b) integer {ha,wa,hb,wb} = apply({a,a[1],b,b[1]},length) if wa!=hb then return 0 end if sequence...
Give a code snippet in #Phix 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/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Visual_Basic_.NET
Visual Basic .NET
Imports System Imports System.Text.RegularExpressions   Module Bulls_and_Cows Function CreateNumber() As String Dim random As New Random() Dim sequence As Char() = {"1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c}   For i As Integer = 0 To sequence.Length - 1 Dim j As Intege...
Give a code snippet in #Visual_Basic_.NET Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player ...
christopher/rosetta-code
http://rosettacode.org/wiki/Spinning_rod_animation/Text
Spinning rod animation/Text
Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be...
#SimpleCode
SimpleCode
dtxt | wait 0.25 ctxt reset dtxt / wait 0.25 ctxt reset dtxt - wait 0.25 ctxt reset dtxt \ wait 0.25
Give a code snippet in #SimpleCode Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Java
Java
public class Sudoku { private int mBoard[][]; private int mBoardSize; private int mBoxSize; private boolean mRowSubset[][]; private boolean mColSubset[][]; private boolean mBoxSubset[][];   public Sudoku(int board[][]) { mBoard = board; mBoardSize = mBoard.length; mBo...
Give a code snippet in #Java Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
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...
#C
C
  #include <stdio.h>   const char *donuts[] = {"iced", "jam", "plain", "something completely different"}; int pos[] = {0, 0, 0, 0};   void printDonuts(int k) { for (size_t i = 1; i < k + 1; i += 1) // offset: i:1..N, N=k+1 printf("%s\t", donuts[pos[i]]); // str:0..N-1 printf("\n"); }...
Give a code snippet in #C 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 thos...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Pike
Pike
array cumu(int n) { array(array(int)) cache = ({({1})});   for(int l = sizeof(cache); l < n + 1; l++) { array(int) r = ({0}); for(int x = 1; x < l + 1; x++) { r = Array.push(r, r[-1] + cache[l - x][min(x, l-x)]); } cache = Array.push(cache, r); } return cache[n]; }   array row(int n) { array r = cumu(n)...
Give a code snippet in #Pike This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has ...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Sidef
Sidef
func perfect_totient({.<=1}, sum=0) { sum } func perfect_totient( n, sum=0) { __FUNC__(var(t = n.euler_phi), sum + t) }   say (1..Inf -> lazy.grep {|n| perfect_totient(n) == n }.first(20))
Give a code snippet in #Sidef Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
christopher/rosetta-code
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.
#C.23
C#
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; ...
Give a code snippet in #C.23 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/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#min
min
(over over / '* dip) :muldiv
Give a code snippet in #min Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Groovy
Groovy
import java.util.regex.Pattern   class LargeEarthquake { static void main(String[] args) { def r = Pattern.compile("\\s+") println("Those earthquakes with a magnitude > 6.0 are:\n") def f = new File("data.txt") f.eachLine { it -> if (r.split(it)[2].toDouble() > 6.0) { ...
Give a code snippet in #Groovy Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#OCaml
OCaml
let () = let oc = open_out "/dev/lp0" in output_string oc "Hello world!\n"; close_out oc ;;
Give a code snippet in #OCaml Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Swift
Swift
print("Enter a string: ", terminator: "") if let str = readLine() { print(str) }
Give a code snippet in #Swift User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Lingo
Lingo
on rep (str, n) res = "" repeat with i = 1 to n put str after res end repeat return res end
Give a code snippet in #Lingo Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve
Sierpinski arrowhead curve
Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
#Processing
Processing
final PVector t = new PVector(20, 30, 60);   void setup() { size(450, 400); noLoop(); background(0, 0, 200); stroke(-1); sc(7, 400, -60, t); }   PVector sc(int o, float l, final int a, final PVector s) { if (o > 0) { sc(--o, l *= .5, -a, s).z += a; sc(o, l, a, s).z += a; sc(o, l, -a, s); } els...
Give a code snippet in #Processing Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclops_numbers
Cyclops numbers
A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10. There are many different ...
#Go
Go
package main   import ( "fmt" "rcu" "strconv" "strings" )   func findFirst(list []int) (int, int) { for i, n := range list { if n > 1e7 { return n, i } } return -1, -1 }   func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < ...
Give a code snippet in #Go A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10...
christopher/rosetta-code
http://rosettacode.org/wiki/Quoting_constructs
Quoting constructs
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati...
#Smalltalk
Smalltalk
$a $Å $日
Give a code snippet in #Smalltalk Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Lua
Lua
local line = "---------+----------------------------------+-------+-------+" local digits = {1,2,3,4,5,6,7,8,9}   function and_bits (a, b) -- print (a, b) return a & b -- Lua 5.3 end   function or_bits (a, b) return a | b -- Lua 5.3 end     function get_digits (n) local tDigits = {} for i = 1, #digits do tDigits[i]...
Give a code snippet in #Lua Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those n...
christopher/rosetta-code