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/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Delphi
Delphi
  program Arithmetic_Complex;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.VarCmplx;   var a, b: Variant;   begin a := VarComplexCreate(5, 3); b := VarComplexCreate(0.5, 6.0);   writeln(format('(%s) + (%s) = %s',[a,b, a+b]));   writeln(format('(%s) * (%s) = %s',[a,b, a*b]));   writeln(format('-(%...
Give a code snippet in #Delphi A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displays...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#R
R
  Full_Data<-structure(list(item = c("map", "compass", "water", "sandwich", "glucose", "tin", "banana", "apple", "cheese", "beer", "suntan_cream", "camera", "T-shirt", "trousers", "umbrella", "waterproof_trousers", "waterproof_overclothes", "note-case", "sunglasses", "towel", "socks", "book"), weigth = c(9, 13, 153...
Give a code snippet in #R A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#BASIC
BASIC
DECLARE FUNCTION int2Text$ (number AS LONG)   'small DATA "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" DATA "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" 'tens DATA "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty"...
Give a code snippet in #BASIC Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than posi...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#PureBasic
PureBasic
Procedure.f Max (Array a.f(1)) Protected last, i, ret.f   ret = a(0) last = ArraySize(a()) For i = 1 To last If ret < a(i) ret = a(i) EndIf Next   ProcedureReturn ret EndProcedure
Give a code snippet in #PureBasic Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#AWK
AWK
  # syntax: GAWK -f FIND_THE_LAST_SUNDAY_OF_EACH_MONTH.AWK [year] BEGIN { split("31,28,31,30,31,30,31,31,30,31,30,31",daynum_array,",") # days per month in non leap year year = (ARGV[1] == "") ? strftime("%Y") : ARGV[1] if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { daynum_array[2] = 29 ...
Give a code snippet in #AWK Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Fantom
Fantom
class FizzBuzz { public static Void main () { for (Int i:=1; i <= 100; ++i) { if (i % 15 == 0) echo ("FizzBuzz") else if (i % 3 == 0) echo ("Fizz") else if (i % 5 == 0) echo ("Buzz") else echo (i) } } }
Give a code snippet in #Fantom Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
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.
#Oz
Oz
declare fun {NonSqr N} N + {Float.toInt {Floor 0.5 + {Sqrt {Int.toFloat N}}}} end   fun {SqrtInt N} {Float.toInt {Sqrt {Int.toFloat N}}} end   fun {IsSquare N} {Pow {SqrtInt N} 2} == N end   Ns = {Map {List.number 1 999999 1} NonSqr} in {Show {List.take Ns 22}} {Show {Some Ns IsSquare}}
Give a code snippet in #Oz 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/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: ...
#Forth
Forth
create units s" kilometer" 2, s" meter" 2, s" centimeter" 2, s" tochka" 2, s" liniya" 2, s" diuym" 2, s" vershok" 2, s" piad" 2, s" fut" 2, s" arshin" 2, s" sazhen" 2, s" versta" 2, s" milia" 2, create values 1000.0e f, 1.0e f, 0.01e f, 0.000254e f, 0.00254e f, 0.0254e f, 0.04445e f, 0.1778e f, 0.3048e f, 0.7112e f, 2....
Give a code snippet in #Forth Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and ...
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...
#Modula-3
Modula-3
VAR src: TEXT := "Foo"; VAR dst: TEXT := src;
Give a code snippet in #Modula-3 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 Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Emacs_Lisp
Emacs Lisp
(format-time-string "%Y-%m-%d") (format-time-string "%F") ;; new in Emacs 24 ;; => "2015-11-08"   (format-time-string "%A, %B %e, %Y") ;; => "Sunday, November 8, 2015"
Give a code snippet in #Emacs_Lisp This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Python
Python
>>> # Extreme values from expressions >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> # Print >>> for value in (inf, _inf, _zero, nan): print (value)   inf -inf -0.0 nan >>> # Extreme values from other means >>> float('nan'...
Give a code snippet in #Python The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#BASIC256
BASIC256
  # Caeser Cipher # basic256 1.1.4.0   dec$ = "" type$ = "cleartext "   input "If decrypting enter " + "<d> " + " -- else press enter > ",dec$ # it's a klooj I know... input "Enter offset > ", iOffset   if dec$ = "d" then iOffset = 26 - iOffset type$ = "ciphertext " end if   input "Enter " + type$ + "> ", str$...
Give a code snippet in #BASIC256 Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#MiniScript
MiniScript
// placeholder knights rank = ["♘"] * 8   // function to get a random free space from a to b, inclusive randFree = function(a, b) free = [] for i in range(a, b) if rank[i] == "♘" then free.push i end for return free[rnd * free.len] end function   // place the king kingIdx = randFree(1, 6) rank[k...
Give a code snippet in #MiniScript Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns m...
christopher/rosetta-code
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#Python
Python
############################# # Create a passwd text file ############################# # note that UID & gid are of type "text" passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, # UID and GID are type int GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', ...
Give a code snippet in #Python Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Slate
Slate
define: #name -> (query: 'Enter a variable name: ') intern. "X" define: name -> 42. X print.
Give a code snippet in #Slate Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#J
J
INTERACT=: noun define pc interact; cc Value edit center; cc increment button;cn "Increment"; cc random button;cn "Random"; pas 6 6;pcenter; )   interact_run=: verb define wd INTERACT wd 'set Value text 0;' wd 'pshow;' )   interact_cancel=: interact_close=: verb define wd'pclose' )   interact_Value_button=: verb de...
Give a code snippet in #J Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#ATS
ATS
(* The Rosetta Code linear list type can contain any vt@ype. (The ‘@’ means it doesn’t have to be the size of a pointer. You can read {0 <= n} as ‘for all non-negative n’. *) dataviewtype rclist_vt (vt : vt@ype+, n : int) = | rclist_vt_nil (vt, 0) | {0 <= n} rclist_vt_cons (vt, n + 1) of (vt, rclist_vt (vt, n))  ...
Give a code snippet in #ATS singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element defin...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln("Hello world!"); end func;
Give a code snippet in #Seed7 Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#zkl
zkl
fcn printVerse(name){ z,x := name[0].toLower(), z.toUpper() + name[1,*].toLower(); y:=( if("aeiou".holds(z)) name.toLower() else x[1,*] ); b,f,m := T("b","f","m").apply('wrap(c){ z==c and y or c+y }); println("%s, %s, bo-%s".fmt(x,x,b)); println("Banana-fana fo-",f); println("Fee-fi-mo-",m); printl...
Give a code snippet in #zkl Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like ...
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Factor
Factor
: symmetric-diff ( a b -- c ) [ diff ] [ swap diff ] 2bi append ;   { "John" "Bob" "Mary" "Serena" } { "Jim" "Mary" "John" "Bob" } symmetric-diff .
Give a code snippet in #Factor Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Scheme
Scheme
  (import (scheme base) (scheme read) (scheme write) (srfi 27)) ; random numbers   (define *start-position* #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #\space)) (random-source-randomize! default-random-source)   ;; return a 16-place vector with the tiles randomly shuffled (define (create-start-pos...
Give a code snippet in #Scheme Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Wren
Wren
/* query.wren */   class RCQuery { // Both arguments are lists as we need pass by reference here static query(Data, Length) { var s = "Here am I" var sc = s.count if (sc > Length[0]) return 0 // buffer too small for (i in 0...sc) Data[i] = s[i].bytes[0] Length[0] = sc ...
Give a code snippet in #Wren This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case...
#C.23
C#
using System;   namespace EulerSumOfPowers { class Program { const int MAX_NUMBER = 250;   static void Main(string[] args) { bool found = false; long[] fifth = new long[MAX_NUMBER];   for (int i = 1; i <= MAX_NUMBER; i++) { long i2 = i * i; ...
Give a code snippet in #C.23 There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Erlang
Erlang
-module(stack_traces).   -export([main/0]).   main() -> {ok,A} = outer(), io:format("~p\n", [A]).   outer() -> {ok,A} = middle(), {ok,A}.   middle() -> {ok,A} = inner(), {ok,A}.   inner() -> try throw(42) catch 42 -> {ok,erlang:get_stacktrace()} end.
Give a code snippet in #Erlang Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Odd_word_problem
Odd word problem
Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one punctuation, the stream will...
#Python
Python
from sys import stdin, stdout   def char_in(): return stdin.read(1) def char_out(c): stdout.write(c)   def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.'   # delay action until later, in the shape of a closure def clos(): char_out(a) prev()   return odd(clo...
Give a code snippet in #Python Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only o...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th...
#Go
Go
package main   import ( "bufio" "os" )   func main() { in := bufio.NewReader(os.Stdin) var blankLine = "\n" var printLongest func(string) string printLongest = func(candidate string) (longest string) { longest = candidate s, err := in.ReadString('\n') defer func() { ...
Give a code snippet in #Go Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge ...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#MontiLang
MontiLang
|ha| 5 * PRINT .
Give a code snippet in #MontiLang Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*",...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#BASIC
BASIC
Declare Function modulo(x As Double, y As Double) As Double Declare Function wd(m As Double, d As Double, y As Double) As Integer   Cls Dim yr As Double For yr = 2008 To 2121 If wd(12,25,yr) = 1 Then Print "Dec " & 25 & ", " & yr EndIf Next Sleep   Function modulo(x As Double, y As Double) As Double If y = 0 Then ...
Give a code snippet in #BASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#R
R
# Number Names   ones <- c("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen") tens <- c("ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety") m...
Give a code snippet in #R Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive...
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#Ruby
Ruby
require 'singleton' class MySingleton include Singleton # constructor and/or methods go here end   a = MySingleton.instance # instance is only created the first time it is requested b = MySingleton.instance puts a.equal?(b) # outputs "true"
Give a code snippet in #Ruby A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#Pascal
Pascal
program xshowwindow; {$mode objfpc}{$H+}   uses xlib, x, ctypes;   procedure ModalShowX11Window(AMsg: string); var d: PDisplay; w: TWindow; e: TXEvent; msg: PChar; s: cint; begin msg := PChar(AMsg);   { open connection with the server } d := XOpenDisplay(nil); if (d = nil) then begin WriteLn('...
Give a code snippet in #Pascal Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Erlang
Erlang
-module(bulls_and_cows). -export([generate_secret/0, score_guess/2, play/0]).   % generate the secret code generate_secret() -> generate_secret([], 4, lists:seq(1,9)). generate_secret(Secret, 0, _) -> Secret; generate_secret(Secret, N, Digits) -> Next = lists:nth(random:uniform(length(Digits)), Digits), generate_se...
Give a code snippet in #Erlang Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Kotlin
Kotlin
// version 1.1.2   fun getCode(c: Char) = when (c) { 'B', 'F', 'P', 'V' -> "1" 'C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z' -> "2" 'D', 'T' -> "3" 'L' -> "4" 'M', 'N' -> "5" 'R' -> "6" 'H', 'W' -> "-" else -> "" }   fun soundex(s: String): String { if (s == "") return "" val sb = Strin...
Give a code snippet in #Kotlin Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Processing
Processing
void setup() { println("First 25 abundant odd numbers: "); int abundant = 0; int i = 1; while (abundant < 25) { int sigma_sum = sigma(i); if (sigma_sum > 2 * i) { abundant++; println(i + " Sigma sum: " + sigma_sum); } i += 2; } println("Thousandth abundant odd number: "); whil...
Give a code snippet in #Processing An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#REALbasic
REALbasic
Sub Renamer() Dim f As FolderItem, r As FolderItem   f = GetFolderItem("input.txt") 'Changing a FolderItem's Name attribute renames the file or directory. If f.Exists Then f.Name = "output.txt" 'Files and directories are handled almost identically in RB. f = GetFolderItem("docs") If f.Exists...
Give a code snippet in #REALbasic Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has th...
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#VBA
VBA
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlXYScatter .HasLegend = False .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(...
Give a code snippet in #VBA The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Smalltalk
Smalltalk
SystemWindow new openInWorld.
Give a code snippet in #Smalltalk Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Elixir
Elixir
defmodule RBtree do def find(nil, _), do: :not_found def find({ key, value, _, _, _ }, key), do: { :found, { key, value } } def find({ key1, _, _, left, _ }, key) when key < key1, do: find(left, key) def find({ key1, _, _, _, right }, key) when key > key1, do: find(right, key)   def new(key, value), do: ins(n...
Give a code snippet in #Elixir Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#REXX
REXX
/*REXX program demonstrates that functions can be nested (an outer and inner function).*/ ctr= 0 /*initialize the CTR REXX variable.*/ call MakeList '. ' /*invoke MakeList with the separator.*/ exit 0 ...
Give a code snippet in #REXX In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two ...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Phixmonti
Phixmonti
def rep /# s n -- s #/ "" swap for drop over chain endfor nip enddef   "ha" 5 rep print
Give a code snippet in #Phixmonti Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*",...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#Icon_and_Unicon
Icon and Unicon
link graphics,numbers,printf   procedure main() # pinstripe   &window := open("Colour Pinstripe","g","bg=black") | stop("Unable to open window")   WAttrib("canvas=hidden") WAttrib(sprintf("size=%d,%d",WAttrib("displaywidth"),WAttrib("displayheight"))) WAttrib("canvas=maximal")   Colours := ["bl...
Give a code snippet in #Icon_and_Unicon The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   b...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#SNOBOL4
SNOBOL4
s1 = s2 = " Hello, people of earth! " s2 = CHAR(3) s2 CHAR(134) &ALPHABET TAB(33) . prechars &ALPHABET POS(127) RTAB(0) . postchars stripchars = " " prechars postchars   * TRIM() removes final spaces and tabs: OUTPUT = "Original: >" s1 "<" OUTPUT = "With trim() >" REVERSE(TRIM(REVERSE(TR...
Give a code snippet in #SNOBOL4 Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace ...
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
#C.2B.2B
C++
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget>   class QPaintEvent ;   class MyWidget : public QWidget { public : MyWidget( ) ;   protected : void paintEvent( QPaintEvent * ) ; private : int width ; int height ; const int colornumber ; } ; #endif
Give a code snippet in #C.2B.2B 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/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#OCaml
OCaml
let p x y = let d = sqrt(x ** 2.0 +. y ** 2.0) in 10.0 <= d && d <= 15.0   let () = Random.self_init(); let rec aux i acc = if i >= 100 then acc else let x = (Random.float 40.0) -. 20.0 and y = (Random.float 40.0) -. 20.0 in if (p x y) then aux (succ i) ((x,y)::acc) else aux i ...
Give a code snippet in #OCaml Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" cir...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#Egel
Egel
  import "prelude.eg" import "io.ego" import "random.ego"   using System using IO using List using Math   def swap = [ (I J) XX -> insert I (nth J XX) (insert J (nth I XX) XX) ]   def shuffle = [ XX -> let INDICES = reverse (fromto 0 ((length XX) - 1)) in let SWAPS = map [ I -> I (between 0 I) ]...
Give a code snippet in #Egel Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The sco...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Go
Go
if booleanExpression { statements }
Give a code snippet in #Go Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common con...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Factor
Factor
foo
Give a code snippet in #Factor Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a v...
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#PARI.2FGP
PARI/GP
label jumpto; begin ... jumpto: some statement; ... goto jumpto; ... end;
Give a code snippet in #PARI.2FGP Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   constr...
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#Perl
Perl
sub encode { shift =~ s/(.)\1*/length($&).$1/grse; }   sub decode { shift =~ s/(\d+)(.)/$2 x $1/grse; }
Give a code snippet in #Perl Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a funct...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Phix
Phix
with javascript_semantics function inOrder(sequence s) for i=2 to length(s) do if s[i]<s[i-1] then return false end if end for return true end function function permutationSort(sequence s) for n=1 to factorial(length(s)) do sequence perm = permute(n,s) if inOrder(perm) then re...
Give a code snippet in #Phix 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/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...
#Raku
Raku
sub mangle ($name, $initial) { my $fl = $name.lc.substr(0,1); $fl ~~ /<[aeiou]>/ ?? $initial~$name.lc !! $fl eq $initial ?? $name.substr(1) !! $initial~$name.substr(1) }   sub name-game (Str $name) { qq:to/NAME-GAME/; $name, $name, bo-{ mangle $name, 'b' } Banana-fana fo-{ mangle $na...
Give a code snippet in #Raku Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical 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 |...
#Modula-2
Modula-2
MODULE LogicalOps; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE Print(a,b : BOOLEAN); VAR buf : ARRAY[0..31] OF CHAR; BEGIN FormatString("a and b is %b\n", buf, a AND b); WriteString(buf); FormatString("a or b is %b\n", buf, a OR b); WriteString(b...
Give a code snippet in #Modula-2 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 Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Toka
Toka
[ ( string -- flag ) >number nip ] is isNumeric   ( Some tests ) decimal " 100" isNumeric . ( succeeds, 100 is a valid decimal integer ) " 100.21" isNumeric . ( fails, 100.21 is not an integer) " a" isNumeric . ( fails, 'a' is not a valid integer in the decimal base ) " $a" isNumeric . ( succeeds, bec...
Give a code snippet in #Toka Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#Racket
Racket
  #lang racket (require data/heap "../lib/vector2.rkt" "../lib/queue.rkt" (only-in "../lib/util.rkt" push! tstruct ret awhen))   (define level (list "#######" "# #" "# #" "#. # #" "#. $$ #" "#.$$ #" ...
Give a code snippet in #Racket Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character...
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. ...
#Clojure
Clojure
(doseq [i (range 5), j (range (inc i))] (print "*") (if (= i j) (println)))
Give a code snippet in #Clojure “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 struc...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Action.21
Action!
DEFINE MAX="100" INT ARRAY keys(MAX) INT ARRAY values(MAX) BYTE count   PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC ClearMap() count=0 RETURN   PROC AddToMap(INT a) INT i,index   index=-1 IF co...
Give a code snippet in #Action.21 Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), i...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#ooRexx
ooRexx
  loop candidate = 6 to 2**19 sum = .fraction~new(1, candidate) max2 = rxcalcsqrt(candidate)~trunc   loop factor = 2 to max2 if candidate // factor == 0 then do sum += .fraction~new(1, factor) sum += .fraction~new(1, candidate / factor) end end if sum == 1 then ...
Give a code snippet in #ooRexx Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator ...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#AWK
AWK
  # syntax: GAWK -f PRIMALITY_BY_WILSONS_THEOREM.AWK # converted from FreeBASIC BEGIN { start = 2 stop = 200 for (i=start; i<=stop; i++) { if (is_wilson_prime(i)) { printf("%5d%1s",i,++count%10?"":"\n") } } printf("\nWilson primality test range %d-%d: %d\n",start,stop,count) ...
Give a code snippet in #AWK Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Sidef
Sidef
for (var i = 10; i >= 0; i--) { say i }
Give a code snippet in #Sidef Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increm...
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#Common_Lisp
Common Lisp
(time (do some stuff))
Give a code snippet in #Common_Lisp Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accompli...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 ...
#Perl
Perl
sub stooge { use integer; my ($x, $i, $j) = @_;   $i //= 0; $j //= $#$x;   if ( $x->[$j] < $x->[$i] ) { @$x[$i, $j] = @$x[$j, $i]; } if ( $j - $i > 1 ) { my $t = ($j - $i + 1) / 3; stooge( $x, $i, $j - $t ); ...
Give a code snippet in #Perl 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/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#REBOL
REBOL
print ["Original:" original: "Hello,How,Are,You,Today"] tokens: parse original "," dotted: "" repeat i tokens [append dotted rejoin [i "."]] print ["Dotted: " dotted]
Give a code snippet in #REBOL Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks re...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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 ...
#OCaml
OCaml
let sortrefs list = let sorted = List.map ( ! ) list |> List.sort (fun a b -> if a < b then -1 else if a > b then 1 else 0) in List.iter2 (fun v x -> v := x) list sorted   open Printf   let test () = let x = ref "lions, tigers, and" in l...
Give a code snippet in #OCaml 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const func integer: randN (in integer: n) is return ord(rand(1, n) = 1);   const func integer: unbiased (in integer: n) is func result var integer: unbiased is 0; begin repeat unbiased := randN(n); until unbiased <> randN(n); end func;   const...
Give a code snippet in #Seed7 P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator ...
christopher/rosetta-code
http://rosettacode.org/wiki/Self_numbers
Self numbers
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. You should either confirm or d...
#F.23
F#
  // Self numbers. Nigel Galloway: October 6th., 2020 let fN g=let rec fG n g=match n/10 with 0->n+g |i->fG i (g+(n%10)) in fG g g let Self=let rec Self n i g=seq{let g=g@([n..i]|>List.map fN) in yield! List.except g [n..i]; yield! Self (n+100) (i+100) (List.filter(fun n->n>i) g)} in Self 0 99 []   Self |> Seq.take 5...
Give a code snippet in #F.23 A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Python
Python
a = 5 #...input or change a here assert a == 42 # throws an AssertionError when a is not 42 assert a == 42, "Error message" # throws an AssertionError # when a is not 42 with "Error message" for the message # the error message can be any expression
Give a code snippet in #Python Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#D
D
import std.stdio, std.random, std.string, std.array, std.algorithm, std.file, std.conv;   enum int cx = 4, cy = 2; // Cell size x and y. enum int cx2 = cx / 2, cy2 = cy / 2; enum pathSymbol = '.'; struct V2 { int x, y; }   bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow @safe @nogc { if (s == ...
Give a code snippet in #D Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#XPL0
XPL0
char Deck(52); \card structure (low 2 bits = suit) def Players = 4; \number of players to deal to char Hand(Players, 52); \each player's hand int Card, N, I, J, T; char Suit, Royal; [for Card:= 0 to 52-1 do \make a new deck Deck(Card):= Card; for N:= 0 to 10...
Give a code snippet in #XPL0 Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current co...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Brat
Brat
zip = { keys, values | h = [:] keys.each_with_index { key, index | h[key] = values[index] }   h }   p zip [1 2 3] [:a :b :c] #Prints [1: a, 2: b, 3: c]
Give a code snippet in #Brat Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Def...
#F.23
F#
  open System.Collections.Generic   let first (l: LinkedList<char>) = l.First let last (l: LinkedList<char>) = l.Last   let next (l: LinkedListNode<char>) = l.Next let prev (l: LinkedListNode<char>) = l.Previous   let traverse g f (ls: LinkedList<char>) = let rec traverse (l: LinkedListNode<char>) = match l...
Give a code snippet in #F.23 Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Re...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Ring
Ring
  see "11^5 = " + ipow(11, 5) + nl see "pi^3 = " + fpow(3.14, 3) + nl   func ipow a, b p2 = 1 for i = 1 to 32 p2 *= p2 if b < 0 p2 *= a ok b = b << 1 next return p2   func fpow a, b p = 1 for i = 1 to 32 p *= p if b < 0 p *= a ok b = ...
Give a code snippet in #Ring Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or proc...
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
#Lasso
Lasso
local(lasso = " --------------------------------------------------------------- | ,--, | | ,---.'| ,----.. | | | | : ,---, .--.--. .--.--. / / \\ | | :  : | ' .' \\ / / '. / / ...
Give a code snippet in #Lasso 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/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Arturo
Arturo
getDifference: function [b1, b2][ r: (b2 - b1) % 360.0   if r >= 180.0 -> r: r - 360.0   return r ]   print "Input in -180 to +180 range" print getDifference 20.0 45.0 print getDifference neg 45.0 45.0 print getDifference neg 85.0 90.0 print getDifference neg 95.0 90.0 print getDifference neg 45.0 1...
Give a code snippet in #Arturo Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Biorhythms
Biorhythms
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that u...
#Locomotive_Basic
Locomotive Basic
10 input "Birthday (y,m,d) ",y,m,d:gosub 3000 20 gosub 1000 30 bday = day 40 input "Today's date (y,m,d) ",y,m,d:gosub 3000 50 gosub 1000 60 diff = day - bday 70 print:print "Age in days:" tab(22) diff 80 t$ = "physical":l = 23:gosub 2000 90 t$ = "emotional":l = 28:gosub 2000 100 t$ = "intellectual":l = 33:gosub 2000 9...
Give a code snippet in #Locomotive_Basic For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Tcl
Tcl
proc fusc n { if {$n < 2} { return $n }   if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) }   if {$n % 2} { ;# n is odd set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}] } else { ;# n is even set r [fusc [expr {$n/2}]] ...
Give a code snippet in #Tcl Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition star...
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...
#ActionScript
ActionScript
function combSort(input:Array) { var gap:uint = input.length; var swapped:Boolean = false; while(gap > 1 || swapped) { gap /= 1.25; swapped = false; for(var i:uint = 0; i + gap < input.length; i++) { if(input[i] > input[i+gap]) { var tmp = input[i]; input[i] = input[i+gap]; input[i+gap]=tm...
Give a code snippet in #ActionScript 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 co...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Ada
Ada
with Ada.Command_Line, Ada.Text_IO;   procedure Josephus is   function Arg(Idx, Default: Positive) return Positive is -- read Argument(Idx) (if Ada.Command_Line.Argument_Count >= Index then Positive'Value(Ada.Command_Line.Argument(Index)) else Default);   Prisoners: constant Positive := Arg(Idx =>...
Give a code snippet in #Ada Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Ceylon
Ceylon
shared void run() {   {Integer*} hailstone(variable Integer n) { variable [Integer*] stones = [n]; while(n != 1) { n = if(n.even) then n / 2 else 3 * n + 1; stones = stones.append([n]); } return stones; }   value hs27 = hailstone(27); print("hailstone sequence for 27 is ``hs27.take(3)``...``hs27.skip(...
Give a code snippet in #Ceylon The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Topological_sort
Topological 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 ...
#Swift
Swift
let libs = [ ("des_system_lib", ["std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"]), ("dw01", ["ieee", "dw01", "dware", "gtech"]), ("dw02", ["ieee", "dw02", "dware"]), ("dw03", ["std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"]), ("dw04", ["dw04", "ieee"...
Give a code snippet in #Swift 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#AutoHotkey
AutoHotkey
Loop { If isHappy(A_Index) { out .= (out="" ? "" : ",") . A_Index i ++ If (i = 8) { MsgBox, The first 8 happy numbers are: %out% ExitApp } } }   isHappy(num, list="") { list .= (list="" ? "" : ",") . num Loop, Parse, num sum += A_LoopField ** 2 If (sum = 1) Return true El...
Give a code snippet in #AutoHotkey From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endle...
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#MiniZinc
MiniZinc
  %Solve Zebra Puzzle. Nigel Galloway, August 27th., 2019 include "alldifferent.mzn"; enum N={English,Swedish,Danish,German,Norwegian}; enum I={Tea,Coffee,Milk,Beer,Water}; enum G={Dog,Birds,Cats,Horse,Zebra}; enum E={Red,Green,White,Blue,Yellow}; enum L={PallMall,Dunhill,BlueMaster,Prince,Blend}; array[1..5] of var N:...
Give a code snippet in #MiniZinc Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Java
Java
import javax.swing.*; import java.awt.*;   public class OutputSwing {   public static void main(String[] args) {   SwingUtilities.invokeLater(new Runnable(){ public void run() { JOptionPane.showMessageDialog (null, "Goodbye, World!"); // in alert box JFrame frame ...
Give a code snippet in #Java Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#zkl
zkl
(0).pump(10,List,fcn(i){i*i}.fp)[8]() //-->64 list:=(0).pump(10,List,fcn(i){i*i}.fp); foreach n in (list.len()-1) { list[n]().println() } list.run(True).println()
Give a code snippet in #zkl Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Phix
Phix
with javascript_semantics integer n = 6, x = 1, y = 0, counter = 0, len = n, dx = 0, dy = 1 string fmt = sprintf("%%%dd",length(sprintf("%d",n*n))) sequence m = repeat(repeat("??",n),n) for i=1 to 2*n do -- 2n runs.. for j=1 to len do -- of a length... x += d...
Give a code snippet in #Phix Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 ...
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...
#LOLCODE
LOLCODE
HAI CAN HAS STDIO? IM IN YR LOOP VISIBLE "SPAM" IM OUTTA YR LOOP KTHXBYE
Give a code snippet in #LOLCODE 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   Lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Quackery
Quackery
[ abs 0 swap [ base share /mod rot + swap dup 0 = until ] drop ] is digitsum ( n --> n )   [ 0 swap [ dup base share > while dip 1+ digitsum again ] ] is digitalroot ( n --> n n )   [ dup digitalroot rot echo say " has additive persistance " ...
Give a code snippet in #Quackery The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} ...
christopher/rosetta-code
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Go
Go
// Implmentation following pseudocode from "An intoductory tutorial on kd-trees" // by Andrew W. Moore, Carnegie Mellon University, PDF accessed from // http://www.autonlab.org/autonweb/14665 package main   import ( "fmt" "math" "math/rand" "sort" "time" )   // point is a k-dimensional point. type p...
Give a code snippet in #Go This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a...
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...
#4DOS_Batch
4DOS Batch
@echo off do forever echo SPAM enddo
Give a code snippet in #4DOS_Batch 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  ...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#Euphoria
Euphoria
  include GtkEngine.e -- see OpenEuphoria.org   constant -- interface win = create(GtkWindow,"title=GUI Component Interaction;size=200x100;border=10;$destroy=Quit"), pan = create(GtkBox,"orientation=vertical;spacing=10"), inp = create(GtkEntry,"name=Input;text=0;$activate=Validate"), box = create(GtkBut...
Give a code snippet in #Euphoria Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and chec...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Forth
Forth
: josephus 0 1 begin dup 41 <= while swap 3 + over mod swap 1+ repeat drop ;
Give a code snippet in #Forth Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\...
christopher/rosetta-code
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the i...
#UNIX_Shell
UNIX Shell
  macList=("88:53:2E:67:07:BE" "D4:F4:6F:C9:EF:8D" "FC:FB:FB:01:FA:21" "4c:72:b9:56:fe:bc" "00-14-22-01-23-45");for burger in ${macList[@]};do curl http://api.macvendors.com/$burger && sleep 5 && echo;done  
Give a code snippet in #UNIX_Shell Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (o...
christopher/rosetta-code
http://rosettacode.org/wiki/Padovan_sequence
Padovan sequence
The Padovan sequence is similar to the Fibonacci sequence in several ways. Some are given in the table below, and the referenced video shows some of the geometric similarities. Comment Padovan Fibonacci Named after. Richard Padovan Leonardo of Pisa: Fibonacci Recurrence initial values....
#Phix
Phix
with javascript_semantics sequence padovan = {1,1,1} function padovanr(integer n) while length(padovan)<n do padovan &= padovan[$-2]+padovan[$-1] end while return padovan[n] end function constant p = 1.324717957244746025960908854, s = 1.0453567932525329623 function padovana(integer n) ...
Give a code snippet in #Phix The Padovan sequence is similar to the Fibonacci sequence in several ways. Some are given in the table below, and the referenced video shows some of the geometric similarities. Comment Padovan Fibonacci Named after. Richard Padovan Leonardo of Pisa: Fibonacci ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe
Bitmap/PPM conversion through a pipe
Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page. There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux)...
#OCaml
OCaml
let print_jpeg ~img ?(quality=96) () = let cmd = Printf.sprintf "cjpeg -quality %d" quality in (* let cmd = Printf.sprintf "ppmtojpeg -quality %d" quality in let cmd = Printf.sprintf "convert ppm:- -quality %d jpg:-" quality in *) let ic, oc = Unix.open_process cmd in output_ppm ~img ~oc; try while ...
Give a code snippet in #OCaml Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page. There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtoj...
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
#Fortran
Fortran
sha256 rc.txt 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF rc.txt (12 bytes)
Give a code snippet in #Fortran 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: 764faf5c61ac315f1497f9dfa542713965b...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Java
Java
public class Clear { public static void main (String[] args) { System.out.print("\033[2J"); } }
Give a code snippet in #Java Task Clear the terminal window.
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#C.2B.2B
C++
#include <iostream> #include <boost/multiprecision/gmp.hpp> #include <string>   namespace mp = boost::multiprecision;   int main(int argc, char const *argv[]) { // We could just use (1 << 18) instead of tmpres, but let's point out one // pecularity with gmp and hence boost::multiprecision: they won't accept ...
Give a code snippet in #C.2B.2B Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
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...
#Julia
Julia
function guesswithfeedback(n::Integer) number = rand(1:n) print("I choose a number between 1 and $n\nYour guess? ") while (guess = readline()) != dec(number) if all(isdigit, guess) print("Too ", parse(Int, guess) < number ? "small" : "big") else print("Enter an intege...
Give a code snippet in #Julia 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: hi...
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#11l
11l
F fusc(n) V res = [0] * n res[1] = 1 L(i) 2 .< n res[i] = I i % 2 == 0 {res[i I/ 2]} E res[(i-1) I/ 2] + res[(i+1) I/ 2] R res   print(‘First 61 terms:’) print(fusc(61))   print() print(‘Points in the sequence where an item has more digits than any previous items:’) V f = fusc(20'000'000) V max_len = ...
Give a code snippet in #11l Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition star...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#BaCon
BaCon
OPTION GUI TRUE   gui = GUIDEFINE("{ type=window name=window XtNtitle=\"Graphical\" } \ { type=labelWidgetClass name=label parent=window XtNlabel=\"Goodbye, World!\" } ")   CALL GUIEVENT$(gui)
Give a code snippet in #BaCon Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Maple
Maple
> dog, Dog, DOG := "Benjamin", "Samba", "Bernie": > if nops( { dog, Dog, DOG } ) = 3 then > printf( "There are three dogs named %s, %s and %s.\n", dog, Dog, DOG ) > elif nops( { dog, Dog, DOG } ) = 2 then > printf( "WTF? There are two dogs named %s and %s.\n", op( { dog, Dog, DOG } ) ) > else > printf( "There is ...
Give a code snippet in #Maple Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Sa...
christopher/rosetta-code