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/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Frink
Frink
  a = input["Enter number: "] toString[eval[a] + 1]  
Give a code snippet in #Frink Task Increment a numerical string.
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...
#Lasso
Lasso
local(i = 1024) while(#i > 0) => {^ #i + '\r' #i /= 2 ^}
Give a code snippet in #Lasso 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/Downwar...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#Go
Go
package main   import "fmt"   func analyze(s string) { chars := []rune(s) le := len(chars) fmt.Printf("Analyzing %q which has a length of %d:\n", s, le) if le > 1 { for i := 0; i < le-1; i++ { for j := i + 1; j < le; j++ { if chars[j] == chars[i] { ...
Give a code snippet in #Go Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length ...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#Euphoria
Euphoria
constant base = 1000000000   function atom_to_long(atom a) sequence s s = {} while a>0 do s = append(s,remainder(a,base)) a = floor(a/base) end while return s end function   function long_mult(object a, object b) sequence c if atom(a) then a = atom_to_long(a) end ...
Give a code snippet in #Euphoria Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#VBA
VBA
Option Explicit   Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)   Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,......
Give a code snippet in #VBA Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore u...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#PHP
PHP
<?php echo hash('sha256', 'Rosetta code');  
Give a code snippet in #PHP SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e...
christopher/rosetta-code
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#Euphoria
Euphoria
sequence lines sequence count lines = {} count = {}   procedure read(integer fn) object line while 1 do line = gets(fn) if atom(line) then exit else lines = append(lines, line) task_yield() end if end while   lines = append(lines,0) ...
Give a code snippet in #Euphoria The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with diff...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Apex
Apex
  string count = '12345'; count = String.valueOf(integer.valueOf(count)+1); system.debug('Incremental Value : '+count);  
Give a code snippet in #Apex Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#MATLAB
MATLAB
function testMTF symTable = 'abcdefghijklmnopqrstuvwxyz'; inStr = {'broood' 'bananaaa' 'hiphophiphop'}; for k = 1:length(inStr) outArr = encodeMTF(inStr{k}, symTable); outStr = decodeMTF(outArr, symTable); fprintf('%s: [ %s]\n', inStr{k}, sprintf('%d ', outArr)) fprintf('%sco...
Give a code snippet in #MATLAB Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is usefu...
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.)
#Gema
Gema
! comment starts with "!" and continues to end of line
Give a code snippet in #Gema 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/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func integer: ROMAN parse (in string: roman) is func result var integer: arabic is 0; local var integer: index is 0; var integer: number is 0; var integer: lastval is 0; begin for index range length(roman) downto 1 do case roman[index] of when {'...
Give a code snippet in #Seed7 Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, st...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#MATLAB_.2F_Octave
MATLAB / Octave
function stem_and_leaf_plot(x,stem_unit,leaf_unit) if nargin < 2, stem_unit = 10; end; if nargin < 3, leaf_unit = 1; else x = leaf_unit*round(x/leaf_unit); end;   stem = floor(x/stem_unit); leaf = mod(x,stem_unit);   for k = min(stem):max(stem) printf('\n%d |',k) printf(' %d' ,sort(l...
Give a code snippet in #MATLAB_.2F_Octave Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#R
R
a <- 1:100 evennums <- a[ a%%2 == 0 ] print(evennums)
Give a code snippet in #R Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Argile
Argile
use std, array (: array.arg also defines pointer operators :) let var = 42 let ptr = &var (: value of ptr is address of var :) print var (: prints 42 :) (*ptr)++ (: increments value pointed by ptr :) print var (: prints 43 :)
Give a code snippet in #Argile 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/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#R
R
v = c("Here", "are", "some", "sample", "strings", "to", "be", "sorted") print(v[order(-nchar(v), tolower(v))])
Give a code snippet in #R 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...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#MiniScript
MiniScript
roll = function() results = [] for i in range(0,3) results.push ceil(rnd * 6) end for results.sort results.remove 0 return results.sum end function   while true attributes = [] gt15 = 0 // (how many attributes > 15) for i in range(0,5) attributes.push roll ...
Give a code snippet in #MiniScript RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four,...
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 ...
#D
D
import std.stdio, std.algorithm, std.random, std.array;   enum int boxW = 41, boxH = 37; // Galton box width and height. enum int pinsBaseW = 19; // Pins triangle base size. enum int nMaxBalls = 55; // Number of balls.   static assert(boxW >= 2 && boxH >= 2); static assert((boxW - 4) >= (pinsBaseW * 2 - 1))...
Give a code snippet in #D 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...
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...
#Phix
Phix
integer i = 1024 while i!=0 do ?i i = floor(i/2) -- (see note) end while
Give a code snippet in #Phix 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#Lua
Lua
  function scandir(directory) local i, t, popen = 0, {}, io.popen local pfile = popen('ls -a "'..directory..'"') for filename in pfile:lines() do if filename ~= '.' and filename ~= '..' then i = i + 1 t[i] = filename end end pfile:close() return t end   function isemptydir(directory) return #scandir(di...
Give a code snippet in #Lua Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empt...
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. ...
#Jinja
Jinja
print(Template("""{% set sum = 0 %} {% for i in range(6) %} {{ sum }}{% set sum = sum + i %} {%- endfor %}""").render())  
Give a code snippet in #Jinja “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 structu...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#LaTeX
LaTeX
\documentclass{minimal} \newcounter{tmpnum} \newcommand{\stringinc}[1]{% \setcounter{tmpnum}{#1}% \stepcounter{tmpnum}% \arabic{tmpnum}% } \begin{document} The number 12345 is followed by \stringinc{12345}. \end{document}
Give a code snippet in #LaTeX Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#AWK
AWK
  BEGIN { nrcolors = 8   for (height=0; height<20; height++) { for (width=0; width<nrcolors; width++) { # print (ANSI) basic color and amount of spaces printf("\033[%dm%*s", width + 40, 64 / nrcolors, " ") }   # reset color and print newline printf("\033[0m\n") } }  
Give a code snippet in #AWK Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#BaCon
BaCon
OPTION COLLAPSE TRUE OPTION DELIM ","   csv$ = LOAD$("data.csv")   DOTIMES AMOUNT(csv$, NL$) line$ = TOKEN$(csv$, _, NL$)   IF _ = 1 THEN total$ = APPEND$(line$, 0, "SUM") ELSE line$ = CHANGE$(line$, _, STR$(_*10) ) total$ = APPEND$(total$, 0, line$, NL$) total$ = APPEND$(tot...
Give a code snippet in #BaCon CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, chan...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#Factor
Factor
USE: io.sockets host-name
Give a code snippet in #Factor Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Fortran
Fortran
  Program eee implicit none integer, parameter :: QP = selected_real_kind(16) real(QP), parameter :: one = 1.0 real(QP) :: ee   write(*,*) ' exp(1.) ', exp(1._QP)   ee = 1. +(one +(one +(one +(one +(one+ (one +(one +(one +(one +(one +(one & +(one +(one +(one +(one +(one +(one +(one +(one +(one +...
Give a code snippet in #Fortran Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#JavaScript
JavaScript
(() => { "use strict";   // - APPROXIMATION OF E OBTAINED AFTER N ITERATIONS --   // eApprox : Int -> Float const eApprox = n => sum( scanl(mul)(1)( enumFromTo(1)(n) ) .map(x => 1 / x) );     // ---------------------- TEST ---------...
Give a code snippet in #JavaScript Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 ...
#REXX
REXX
/*REXX program sorts a list (four groups) of integers using the bead sort algorithm.*/ /* [↓] define two dozen grasshopper numbers. */ gHopper= 1 4 10 12 22 26 30 46 54 62 66 78 94 110 126 134 138 158 162 186 190 222 254 270 /* [↓] these a...
Give a code snippet in #REXX 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/Substring
Substring
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 |...
#Ring
Ring
cStr = "a":"h" # 'abcdefgh' n = 3 m = 3 # starting from n characters in and of m length See substr(cStr,n, m) + nl #=> cde # starting from n characters in, up to the end of the string See substr(cStr,n) + nl #=> cdefgh # whole string minus last character See substr(cstr,1,len(cStr)-1) + nl #=> ab...
Give a code snippet in #Ring 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/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#EchoLisp
EchoLisp
  (define (task (nfrom 2) (range 20)) (for ((i (in-range nfrom (+ nfrom range)))) (writeln i "=" (string-join (prime-factors i) " x "))))    
Give a code snippet in #EchoLisp Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it wo...
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 ...
#Haxe
Haxe
function multiply(x:Float, y:Float):Float{ return x * y; }
Give a code snippet in #Haxe 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 f...
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...
#Commodore_BASIC
Commodore BASIC
  10 rem 100 prisoners 20 rem set arrays 30 rem dr = drawers containing card values 40 rem ig = a list of numbers 1 through 100, shuffled to become the 41 rem guess sequence for each inmate - method 1 50 dim dr(100),ig(100) 55 rem initialize drawers with own card in each drawer 60 for i=1 to 100:dr(i)=i:next   1000 p...
Give a code snippet in #Commodore_BASIC 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. Prisone...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algor...
#Racket
Racket
  #lang racket (require (only-in srfi/43 vector-swap!))   (define (comb-sort xs) (define (ref i) (vector-ref xs i)) (define (swap i j) (vector-swap! xs i j)) (define (new gap) (max 1 (exact-floor (/ gap 1.25)))) (define size (vector-length xs)) (let loop ([gap size] [swaps 0]) (unless (and (= gap 1) (= ...
Give a code snippet in #Racket Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare ...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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) The Miller–Rabin primality test or Rabin–Miller prima...
#PHP
PHP
<?php function is_prime($n, $k) { if ($n == 2) return true; if ($n < 2 || $n % 2 == 0) return false;   $d = $n - 1; $s = 0;   while ($d % 2 == 0) { $d /= 2; $s++; }   for ($i = 0; $i < $k; $i++) { $a = rand(2, $n-1);   $x = bcpowmod($a, $d, $n)...
Give a code snippet in #PHP This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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) The Miller–Rabin primali...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Free_Pascal
Free Pascal
  Program BestShuffle;   Const arr : array[1..6] Of string = ('abracadabra','seesaw','elk','grrrrrr','up','a');   Function Shuffle(inp: String): STRING;   Var x,ReplacementDigit : longint; ch : char; Begin If length(inp) > 1 Then Begin Randomize; For x := 1 To length(inp) Do Begin ...
Give a code snippet in #Free_Pascal Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#C.23
C#
System.Net.Dns.GetHostName();
Give a code snippet in #C.23 Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#Nim
Nim
import sequtils, permutationsswap   type Matrix[M,N: static[int]] = array[M, array[N, float]]   proc det[M,N](a: Matrix[M,N]): float = let n = toSeq 0..a.high for sigma, sign in n.permutations: var x = sign.float for i in n: x *= a[i][sigma[i]] result += x   proc perm[M,N](a: Matrix[M,N]): float = let...
Give a code snippet in #Nim For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#ERRE
ERRE
  PROGRAM DAY_OF_THE_WEEK   PROCEDURE MODULO(X,Y->RES) IF Y=0 THEN RES=X ELSE RES=X-Y*INT(X/Y) END IF END PROCEDURE   PROCEDURE WD(M,D,Y->RES%) IF M=1 OR M=2 THEN M+=12 Y-=1 END IF MODULO(365*Y+INT(Y/4)-INT(Y/100)+INT(Y/400)+D+INT((153*M+8)/5),7->RES) RES%=RES+1.0 END PROCED...
Give a code snippet in #ERRE A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Peripheral_drift_illusion
Peripheral drift illusion
Task Generate and display a Peripheral Drift Illusion The image appears to be moving even though it is perfectly static. Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host. References Codepen demo.
#Wren
Wren
import "dome" for Window import "graphics" for Canvas, Color   // signifies the white edges on the blue squares var LT = 0 var TR = 1 var RB = 2 var BL = 3   var Edges = [ [LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB], [LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL], [TR, LT, LT, BL, BL, RB, RB, TR, TR,...
Give a code snippet in #Wren Task Generate and display a Peripheral Drift Illusion The image appears to be moving even though it is perfectly static. Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host. References Codepen demo.
christopher/rosetta-code
http://rosettacode.org/wiki/Harmonic_series
Harmonic series
This page uses content from Wikipedia. The original article was at Harmonic 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) In mathematics, the n-th harmonic number is the sum of the recipr...
#Prolog
Prolog
main:- print_harmonic_series(20), nl, nth_harmonic_number(100, T), Num is numerator(T), Denom is denominator(T), writef('100th harmonic number: %t/%t\n', [Num, Denom]), nl, print_first_harmonic_greater_than(10).   print_harmonic_series(N):- writef('First %t harmonic numbers:\n', [N])...
Give a code snippet in #Prolog This page uses content from Wikipedia. The original article was at Harmonic 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) In mathematics, the n-th harmonic...
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: ...
#Lua
Lua
function cpuMove() local totalChance = record.R + record.P + record.S if totalChance == 0 then -- First game, unweighted random local choice = math.random(1, 3) if choice == 1 then return "R" end if choice == 2 then return "P" end if choice == 3 then return "S" end end local choice = math.ran...
Give a code snippet in #Lua 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/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#11l
11l
V src = ‘hello’ V dst = copy(src)
Give a code snippet in #11l This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty str...
christopher/rosetta-code
http://rosettacode.org/wiki/War_card_game
War card game
War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCell Poker hand_analyser Go Fish...
#Nim
Nim
import strformat import playing_cards   const None = -1 Player1 = 0 Player2 = 1   type Player = range[None..Player2]   const PlayerNames: array[Player1..Player2, string] = ["Player 1", "Player 2"]   #---------------------------------------------------------------------------------------------------   proc `<`(a, ...
Give a code snippet in #Nim War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCell ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#Ioke
Ioke
Text isPangram? = method( letters = "abcdefghijklmnopqrstuvwxyz" chars text = self lower chars letters map(x, text include?(x)) reduce(&&) )
Give a code snippet in #Ioke Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Writ...
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.)
#XUL
XUL
<!-- Comment syntax is borrowed from XML and HTML. -->
Give a code snippet in #XUL 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/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#Yabasic
Yabasic
for i = 1 to 33 print "decimal: ", i, " hex: ", hex$(i), " bin: ", bin$(i) next  
Give a code snippet in #Yabasic Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard r...
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 ...
#BBC_BASIC
BBC BASIC
PRINT FNfibonacci_r(1), FNfibonacci_i(1) PRINT FNfibonacci_r(13), FNfibonacci_i(13) PRINT FNfibonacci_r(26), FNfibonacci_i(26) END   DEF FNfibonacci_r(N) IF N < 2 THEN = N = FNfibonacci_r(N-1) + FNfibonacci_r(N-2)   DEF FNfibonacci_i(N) LOCAL F, I, P, T IF N ...
Give a code snippet in #BBC_BASIC 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or ...
#Ada
Ada
with Ada.Text_IO, Ada.Directories;   procedure Directory_Tree is   procedure Print_Tree(Current: String; Indention: Natural := 0) is   function Spaces(N: Natural) return String is (if N= 0 then "" else " " & Spaces(N-1));   use Ada.Directories; Search: Search_Type; Found: Directory_Entry_T...
Give a code snippet in #Ada A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarc...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#PicoLisp
PicoLisp
(prinl "myDir is" (and (dir "myDir") " not") " empty")
Give a code snippet in #PicoLisp Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#D
D
import std.stdio, std.algorithm, std.conv, std.array;   void fractran(in string prog, int val, in uint limit) { const fracts = prog.split.map!(p => p.split("/").to!(int[])).array;   foreach (immutable n; 0 .. limit) { writeln(n, ": ", val); const found = fracts.find!(p => val % p[1] == 0); ...
Give a code snippet in #D FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial po...
christopher/rosetta-code
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#C.2B.2B
C++
#include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector>   bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) { const size_t n1 = str.length(); const size_t n2 = suffix.length(); if (n1 < n2) return false; return st...
Give a code snippet in #C.2B.2B File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of exte...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Racket
Racket
  #lang racket (require data/heap)   (define pq (make-heap (λ(x y) (<= (second x) (second y)))))   (define (insert! x pri) (heap-add! pq (list pri x)))   (define (remove-min!) (begin0 (first (heap-min pq)) (heap-remove-min! pq)))   (insert! 3 "Clear drains") (insert! 4 "Feed cat") (insert! 5 "Make tea") (...
Give a code snippet in #Racket A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in pri...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#Clojure
Clojure
  (ns i-before-e.core (:require [clojure.string :as s]) (:gen-class))   (def patterns {:cie #"cie" :ie #"(?<!c)ie" :cei #"cei" :ei #"(?<!c)ei"})   (defn update-counts "Given a map of counts of matching patterns and a word, increment any count if the word matches it's pattern." [counts [word freq]] (apply hash...
Give a code snippet in #Clojure The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individua...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#C.2B.2B
C++
int a[5]; // array of 5 ints (since int is POD, the members are not initialized) a[0] = 1; // indexes start at 0   int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; // arrays can be initialized on creation   #include <string> std::string strings[4]; // std::string is no POD, therefore all array members are defau...
Give a code snippet in #C.2B.2B This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Lua
Lua
  g = love.graphics wid, hei = g.getWidth(), g.getHeight()   function choose( i, j ) local r = math.random() if r < .01 then return 0, .16 * j elseif r < .07 then return .2 * i - .26 * j, .23 * i + .22 * j + 1.6 elseif r < .14 then return -.15 * i + .28 * j, .26 * i + .24 * j + .44 else return .85 * i...
Give a code snippet in #Lua A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of th...
#zkl
zkl
var [const] MsgHash=Import("zklMsgHash"); // SHA-256, etc const symbols="123456789" // 58 characters: no cap i,o; ell, zero "ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz";   fcn unbase58(str){ // --> Data (byte bucket) out:=Data().fill(0,25); str.pump(Void,symbols.index,'wrap(n){ // throw...
Give a code snippet in #zkl Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding,...
christopher/rosetta-code
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the...
#Vlang
Vlang
import os import rand import time import arrays   fn is_wordiff(guesses []string, word string, dict []string) bool { if word !in dict { println('That word is not in the dictionary') return false } if word in guesses { println('That word has already been used') return false ...
Give a code snippet in #Vlang Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. N...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#BASIC256
BASIC256
  function sumDigitos(n) if n < 0 then return 0 suma = 0 while n > 0 suma = suma + (n mod 10) n = n \ 10 end while return suma end function   function isHarshad(n) return n mod sumDigitos(n) = 0 end function   print "Los primeros 20 números de Harshad o Niven son:" cuenta = 0 i = 1   do if isHarshad(i) then ...
Give a code snippet in #BASIC256 The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The ta...
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.)
#Racket
Racket
  ; this is a to-end-of-line coment   #| balanced comment, #| can be nested |# |#   #;(this expression is ignored)   #; ; the following expression is commented because of the #; in the beginning (ignored)    
Give a code snippet in #Racket 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/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#BASIC256
BASIC256
  arraybase 1 dim list1(5): dim list2(6): dim list3(5): dim list4(5) list1 = {1, 2, 1, 5, 2} list2 = {1, 2, 1, 5, 2, 2} list3 = {1, 2, 3, 4, 5} list4 = {1, 2, 3, 4, 5}   if Orden(list1[], list2[]) then print "list1 < list2" else print "list 1>= list2" if Orden(list2[], list3[]) then print "list2 < list3" else print "li...
Give a code snippet in #BASIC256 sorting 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Java
Java
  package programas;   import java.math.BigInteger; import java.util.InputMismatchException; import java.util.Scanner;   public class IterativeFactorial {   public BigInteger factorial(BigInteger n) { if ( n == null ) { throw new IllegalArgumentException(); } else if ( n.signum() == - 1 ) { //...
Give a code snippet in #Java Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
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...
#AutoHotkey
AutoHotkey
SetBatchLines, -1 iterations := 5 step := 10 iterations *= step Loop,  % iterations { If Mod(A_Index, step) Continue MsgBox, % A_Index } ExitApp
Give a code snippet in #AutoHotkey 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   Loop...
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...
#Halon
Halon
forever { echo "SPAM"; }
Give a code snippet in #Halon 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   Loop...
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 ...
#Forth
Forth
: fib ( n -- fib ) 0 1 rot 0 ?do over + swap loop drop ;
Give a code snippet in #Forth 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Array_Length is Fruits : constant array (Positive range <>) of access constant String  := (new String'("orange"), new String'("apple"));   begin for Fruit of Fruits loop Ada.Text_IO.Put (Integer'Image (Fruit'Length)); end loop;   Ada.Text_...
Give a code snippet in #Ada Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequen...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Liberty_BASIC
Liberty BASIC
mini=0 maxi=100   print "Think of a number between ";mini;" and ";maxi print "Each time I guess a number you must state whether my" print "guess was too high, too low, or equal to your number." print   while response$<>"=" if not(mini<=maxi) then print "Error" exit while end if guess=int((maxi-mini)/2)+mini ...
Give a code snippet in #Liberty_BASIC Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the targ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Shen
Shen
(datatype point X : number; Y : number; ==================== [point X Y] : point;)
Give a code snippet in #Shen 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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Re...
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   numeric digits 20   class RAvgSimpleMoving public   properties private window = java.util.Queue period sum   properties constant exMsg = 'Period must be a positive integer'   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
Give a code snippet in #NetRexx 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#XLISP
XLISP
(defun mean (v) (if (= (vector-length v) 0) nil (let ((l (vector->list v))) (/ (apply + l) (length l)))))
Give a code snippet in #XLISP Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an esta...
christopher/rosetta-code
http://rosettacode.org/wiki/Minkowski_question-mark_function
Minkowski question-mark function
The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o...
#Wren
Wren
import "/fmt" for Fmt   var MAXITER = 151   var minkowski // predeclare as recursive minkowski = Fn.new { |x| if (x > 1 || x < 0) return x.floor + minkowski.call(x - x.floor) var p = x.floor var q = 1 var r = p + 1 var s = 1 var d = 1 var y = p while (true) { d = d / 2 if...
Give a code snippet in #Wren The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The d...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Simula
Simula
BEGIN   CLASS ENV; BEGIN   CLASS ITEM(N, X); TEXT N; REAL X; BEGIN REF(ITEM) NEXT; NEXT :- HEAD; HEAD :- THIS ITEM; END ITEM;   REF(ITEM) HEAD;   REF(ITEM) PROCEDURE LOOKUP(V); TEXT V; BEGIN REF(ITEM) I; BOOLEAN FOUND; I :- HEAD; ...
Give a code snippet in #Simula x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples an...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the widt...
#AutoHotkey
AutoHotkey
Msgbox % IntervalAdd(1,2) ; [2.999999,3.000001]   SetFormat, FloatFast, 0.20 Msgbox % IntervalAdd(1,2) ; [2.99999999999999910000,3.00000000000000090000]   ;In v1.0.48+, floating point variables have about 15 digits of precision internally ;unless SetFormat Float (i.e. the slow mode) is present anywhere in the script. ...
Give a code snippet in #AutoHotkey Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Addi...
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...
#Elena
Elena
import extensions;   class MyClass { prop int Variable;   someMethod() { Variable := 1 }   constructor() { } }   public program() { // instantiate the class var instance := new MyClass();   // invoke the method instance.someMethod();   // get the variable ...
Give a code snippet in #Elena 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 cla...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#D
D
void main() { import std.stdio, std.algorithm, std.range, std.meta, std.numeric, std.conv, std.typecons;   auto list = iota(1, 11); alias ops = AliasSeq!(q{a + b}, q{a * b}, min, max, gcd);   foreach (op; ops) writeln(op.stringof, ": ", list.reduce!op);   // std.algorithm.reduce s...
Give a code snippet in #D Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Exam...
#Julia
Julia
using .Hidato   const numbrixmoves = [[-1, 0], [0, -1], [0, 1], [1, 0]]   board, maxmoves, fixed, starts = hidatoconfigure(numbrix1) printboard(board, " 0 ", " ") hidatosolve(board, maxmoves, numbrixmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)   board, maxmoves, fixed, starts = hidatoconfigure(numbr...
Give a code snippet in #Julia Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end n...
christopher/rosetta-code
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics th...
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h>   #define SIM_N 5 /* Run 5 simulations */ #define PRINT_DISCARDED 1 /* Whether or not to print the discard pile */   #define min(x,y) ((x<y)?(x):(y))   typedef uint8_t card_t;   /* Return a random number from an uniform distribution (0..n-1) */ unsi...
Give a code snippet in #C Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the tr...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Perl
Perl
use Math::Matrix;   sub cramers_rule { my ($A, $terms) = @_; my @solutions; my $det = $A->determinant; foreach my $i (0 .. $#{$A}) { my $Ai = $A->clone; foreach my $j (0 .. $#{$terms}) { $Ai->[$j][$i] = $terms->[$j]; } push @solutions, $Ai->determinant / $det;...
Give a code snippet in #Perl linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_...
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...
#Logo
Logo
print "Hello\,\ world print "|Hello, world|
Give a code snippet in #Logo 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   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. BABBAGE-PROGRAM. * A line beginning with an asterisk is an explanatory note. * The machine will disregard any such line. DATA DIVISION. WORKING-STORAGE SECTION. * In this part of the program we reserve the storage space we shall * be using for our variables, using a 'PICTURE' clause...
Give a code snippet in #COBOL Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#Scala
Scala
import scala.math.abs   object Dinesman3 extends App { val tenants = List("Baker", "Cooper2", "Fletcher4", "Miller", "Smith") val (groundFloor, topFloor) = (1, tenants.size)   /** Rules with related tenants and restrictions*/ val exclusions = List((suggestedFloor0: Map[String, Int]) => suggestedFloor0("Bake...
Give a code snippet in #Scala Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are a...
christopher/rosetta-code
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions ...
#Ursala
Ursala
#import std #import nat   break = ~&r**+ zipt*+ ~&lh*~+ ~&lzyCPrX|\+ -*^|\~&tK33 :^/~& 0!*t   band = pad0+ ~&rSS+ zipt^*D(~&r,^lrrSPT/~&ltK33tx zipt^/~&r ~&lSNyCK33+ zipp0)^/~&rx ~&B->NlNSPC ~&bt   deconv = # takes a natural number n to the n-dimensional deconvolution function   ~&?\math..div! iota; ~&!*; @h|\; (~&al^?...
Give a code snippet in #Ursala This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}}...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Ada
Ada
with Ada.Numerics.Long_Elementary_Functions; with Ada.Text_IO; use Ada.Text_IO;   procedure Sequence_Of_Non_Squares_Test is use Ada.Numerics.Long_Elementary_Functions;   function Non_Square (N : Positive) return Positive is begin return N + Positive (Long_Float'Rounding (Sqrt (Long_Float (N)))); end ...
Give a code snippet in #Ada Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037 ...
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...
#Factor
Factor
USING: bit-arrays formatting fry kernel math math.ranges sequences ; IN: rosetta.doors   CONSTANT: number-of-doors 100   : multiples ( n -- range ) 0 number-of-doors rot <range> ;   : toggle-multiples ( n doors -- ) [ multiples ] dip '[ _ [ not ] change-nth ] each ;   : toggle-all-multiples ( doors -- ) [ n...
Give a code snippet in #Factor There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ....
christopher/rosetta-code
http://rosettacode.org/wiki/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 |...
#Dyalect
Dyalect
func compare(a, b) { if a == b { print("'\(a)' and '\(b)' are lexically equal.") } if a != b { print("'\(a)' and '\(b)' are not lexically equal.") }   if a < b { print("'\(a)' is lexically before '\(b)'.") } if a > b { print("'\(a)' is lexically after '\(b)'.") }   if a >= b { prin...
Give a code snippet in #Dyalect 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/Latin_Squares_in_reduced_form
Latin Squares in reduced form
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S...
#Phix
Phix
string aleph = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" function rfls(integer n, bool count_only=true) if n>length(aleph) then ?9/0 end if -- too big... if n=1 then return iff(count_only?1:{{1}}) end if sequence tn = tagset(n), -- {1..n} vcs = repeat(tn,n), -- valid...
Give a code snippet in #Phix A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element wit...
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 ...
#Oz
Oz
fun {Multiply X Y} X * Y end
Give a code snippet in #Oz 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 fro...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Plain_English
Plain English
To run: Start up. Demonstrate do-while. Wait for the escape key. Shut down.   To demonstrate do-while: Bump a counter. Convert the counter to a string. Write the string on the console. If the counter is evenly divisible by 6, exit. Repeat.
Give a code snippet in #Plain_English Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#ooRexx
ooRexx
/*REXX pgm generates primitive Heronian triangles by side length & area.*/ Call time 'R' Numeric Digits 12 Parse Arg mxs area list If mxs ='' Then mxs =200 If area='' Then area=210 If list='' Then list=10 tx='primitive Heronian triangles' Call heronian mxs /* invoke sub with max SIDES. */...
Give a code snippet in #ooRexx Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a +...
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...
#M2000_Interpreter
M2000 Interpreter
song$=format$("\r\n{0}, {0}, bo-{2}{1}\r\nBanana-fana fo-{3}{1}\r\nFee-fi-mo-{4}{1}\r\n{0}!\r\n")
Give a code snippet in #M2000_Interpreter 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' ...
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...
#Perl
Perl
use strict; use warnings; use bigint; sub isEgyption{ my $nr = int($_[0]); my $de = int($_[1]); if($nr == 0 or $de == 0){ #Invalid input return; } if($de % $nr == 0){ # They divide so print printf "1/" . int($de/$nr); return; } if($nr % $de == 0){ # Invalid fraction printf $nr/$de; r...
Give a code snippet in #Perl 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   (u...
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 ...
#R
R
halve <- function(a) floor(a/2) double <- function(a) a*2 iseven <- function(a) (a%%2)==0   ethiopicmult <- function(plier, plicand, tutor=FALSE) { if (tutor) { cat("ethiopic multiplication of", plier, "and", plicand, "\n") } result <- 0 while(plier >= 1) { if (!iseven(plier)) { result <- result + plicand } ...
Give a code snippet in #R 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Befunge
Befunge
0" &7&%h&'&%| &7&%7%&%&'&%&'&%&7&%"v v"'%$%'%$%3$%$%7% 0%&7&%&7&(%$%'%$"< >"%$%7%$%&%$%&'&%7%$%7%$%, '&+(%$%"v v"+&'&%+('%$%$%'%$%$%$%$%$%$%$%'%$"< >"(%$%$%'%$%$%( %$+(%&%$+(%&%$+(%&"v v"(; $%$%(+$%&%(+$%$%'%$%+&%$%$%$%"< ? ";(;(+(+$%+(%&(;(3%$%&$ 7`+( ":v > ^v!:-1<\,:g7+*63%4 \/_#4:_v#:-*84_$@ $_\:,\^ ...
Give a code snippet in #Befunge Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Racket
Racket
#lang racket   (define (guess-number min max) (define target (+ min (random (- max min -1)))) (printf "I'm thinking of a number between ~a and ~a\n" min max) (let loop ([prompt "Your guess"]) (printf "~a: " prompt) (flush-output) (define guess (read)) (define response (cond [(not (exact-inte...
Give a code snippet in #Racket Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: h...
christopher/rosetta-code
http://rosettacode.org/wiki/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 |...
#NSIS
NSIS
Function Bitwise Push $0 Push $1 Push $2 StrCpy $0 7 StrCpy $1 2   IntOp $2 $0 & $1 DetailPrint "Bitwise AND: $0 & $1 = $2" IntOp $2 $0 | $1 DetailPrint "Bitwise OR: $0 | $1 = $2" IntOp $2 $0 ^ $1 DetailPrint "Bitwise XOR: $0 ^ $1 = $2" IntOp $2 $0 ~ DetailPrint "Bitwise NOT (negate in NSIS docs): ~$0 = $2...
Give a code snippet in #NSIS 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/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Raven
Raven
'input.txt' delete '/input.txt' delete 'docs' rmdir '/docs' rmdir
Give a code snippet in #Raven Task Delete a file called "input.txt" and delete a 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/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#ERRE
ERRE
  PROGRAM ROOTS_FUNCTION   !VAR E,X,STP,VALUE,S%,I%,LIMIT%,X1,X2,D   FUNCTION F(X) F=X*X*X-3*X*X+2*X END FUNCTION   BEGIN X=-1 STP=1.0E-6 E=1.0E-9 S%=(F(X)>0)   PRINT("VERSION 1: SIMPLY STEPPING X") WHILE X<3.0 DO VALUE=F(X) IF ABS(VALUE)<E THEN PRINT("ROOT FOUND AT X =";X) S%=NO...
Give a code snippet in #ERRE Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Objeck
Objeck
bundle Default { class NQueens { b : static : Int[]; s : static : Int;   function : Main(args : String[]) ~ Nil { b := Int->New[8]; s := 0;   y := 0; b[0] := -1;   while (y >= 0) { do { b[y]+=1; } while((b[y] < 8) & Unsafe(y));   if...
Give a code snippet in #Objeck Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Vlang
Vlang
import strings const ( dig = ["00", "01", "10"] dig1 = ["", "1", "10"] )   struct Zeckendorf { mut: d_val int d_len int }   fn new_zeck(xx string) Zeckendorf { mut z := Zeckendorf{} mut x := xx if x == "" { x = "0" } mut q := 1 mut i := x.len - 1 z.d_len = i / 2 ...
Give a code snippet in #Vlang This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the...
#D
D
import std.array; import std.conv; import std.format; import std.range; import std.stdio;   immutable DIGITS = "0123456789";   string deBruijn(int k, int n) { auto alphabet = DIGITS[0..k]; byte[] a; a.length = k * n; byte[] seq;   void db(int t, int p) { if (t > n) { if (n % p ==...
Give a code snippet in #D The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) req...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#11l
11l
V s = ‘100’ L(base) 2..20 print(‘String '#.' in base #. is #. in base 10’.format(s, base, Int(s, radix' base)))
Give a code snippet in #11l It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of su...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order
Magic squares of singly even order
A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6,...
#Kotlin
Kotlin
// version 1.0.6   fun magicSquareOdd(n: Int): Array<IntArray> { if (n < 3 || n % 2 == 0) throw IllegalArgumentException("Base must be odd and > 2")   var value = 0 val gridSize = n * n var c = n / 2 var r = 0 val result = Array(n) { IntArray(n) } while (++value <= gridSize) { ...
Give a code snippet in #Kotlin A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is ...
christopher/rosetta-code