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/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 ...
#Fortran
Fortran
  ! module circlesort ! I have commented the code that was here and also 'tightened up' various pieces such as how swap detection was done as well ! as fixing an error where the code would exceed array bounds for odd number sized arrays. ! Also, giving some some attribution to the author. - Pete ! This code is a Fortra...
Give a code snippet in #Fortran Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#C.23
C#
using System.Diagnostics;   namespace RC { internal class Program { public static void Main() { string sSource = "Sample App"; string sLog = "Application"; string sEvent = "Hello from RC!";   if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog...
Give a code snippet in #C.23 Task Write script status to the Windows Event Log
christopher/rosetta-code
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#Phix
Phix
else -- rType=FUNC|TYPE log_function_call(rtnNo)
Give a code snippet in #Phix Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtim...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func bigInteger: leftFact (in integer: n) is func result var bigInteger: leftFact is 0_; local var bigInteger: factorial is 1_; var integer: i is 0; begin for i range 1 to n do leftFact +:= factorial; factorial *:= bigInteger co...
Give a code snippet in #Seed7 Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Objeck
Objeck
function : Multiply(a : Float, b : Float) ~, Float { return a * b; }
Give a code snippet in #Objeck A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#BASIC
BASIC
100 FOR I = 1 TO 20 110 GOSUB 200"FACTORIAL 120 PRINT I" = "FA$ 130 NEXT I 140 END   200 FA$ = "1" 210 LET NUM = I 220 LET O = 5 - (I = 1) * 4 230 FOR F = 2 TO I 240 LET M = INT (NUM / F) * F 250 IF NUM - M GOTO 300 260 LET NUM = NUM / F 270 LET F$ = STR $(F) ...
Give a code snippet in #BASIC Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Liberty_BASIC
Liberty BASIC
fileName$ ="F:\sample.txt" requiredLine =7   open fileName$ for input as #i f$ =input$( #i, lof( #i)) close #i   line7$ =word$( f$, 7, chr$( 13)) if line7$ =chr$( 13) +chr$( 10) or line7$ ="" then notice "Empty line! ( or file has fewer lines)."   print line7$
Give a code snippet in #Liberty_BASIC Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and st...
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#True_BASIC
True BASIC
DIM menu$(4) MAT READ menu$ DATA "fee fie", "huff and puff", "mirror mirror", "tick tock"   FUNCTION sel$(choices$()) IF UBOUND(choices$) - LBOUND(choices$) = 0 THEN LET sel$ = "" LET ret$ = "" DO FOR i = LBOUND(choices$) TO UBOUND(choices$) PRINT i; ": "; choices$(i) NEXT i ...
Give a code snippet in #True_BASIC Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Jsish
Jsish
/* Identity matrix, in Jsish */ function identityMatrix(n) { var mat = new Array(n).fill(0); for (var r in mat) { mat[r] = new Array(n).fill(0); mat[r][r] = 1; } return mat; }   provide('identityMatrix', 1);   if (Interp.conf('unitTest')) { ; identityMatrix(0); ; identityMatrix(1);...
Give a code snippet in #Jsish Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Gener...
#Ruby
Ruby
rpn = RPNExpression.from_infix("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3")
Give a code snippet in #Ruby Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens represent...
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...
#Scala
Scala
import java.util   object DoublyLinkedListTraversal extends App {   private val ll = new util.LinkedList[String]   private def traverse(iter: util.Iterator[String]) = while (iter.hasNext) iter.next   traverse(ll.iterator) traverse(ll.descendingIterator) }
Give a code snippet in #Scala 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 R...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Elena
Elena
import system'routines; import extensions;   class Foo;   // create a list of disting object fill(n) = RangeEnumerator.new(1,n).selectBy:(x => new Foo()).toArray();   // testing public program() { var foos := fill(10); }
Give a code snippet in #Elena Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are consider...
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...
#Z80_Assembly
Z80 Assembly
PrintString: ld a,(hl) ;HL is our pointer to the string we want to print cp 0 ;it's better to use OR A to compare A to zero, but for demonstration purposes this is easier to read. ret z ;return if accumulator = zero call PrintChar ;prints accumulator's ascii code to screen - on Amstrad CPC f...
Give a code snippet in #Z80_Assembly 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   con...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#AutoHotkey
AutoHotkey
MsgBox % compose("sin","cos",1.5)   compose(f,g,x) { ; function composition Return %f%(%g%(x)) }
Give a code snippet in #AutoHotkey Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function  ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Lambdatalk
Lambdatalk
  {def christian_name Albert} -> christian_name {def name de Jeumont-Schneidre} -> name   {christian_name} {name} -> Albert de Jeumont-Schneidre  
Give a code snippet in #Lambdatalk String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another strin...
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#BQN
BQN
FDiff ← {{-˜´˘2↕𝕩}⍟𝕨 𝕩}   •Show 1 FDiff 90‿47‿58‿29‿22‿32‿55‿5‿55‿73 •Show 2 FDiff 90‿47‿58‿29‿22‿32‿55‿5‿55‿73
Give a code snippet in #BQN Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#Perl
Perl
use Data::Dumper qw(Dumper);   sub hashJoin { my ($table1, $index1, $table2, $index2) = @_; my %h; # hash phase foreach my $s (@$table1) { push @{ $h{$s->[$index1]} }, $s; } # join phase map { my $r = $_; map [$_, $r], @{ $h{$r->[$index2]} } } @$table2; }   @table1 = ([27, "Jonah"], ...
Give a code snippet in #Perl An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#AWK
AWK
  # syntax: GAWK -f MULTIFACTORIAL.AWK # converted from Go BEGIN { for (k=1; k<=5; k++) { printf("degree %d:",k) for (n=1; n<=10; n++) { printf(" %d",multi_factorial(n,k)) } printf("\n") } exit(0) } function multi_factorial(n,k, r) { r = 1 for (; n>1; n-=k) { r...
Give a code snippet in #AWK The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i"; include "draw.s7i"; include "keybd.s7i"; include "time.s7i"; include "duration.s7i";   const integer: WINDOW_WIDTH is 200; const integer: WINDOW_HEIGHT is 200; const color: BACKGROUND is White; const color: FOREGROUND is Black; const color: ...
Give a code snippet in #Seed7 Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Common_Lisp
Common Lisp
  (print (length #("apple" "orange")))  
Give a code snippet in #Common_Lisp Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter...
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
#ooRexx
ooRexx
/* Rexx */ say 'Hello world!'  
Give a code snippet in #ooRexx 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/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Racket
Racket
#lang racket/base   ;; Racket's `directory-list' produces a sorted list of files (define (ls) (for-each displayln (directory-list)))   ;; Code to run when this file is running directly (module+ main (ls))   (module+ test (require tests/eli-tester racket/port racket/file) (define (make-directory-tree) (make-di...
Give a code snippet in #Racket Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Examp...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Ruby
Ruby
Headings = %w(north east south west north).each_cons(2).flat_map do |a, b| [a, "#{a} by #{b}", "#{a}-#{a}#{b}", "#{a}#{b} by #{a}", "#{a}#{b}", "#{a}#{b} by #{b}", "#{b}-#{a}#{b}", "#{b} by #{a}"] end Headings.prepend nil   def heading(degrees) i = degrees.quo(360).*(32).round.%(32).+(1) [i, Headin...
Give a code snippet in #Ruby There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Frink
Frink
  // Maximum levels for each pixel. levels = 60   // Create a random color for each level. colors = new array[[levels]] for a = 0 to levels-1 colors@a = new color[randomFloat[0,1], randomFloat[0,1], randomFloat[0,1]]   // Make this number smaller for higher resolution. stepsize = .005   g = new graphics g.antialiase...
Give a code snippet in #Frink Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#Lua
Lua
-- Return an iterator to produce every permutation of list function permute (list) local function perm (list, n) if n == 0 then coroutine.yield(list) end for i = 1, n do list[i], list[n] = list[n], list[i] perm(list, n - 1) list[i], list[n] = list[n], list[i] ...
Give a code snippet in #Lua Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative example of Currying in a specific la...
#Java
Java
public class Currier<ARG1, ARG2, RET> { public interface CurriableFunctor<ARG1, ARG2, RET> { RET evaluate(ARG1 arg1, ARG2 arg2); }   public interface CurriedFunctor<ARG2, RET> { RET evaluate(ARG2 arg); }   final CurriableFunctor<ARG1, ARG2, RET> functo...
Give a code snippet in #Java This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative exampl...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#Forth
Forth
: quaternions 4 * floats ;   : qvariable create 1 quaternions allot ;   : q! ( a b c d q -- ) dup 3 floats + f! dup 2 floats + f! dup float+ f! f! ;   : qcopy ( src dest -- ) 1 quaternions move ;   : qnorm ( q -- f ) 0e 4 0 do dup f@ fdup f* f+ float+ loop drop fsqrt ;   : qf* ( q f -- ) 4 0 do dup f@ fove...
Give a code snippet in #Forth Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Python
Python
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import __future__ >>> __future__.all_feature_names ['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals'...
Give a code snippet in #Python Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrat...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Wren
Wren
import "random" for Random import "/ioutil" for Input import "/seq" for Stack   var R = Random.new()   class Game24 { static run() { var digits = List.filled(4, 0) for (i in 0..3) digits[i] = R.int(1, 10) System.print("Make 24 using these digits: %(digits)") var cin = Input.text("> "...
Give a code snippet in #Wren The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four dig...
christopher/rosetta-code
http://rosettacode.org/wiki/Ascending_primes
Ascending primes
Generate and show all primes with strictly ascending decimal digits. Aside: Try solving without peeking at existing solutions. I had a weird idea for generating a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial but generating them quickly is at least mildly interesting. T...
#Quackery
Quackery
[ 0 swap witheach [ swap 10 * + ] ] is digits->n ( [ --> n )   [] ' [ 1 2 3 4 5 6 7 8 9 ] powerset witheach [ digits->n dup isprime iff join else drop ] sort echo
Give a code snippet in #Quackery Generate and show all primes with strictly ascending decimal digits. Aside: Try solving without peeking at existing solutions. I had a weird idea for generating a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial but generating them quickly...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Mercury
Mercury
:- module department_numbers. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is cc_multi.   :- implementation.   :- import_module int, list, solutions, string.   main(!IO) :- io.print_line("P S F", !IO), unsorted_aggregate(department_number, print_solution, !IO).   :- pred print_solution({int...
Give a code snippet in #Mercury There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#HicEst
HicEst
REAL :: mtx(2, 4)   mtx = 1.1 * $ WRITE() mtx   SOLVE(Matrix=mtx, Transpose=mtx) WRITE() mtx
Give a code snippet in #HicEst Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#Frink
Frink
  ### MMM dd yyyy h:mma ### d = parseDate["March 7 2009 7:30pm EST"] println[d + 12 hours -> Eastern] println[d + 12 hours -> Switzerland] // Extra credit  
Give a code snippet in #Frink Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#Red
Red
Red [ Source: https://github.com/vazub/rosetta-red Tabs: 4 Needs: 'View ]   canvas: 500x500 center: as-pair canvas/x / 2 canvas/y / 2 radius: 200   points: collect [ repeat vertex 10 [ angle: vertex * 36 + 18 ;-- +18 is required for pentagram rotation either vertex // 2 = 1 [ keep as-pair (co...
Give a code snippet in #Red A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) f...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#PL.2FI
PL/I
  get list (n); put skip list (n); /* Prints N in decimal */ put skip edit (n) (B); /* prints N as a bit string, N > 0 */  
Give a code snippet in #PL.2FI Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard ro...
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...
#Ring
Ring
  rename("input.txt", "output.txt") rename("docs", "mydocs") rename("/input.txt", "/output.txt") rename("/docs", "/mydocs")  
Give a code snippet in #Ring Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rig...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#REBOL
REBOL
rebol [ Title: "Simple Windowed Application" URL: http://rosettacode.org/wiki/Simple_Windowed_Application ]   clicks: 0   ; Simple GUI's in REBOL can be defined with 'layout', a ; special-purpose language (dialect, in REBOL-speak) for specifying ; interfaces. In the example below, I describe a gradient background ; w...
Give a code snippet in #REBOL Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C
C
#include <stdio.h> #include <string.h> #include <stdlib.h>   int interactiveCompare(const void *x1, const void *x2) { const char *s1 = *(const char * const *)x1; const char *s2 = *(const char * const *)x2; static int count = 0; printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2); int re...
Give a code snippet in #C Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#Yabasic
Yabasic
sub d6() //simulates a marked regular hexahedron coming to rest on a plane return 1 + int(ran(6)) end sub   sub roll_stat() //rolls four dice, returns the sum of the three highest a = d6() : b = d6(): c = d6(): d = d6() return a + b + c + d - min(min(a, b), min(c, d)) end sub   dim statnames$(6) st...
Give a code snippet in #Yabasic RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
survivor[n_, k_] := Nest[Most[RotateLeft[#, k]] &, Range[0, n - 1], n - 1] survivor[41, 3]
Give a code snippet in #Mathematica.2FWolfram_Language 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associativ...
#11l
11l
V base = [‘name’ = ‘Rocket Skates’, ‘price’ = ‘12.75’, ‘color’ = ‘yellow’] V update = [‘price’ = ‘15.25’, ‘color’ = ‘red’, ‘year’ = ‘1974’]   V result = copy(base) result.update(update)   print(result)
Give a code snippet in #11l Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merg...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Nanoquery
Nanoquery
import math   // a function to check if three numbers are a valid triple def is_triple(a, b, c) if not (a < b) and (b < c) return false end   return (a^2 + b^2) = c^2 end   // a function to check if the numbers are coprime def is_coprime(a, b, c) global math return (math.gcd(a, b)=1) && (mat...
Give a code snippet in #Nanoquery A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\...
christopher/rosetta-code
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch...
#Phix
Phix
with javascript_semantics constant limit = 19 integer count = 0, n = 0 printf(1,"The first 19 Disarium numbers are:\n") while count<limit do atom dsum = 0 string digits = sprintf("%d",n) for i=1 to length(digits) do dsum += power(digits[i]-'0',i) end for if dsum=n then printf(1," %d...
Give a code snippet in #Phix A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#Sidef
Sidef
func fft(arr) { arr.len == 1 && return arr   var evn = fft([arr[^arr -> grep { .is_even }]]) var odd = fft([arr[^arr -> grep { .is_odd }]]) var twd = (Num.tau.i / arr.len)   ^odd -> map {|n| odd[n] *= ::exp(twd * n)} (evn »+« odd) + (evn »-« odd) }   var cycles = 3 var sequence = 0..15 var wave...
Give a code snippet in #Sidef Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magni...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Go.21
Go!
-- -- 99 Bottles of Beer in Go! -- John Knottenbelt -- -- Go! is a multi-paradigm programming language that is oriented -- to the needs of programming secure, production quality, agent -- based applications. -- -- http://www.doc.ic.ac.uk/~klc/dalt03.html --   main .. { include "sys:go/io.gof". include "sys:...
Give a code snippet in #Go.21 Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Tcl
Tcl
package require Tk set s "Hello World! " set dir 0 # Periodic animation callback proc animate {} { global dir s if {$dir} { set s [string range $s 1 end][string index $s 0] } else { set s [string index $s end][string range $s 0 end-1] } # We will run this code ~8 times a second (== 1...
Give a code snippet in #Tcl Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demo...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Red
Red
Red [] s: copy "abc" ;; string creation   s: none ;; destruction t: "Abc" if t == "abc" [print "equal case"] ;; comparison , case sensitive if t = "abc" [print "equal (case insensitive)"] ;; comparison , case insensitive s: copy "" ;; copying string if empty? s [pr...
Give a code snippet in #Red Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings accordi...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Logo
Logo
make "size 100 make "white 1 make "black 2 make "sum sum :white :black make "chars [. #] make "origin quotient :size 2 make "grid mdarray (list :size :size) make "directions [ [1 0] [0 1] [-1 0] [0 -1] ]   repeat size [ local "y make "y repcount repeat size [ mdsetitem (list repcount :y) :grid :white ] ] m...
Give a code snippet in #Logo Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#J
J
import java.math.BigInteger; public class Mersenne {   public static boolean isPrime(int p) { if (p == 2) return true; else if (p <= 1 || p % 2 == 0) return false; else { int to = (int)Math.sqrt(p); for (int i = 3; i <= to; i += 2) ...
Give a code snippet in #J Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   proc Bezier(P0, P1, P2); \Draw quadratic Bezier curve real P0, P1, P2; def Segments = 8; int I; real T, A, B, C, X, Y; [Move(fix(P0(0)), fix(P0(1))); for I:= 1 to Segments do [T:= float(I)/float(Segments); A:= sq(1.-T); B:...
Give a code snippet in #XPL0 Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#Draco
Draco
proc nonrec count_jewels(*char jewels, stones) word: [256] bool jewel; word count; byte i; char c;   for i from 0 upto 255 do jewel[i] := false od; while c := jewels*; c ~= '\e' do jewel[c] := true; jewels := jewels + 1; od;   count := 0; while c := stones*; c ~= '\e'...
Give a code snippet in #Draco Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#EchoLisp
EchoLisp
  (lib 'matrix)   (define (mtable i j) (cond ((and (zero? i) (zero? j)) "😅") ((= i 0) j) ((= j 0) i) ((>= j i ) (* i j )) (else " ")))   (array-print (build-array 13 13 mtable))    
Give a code snippet in #EchoLisp Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Haskell
Haskell
-- Some elementary types for Turing Machine data Move = MLeft | MRight | Stay deriving (Show, Eq) data Tape a = Tape a [a] [a] data Action state val = Action val Move state deriving (Show)   instance (Show a) => Show (Tape a) where show (Tape x lts rts) = concat $ left ++ [hd] ++ right where...
Give a code snippet in #Haskell One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machi...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Haskell
Haskell
-- We use a couple of GHC extensions to make the program cooler. They let us -- use / as an operator and 13 as a literal at the type level. (The library -- also provides the fancy Zahlen (ℤ) symbol as a synonym for Integer.)   {-# Language DataKinds #-} {-# Language TypeOperators #-}   import Data.Modular   f :: ℤ/13...
Give a code snippet in #Haskell Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus,...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Swift
Swift
let double = 1.0 as Double // Double precision let float = 1.0 as Float // Single precision let scientific = 1.0E-12   // Swift does not feature type coercion for explicit type declaration let sum = double + float // Error   let div = 1.1 / 2 // Double let div1 = 1 / 2 // 0
Give a code snippet in #Swift Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Gambas
Gambas
'This code will create a GUI Form to display the result   hGridView As GridView 'The display is on a GridView iCol As Integer = 38 'Column start position iRow As Integer = 30 'Row ...
Give a code snippet in #Gambas Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each ot...
#Nim
Nim
import math, strformat, strutils   const Lim = 1_000_035   type Group {.pure.} = enum # "ord" gives the number of terms. Unsexy = (1, "unsexy primes") Pairs = (2, "sexy prime pairs") Triplets = (3, "sexy prime triplets") Quadruplets = (4, "sexy prime quadruplets") Quintuplets = (5, "sexy prime quintupl...
Give a code snippet in #Nim This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime num...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Python
Python
  #lang racket (require racket/draw)   (define (draw-line dc p q) (match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)]))   (define (draw-lines dc ps) (void (for/fold ([p0 (first ps)]) ([p (rest ps)]) (draw-line dc p0 p) p)))   (define (int t p q) (define ((int1 t) x0 x1) (+ (* (- 1 t) ...
Give a code snippet in #Python Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict;   my $template = shift; open my $IN, '<', $template or die $!; my $story = do { local $/ ; <$IN> };   my %blanks; undef $blanks{$_} for $story =~ m/<(.*?)>/g;   for my $blank (sort keys %blanks) { print "$blank: "; chomp (my $replacement = <>); $blanks{$blank} = $re...
Give a code snippet in #Perl This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game wh...
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.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func real Floor(X); \Truncate X toward - infinity real X; return float(fix(X-0.5));   func PerfectSq(N); \Return 'true' if N is a perfect square int N; return sqrt(N)*sqrt(N) = N;   int N, M, M0; [for N:= 1 to 22 do [IntOu...
Give a code snippet in #XPL0 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/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#Ruby
Ruby
require 'priority_queue'   def huffman_encoding(str) char_count = Hash.new(0) str.each_char {|c| char_count[c] += 1}   pq = CPriorityQueue.new # chars with fewest count have highest priority char_count.each {|char, count| pq.push(char, count)}   while pq.length > 1 key1, prio1 = pq.delete_min key2, ...
Give a code snippet in #Ruby Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you co...
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program fcttime.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ N1, 1000000 @ loop number .equ NBMEASURE, 10 @ measure number   /*********************************/ /* Initialized ...
Give a code snippet in #ARM_Assembly Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time ...
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...
#Ursala
Ursala
#import std #import nat   happy = ==1+ ^== sum:-0+ product*iip+ %np*hiNCNCS+ %nP   first "p" = ~&i&& iota; ~&lrtPX/&; leql@lrPrX->lrx ^|\~& ^/successor@l ^|T\~& "p"&& ~&iNC   #cast %nL   main = (first happy) 8
Give a code snippet in #Ursala 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...
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
#mIRC_Scripting_Language
mIRC Scripting Language
alias goodbyegui { dialog -m Goodbye Goodbye }   dialog Goodbye { title "Goodbye, World!" size -1 -1 80 20 option dbu text "Goodbye, World!", 1, 20 6 41 7 }
Give a code snippet in #mIRC_Scripting_Language 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/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Ruby
Ruby
watches = [ "First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First" ] watch_ends = [ "00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59" ] words = ["One","Two","Three","Four","Five","Six","Seven","Eight"] sound = "ding!"   loop do time = Time.now if time.sec == 0 a...
Give a code snippet in #Ruby Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave ...
christopher/rosetta-code
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Threading; using System.Windows.Forms;   namespace ForestFire { class Program : Form { private static readonly Random rand = new Random(); private Bitmap img;   public Program(int w, int h, int f, int p) ...
Give a code snippet in #C.23 This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and S...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#C.2B.2B
C++
/* * RossetaCode: Sum to 100, C++, STL, OOP. * Works with: MSC 16.0 (MSVS2010); GCC 5.1 (use -std=c++11 or -std=c++14 etc.). * * Find solutions to the "sum to one hundred" puzzle. */ #include <iostream> #include <iomanip> #include <algorithm> #include <string> #include <set> #include <map>   using namespace std;...
Give a code snippet in #C.2B.2B Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particul...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#JScript.NET
JScript.NET
enum fruits { apple, banana, cherry } enum fruits { apple = 0, banana = 1, cherry = 2 }
Give a code snippet in #JScript.NET Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#UNIX_Shell
UNIX Shell
#!/bin/sh   A=Bell B=Ball   # Traditional test command implementations test for equality and inequality # but do not have a lexical comparison facility if [ $A = $B ] ; then echo 'The strings are equal' fi if [ $A != $B ] ; then echo 'The strings are not equal' fi   # All variables in the shell are strings, so nume...
Give a code snippet in #UNIX_Shell Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#AutoHotkey
AutoHotkey
; Test parameters max := 20, fizz := 3, buzz := 5, baxx := 7   Loop % max { output := "" if (Mod(A_Index, fizz) = 0) output .= "Fizz" if (Mod(A_Index, buzz) = 0) output .= "Buzz" if (Mod(A_Index, baxx) = 0) output .= "Baxx" if (output = "") FileAppend %A_Index%`n, * else FileAppend %output%`n, * }  
Give a code snippet in #AutoHotkey Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated alon...
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: ...
#Ring
Ring
  # Project : Old Russian measure of length   decimals(7) units = ["tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer"]   convs = [0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676,...
Give a code snippet in #Ring 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 r...
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#EDSAC_order_code
EDSAC order code
  [Attempt at Turing machine for Rosetta Code.] [EDSAC program, Initial Orders 2.]   [Library subroutine M3 prints header and is then overwritten.] PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF *!!NR!STEPS@&#..PZ [..PZ marks end of header]   T48K [& (delta) parameter: Turing machine tape.] ...
Give a code snippet in #EDSAC_order_code One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Tur...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#D
D
import std.stdio, std.algorithm;   T a(T)(T answer) { writefln(" # Called function a(%s) -> %s", answer, answer); return answer; }   T b(T)(T answer) { writefln(" # Called function b(%s) -> %s", answer, answer); return answer; }   void main() { foreach (immutable x, immutable y; [fals...
Give a code snippet in #D Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resourc...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Ela
Ela
open list   mmult a b = [ [ sum $ zipWith (*) ar bc \\ bc <- (transpose b) ] \\ ar <- a ]   [[1, 2], [3, 4]] `mmult` [[-3, -8, 3], [-2, 1, 4]]
Give a code snippet in #Ela Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Erlang
Erlang
% Erlang comments begin with "%" and extend to the end of the line.
Give a code snippet in #Erlang Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the...
#Tcl
Tcl
package require Tcl 8.5 # Gödel number generator proc goedel s { set primes { 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 } set n 1 foreach c [split [string toupper $s] ""] { if {![string is alpha $c]} continue set n [expr {$n * [lindex $primes [expr {[scan $c %c] - 65...
Give a code snippet in #Tcl Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rear...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#Nim
Nim
type Node[T] = ref TNode[T]   TNode[T] = object next, prev: Node[T] data: T
Give a code snippet in #Nim Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Crea...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#XLISP
XLISP
(vector-length #("apple" "orange"))
Give a code snippet in #XLISP Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequ...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Scala
Scala
object Eval extends App {   def evalWithX(expr: String, a: Double, b: Double)= {val x = b; eval(expr)} - {val x = a; eval(expr)}   println(evalWithX("Math.exp(x)", 0.0, 1.0))   }
Give a code snippet in #Scala x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#MATLAB_.2F_Octave
MATLAB / Octave
function t = mean_time_of_day(t) c = pi/(12*60*60); for k=1:length(t) a = sscanf(t{k},'%d:%d:%d'); phi(k) = (a(1)*3600+a(2)*60+a(3)); end; d = angle(mean(exp(i*phi*c)))/(2*pi); % days if (d<0) d += 1; t = datestr(d,"HH:MM:SS"); end;
Give a code snippet in #MATLAB_.2F_Octave Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and usin...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#JavaScript_.2B_HTML
JavaScript + HTML
<html> <head> <title>RC: Basic Animation</title> <script type="text/javascript"> function animate(id) { var element = document.getElementById(id); var textNode = element.childNodes[0]; // assuming no other children   var text = textNode.data; var reverse =...
Give a code snippet in #JavaScript_.2B_HTML Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. ...
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#Clojure
Clojure
(defn fix [pairs] (map second pairs))   (defn getvalid [pairs n] (filter (fn [p] (zero? (mod n (first p)))) (sort-by first pairs)))   (defn gfizzbuzz [pairs numbers] (interpose "\n" (map (fn [n] (let [f (getvalid pairs n)] (if (empty? f) ...
Give a code snippet in #Clojure Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along w...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Elena
Elena
public program() { var 四十二 := "♥♦♣♠"; // UTF8 string var строка := "Привет"w; // UTF16 string   console.writeLine:строка; console.writeLine:四十二; }
Give a code snippet in #Elena As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#Raku
Raku
sub MAIN (*@files) { my %norm; do for @files -> $file { %norm.push: $file X=> slurp($file).lc.words; } (my %inv).push: %norm.invert.unique;   while prompt("Search terms: ").words -> @words { for @words -> $word { say "$word => {%inv.{$word.lc}//'(not found)'}"; } ...
Give a code snippet in #Raku An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / ter...
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...
#Mercury
Mercury
:- module query. :- interface.   :- pred query(string::in, string::out) is det.   :- implementation.   query(_, "Hello, world!").   :- pragma foreign_export("C", query(in, out), "query").   :- pragma foreign_decl("C", " #include <string.h> int Query (char * Data, size_t * Length); "). :- pragma foreign_code("C", " int ...
Give a code snippet in #Mercury 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#Picat
Picat
go ?=> member(N,1..10), Perm = 1..N, Rev = Perm.reverse(), Max = 0, while(Perm != Rev) next_permutation(Perm), C = topswops(Perm), if C > Max then Max := C end end, printf("%2d: %2d\n",N,Max), fail, nl. go => true.   topswops([]) = 0 => true. topswops([1]) = 0 => true. topswop...
Give a code snippet in #Picat Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is co...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#UNIX_Shell
UNIX Shell
# Program to determine the smallest positive integer whose square # has a decimal representation ending in the digits 269,696.   # Start with the smallest positive integer of them all let trial_value=1   # Compute the remainder when the square of the current trial value is divided # by 1,000,000.␣ while (( trial_value ...
Give a code snippet in #UNIX_Shell Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic...
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#Swift
Swift
enum HuffmanTree<T> { case Leaf(T) indirect case Node(HuffmanTree<T>, HuffmanTree<T>)   func printCodes(prefix: String) { switch(self) { case let .Leaf(c): print("\(c)\t\(prefix)") case let .Node(l, r): l.printCodes(prefix + "0") r.printCodes(prefix + "1") } } }   func buildTre...
Give a code snippet in #Swift Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you c...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#PL.2FI
PL/I
  declare in file, out file;   open file (in) title ('/INPUT.TXT,type(text),recsize(100)') input; open file (out) title ('/OUTPUT.TXT,type(text),recsize(100') output; do forever; get file (in) edit (line) (L); put file (out) edit (line) (A); end;  
Give a code snippet in #PL.2FI File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#RLaB
RLaB
  >> x = sqrt(-1) 0 + 1i >> y = 10 + 5i 10 + 5i >> z = 5*x-y -10 + 0i >> isreal(z) 1  
Give a code snippet in #RLaB 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 {\displaysty...
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Perl
Perl
  use strict; use warnings; use Tk; use Math::Trig qw/:pi/;   my $root = new MainWindow( -title => 'Pendulum Animation' ); my $canvas = $root->Canvas(-width => 320, -height => 200); my $after_id;   for ($canvas) { $_->createLine( 0, 25, 320, 25, -tags => [qw/plate/], -width => 2, -fill => 'grey50' ); $_->create...
Give a code snippet in #Perl One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and an...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Apex
Apex
  System.debug ('I will execute'); // This comment is ignored. /* I am a large comment, completely ignored as well. */  
Give a code snippet in #Apex Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#CLU
CLU
christmas = cluster is carol rep = null   own ordinals: array[string] := array[string]$[ "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" ]   own gifts: array[string] := array[string]$[ "A partridge in a ...
Give a code snippet in #CLU Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations:...
christopher/rosetta-code
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#REXX
REXX
/*REXX program finds and shows lists (or counts) attractive numbers up to a specified N.*/ parse arg N . /*get optional argument from the C.L. */ if N=='' | N=="," then N= 120 /*Not specified? Then use the default.*/ cnt= N<0 ...
Give a code snippet in #REXX A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Sh...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#SPAD
SPAD
  blocks:List Tuple Symbol:= _ [(B,O),(X,K),(D,Q),(C,P),(N,A),(G,T),(R,E),(T,G),(Q,D),(F,S), _ (J,W),(H,U),(V,I),(A,N),(O,B),(E,R),(F,S),(L,Y),(P,C),(Z,M)]     findComb(l:List List NNI):List List NNI == #l=0 => [] #l=1 => [[s] for s in first l] r:List List NNI:=[] for y in findComb(rest l) repeat r:=co...
Give a code snippet in #SPAD ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet...
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...
#Rust
Rust
use std::collections::HashSet;   fn main() { let a: HashSet<_> = ["John", "Bob", "Mary", "Serena"] .iter() .collect(); let b = ["Jim", "Mary", "John", "Bob"] .iter() .collect();   let diff = a.symmetric_difference(&b); println!("{:?}", diff); }  
Give a code snippet in #Rust 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 ) {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#VBScript
VBScript
  Dim sieve() If WScript.Arguments.Count>=1 Then n = WScript.Arguments(0) Else n = 99 End If ReDim sieve(n) For i = 1 To n sieve(i) = True Next For i = 2 To n If sieve(i) Then For j = i * 2 To n Step i sieve(j) = False Next ...
Give a code snippet in #VBScript This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Tcl
Tcl
proc froots {lambda {start -3} {end 3} {step 0.0001}} { set res {} set lastsign [sgn [apply $lambda $start]] for {set x $start} {$x <= $end} {set x [expr {$x + $step}]} { set sign [sgn [apply $lambda $x]] if {$sign != $lastsign} { lappend res [format ~%.11f $x] } ...
Give a code snippet in #Tcl Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
christopher/rosetta-code
http://rosettacode.org/wiki/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. ...
#Perl
Perl
for(my $x = 1; $x <= 5; $x++) { for(my $y = 1; $y <= $x; $y++) { print "*"; } print "\n"; }
Give a code snippet in #Perl “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 structur...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Class FASTA_MACHINE { Events "GetBuffer", "header", "DataLine", "Quit" Public: Module Run { Const lineFeed$=chr$(13)+chr$(10) Const WhiteSpace$=" "+chr$(9)+chrcode$(160) Def long state=1, idstate=1 ...
Give a code snippet in #M2000_Interpreter In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such...
christopher/rosetta-code