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/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#Ring
Ring
  Load "guilib.ring"   MyApp = New qApp { num = 0 win1 = new qWidget() { setwindowtitle("Hello World") setGeometry(100,100,370,250)   btn1 = new qpushbutton(win1) { setGeometry(50,200,100,30) settext("Increment") ...
Give a code snippet in #Ring In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI compon...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#C.2B.2B
C++
#include <iostream> #include <random> #include <vector>   int main( ) { std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ; std::random_device seed ; // generator std::mt19937 engine( seed( ) ) ; // number distribution std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1...
Give a code snippet in #C.2B.2B Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Prolog
Prolog
look_and_say(L) :- maplist(write, L), nl, encode(L, L1), look_and_say(L1).   % This code is almost identical to the code of "run-length-encoding" encode(In, Out) :- packList(In, R1), append(R1,Out).     % use of library clpfd allows packList(?In, ?Out) to works % in both ways In --> Out and In <-- Out.   :- use_m...
Give a code snippet in #Prolog The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequenc...
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
#Phix
Phix
procedure print_roots(integer f, atom start, stop, step) -- -- Print approximate roots of f between x=start and x=stop, using -- sign changes as an indicator that a root has been encountered. -- atom x = start, y = 0 puts(1,"-----\n") while x<=stop do atom last_y = y y = f...
Give a code snippet in #Phix 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/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Maple
Maple
  with(ArrayTools):   spiralArray := proc(size::integer) local M, sideLength, count, i, j: M := Matrix(size): count := 0: sideLength := size: for i from 1 to ceil(sideLength / 2) do for j from 1 to sideLength do M[i,i + j - 1] := count++: end: for j from 1 to sideLength - 1 do M[i + j, sideLength + i -...
Give a code snippet in #Maple Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Python
Python
import pygame, math   pygame.init() window = pygame.display.set_mode((600, 600)) pygame.display.set_caption("Fractal Tree") screen = pygame.display.get_surface()   def drawTree(x1, y1, angle, depth): fork_angle = 20 base_len = 10.0 if depth > 0: x2 = x1 + int(math.cos(math.radians(angle)) * depth * ...
Give a code snippet in #Python Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Arturo
Arturo
tau: function [x] -> size factors x   found: 0 i:1 while [found<100][ if 0 = i % tau i [ prints pad to :string i 5 found: found + 1 if 0 = found % 10 -> print "" ] i: i + 1 ]
Give a code snippet in #Arturo A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau functio...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   REAL sum,sum2 INT count   PROC Calc(REAL POINTER x,sd) REAL tmp1,tmp2,tmp3   RealAdd(sum,x,tmp1)  ;tmp1=sum+x RealAssign(tmp1,sum)  ;sum=sum+x RealMult(x,x,tmp1)  ;tmp1=x*x RealAdd(sum2,tmp1,tmp2)  ;tmp2=sum2+x*x RealAssign(tmp2,sum2)  ;sum2=sum2+x*x count==+...
Give a code snippet in #Action.21 Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the f...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#PHP
PHP
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
Give a code snippet in #PHP A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed ...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Pop11
Pop11
;;; field of length 12, 3 digits after decimal place format_print('~12,3,0,`*,`0F', [1299.19]); ;;; prints "00001299.190" format_print('~12,3,0,`*,`0F', [100000000000000000]); ;;; Since the number does not fit into the field prints "************" ;;; that is stars instead of the number format_print('~12,3,0,`*,`0F', [-...
Give a code snippet in #Pop11 Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Erlang
Erlang
%% Implemented by Arjun Sunel -module(even_odd). -export([main/0]).   main()-> test(8).   test(N) -> if (N rem 2)==1 -> io:format("odd\n"); true -> io:format("even\n") end.  
Give a code snippet in #Erlang Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Div...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Burlesque
Burlesque
2.%
Give a code snippet in #Burlesque Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. ...
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...
#PicoLisp
PicoLisp
(de operator (Op) (member Op '("\^" "*" "/" "+" "-")) )   (de leftAssoc (Op) (member Op '("*" "/" "+" "-")) )   (de precedence (Op) (case Op ("\^" 4) (("*" "/") 3) (("+" "-") 2) ) )   (de shuntingYard (Str) (make (let (Fmt (-7 -30 -4) Stack) (tab Fmt "Token" "Output" "Stack...
Give a code snippet in #PicoLisp 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 repre...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Aime
Aime
void f1(integer a) { if (a) { exit(1); } }   integer main(void) { f1(3);   return 0; }
Give a code snippet in #Aime Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#TXR
TXR
(let* ((server (first (getaddrinfo "localhost" 256))) (sock (open-socket server.family sock-stream))) (sock-connect sock server) (put-string "hello socket world"))
Give a code snippet in #TXR For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and computer science, the Levenshtein ...
#Groovy
Groovy
def distance(String str1, String str2) { def dist = new int[str1.size() + 1][str2.size() + 1] (0..str1.size()).each { dist[it][0] = it } (0..str2.size()).each { dist[0][it] = it }   (1..str1.size()).each { i -> (1..str2.size()).each { j -> dist[i][j] = [dist[i - 1][j] + 1, dist[i][j ...
Give a code snippet in #Groovy This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and co...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic 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. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#PARI.2FGP
PARI/GP
roots(a,b,c)=polrootsreal(Pol([a,b,c]))
Give a code snippet in #PARI.2FGP This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Y...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Arturo
Arturo
insertionSort: function [items][ arr: new items loop 1..(size items)-1 'i [ value: arr\[i] j: i - 1   while [and? -> j >= 0 -> value < arr\[j]] [ arr\[j+1]: arr\[j] j: j - 1 ] arr\[j+1]: value ] return arr ]   ...
Give a code snippet in #Arturo Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#AutoIt
AutoIt
$voice = ObjCreate("SAPI.SpVoice") $voice.Speak("This is an example of speech synthesis.")
Give a code snippet in #AutoIt Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#PicoLisp
PicoLisp
(de accumulator (Sum) (curry (Sum) (N) (inc 'Sum N) ) )   (def 'a (accumulator 7)) (a 1) # Output: -> 8 (a 2) # Output: -> 10 (a -5) # Output: -> 5
Give a code snippet in #PicoLisp A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values ...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two p...
#Kotlin
Kotlin
// version 1.1.2   typealias Point = Pair<Double, Double>   fun distance(p1: Point, p2: Point) = Math.hypot(p1.first- p2.first, p1.second - p2.second)   fun bruteForceClosestPair(p: List<Point>): Pair<Double, Pair<Point, Point>> { val n = p.size if (n < 2) throw IllegalArgumentException("Must be at least two po...
Give a code snippet in #Kotlin This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#jq
jq
## Compute (n - 1)! mod m. def facmod($n; $m): reduce range(2; $n+1) as $k (1; (. * $k) % $m);   def isPrime: .>1 and (facmod(. - 1; .) + 1) % . == 0;   "Prime numbers between 2 and 100:", [range(2;101) | select (isPrime)],   # Notice that `infinite` can be used as the second argument of `range`: "First 10 primes aft...
Give a code snippet in #jq Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wik...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Rascal
Rascal
Type Name = Exp;
Give a code snippet in #Rascal Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Vlang
Vlang
fn main() { for i := 10; i >= 0; i-- { print('$i ') } }
Give a code snippet in #Vlang Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increm...
christopher/rosetta-code
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#F.23
F#
  // PartionP: Nigel Galloway. April 12th., 2021 let pP g=let rec fN i g e l=seq{yield(l,e+i);yield(-l,e+i+g);yield! fN(i+1)(g+2)(e+i+g)(-l)} let N,G=Array.create(g+1) 1I,seq{yield (1I,1);yield! fN 1 3 1 1I}|>Seq.takeWhile(fun(_,n)->n<=g)|>List.ofSeq seq{2..g}|>Seq.iter(fun p->N.[p]<-G|>List.takeWhile...
Give a code snippet in #F.23 The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#min
min
randomize (19 random puts 10 ==) (19 random puts!) () () linrec
Give a code snippet in #min Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If...
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Racket
Racket
#lang racket   (with-input-from-file "data/large-earthquake.txt" (λ () (for ((s (in-port read-line)) #:when (> (string->number (third (string-split s))) 6)) (displayln s))))
Give a code snippet in #Racket Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_convolution
Image convolution
One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square K k l {\displaystyle K_{kl}} , where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel width. The filter determine...
#BBC_BASIC
BBC BASIC
Width% = 200 Height% = 200   DIM out&(Width%-1, Height%-1, 2)   VDU 23,22,Width%;Height%;8,16,16,128 *DISPLAY Lena OFF   DIM filter%(2, 2) filter%() = -1, -1, -1, -1, 12, -1, -1, -1, -1   REM Do the convolution: FOR Y% = 1 TO Height%-2 FOR X% = 1 TO Wi...
Give a code snippet in #BBC_BASIC One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square K k l {\displaystyle K_{kl}} , where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#XPL0
XPL0
include c:\cxpl\codes; int A, B; [A:= IntIn(0); B:= IntIn(0); IntOut(0, A+B); CrLf(0); IntOut(0, A-B); CrLf(0); IntOut(0, A*B); CrLf(0); IntOut(0, A/B); CrLf(0); \truncates toward zero IntOut(0, rem(0)); CrLf(0); \remainder's sign matches first operand (A) ]
Give a code snippet in #XPL0 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Fortran
Fortran
program NthRootTest implicit none   print *, nthroot(10, 7131.5**10) print *, nthroot(5, 34.0)   contains   function nthroot(n, A, p) real :: nthroot integer, intent(in) :: n real, intent(in) :: A real, intent(in), optional :: p   real :: rp, x(2)   if ( A < 0 ) then ...
Give a code snippet in #Fortran Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Erlang
Erlang
-module(forward_difference). -export([difference/1, difference/2]).   -export([task/0]). -define(TEST_DATA,[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]).   difference([X|Xs]) -> {Result,_} = lists:mapfoldl(fun (N_2,N_1) -> {N_2 - N_1, N_2} end, X, Xs), Result.   difference([],_) -> []; difference(List,0) -> List; di...
Give a code snippet in #Erlang 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Maple
Maple
# Static Method( obj, other, arg );
Give a code snippet in #Maple In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Kotlin
Kotlin
// version 1.1.0 // compiled with flag -Xcoroutines=enable to suppress 'experimental' warning   import kotlin.coroutines.experimental.buildSequence   fun generatePowers(m: Int) = buildSequence { var n = 0 val mm = m.toDouble() while (true) yield(Math.pow((n++).toDouble(), mm).toLong()) }...
Give a code snippet in #Kotlin A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#UNIX_Shell
UNIX Shell
od -An -N 4 -t u4 /dev/urandom
Give a code snippet in #UNIX_Shell Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity...
#ALGOL_W
ALGOL W
print 2 + 3 * 5 ; same as 2 + (3 * 5) print 3 * 5 + 2 ; same as 3 * (5 + 2)
Give a code snippet in #ALGOL_W This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#BASIC
BASIC
sum = 0 FOR I = LBOUND(a) TO UBOUND(a) sum = sum + a(I) ^ 2 NEXT I PRINT "The sum of squares is: " + sum
Give a code snippet in #BASIC Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
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...
#Potion
Potion
is_num = (s): x = s ord(0) if (x >= "0"ord && x <= "9"ord): true. else: false. .   nums = (s): res = () 0 to (s length, (b): c = s(b) if (is_num(c)): res push(c). .) res.   try = 1 while (true): r = rand string digits = (r(0),r(1),r(2),r(3)) "\nMy next four digits: " print digits j...
Give a code snippet in #Potion 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 d...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Arturo
Arturo
factorial: function [n]-> product 1..n binomial: function [x,y]-> (factorial x) / (factorial y) * factorial x-y   print binomial 5 3
Give a code snippet in #Arturo This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n −...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Julia
Julia
julia> sum(k -> 1/k^2, 1:1000) 1.643934566681559   julia> pi^2/6 1.6449340668482264  
Give a code snippet in #Julia Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Swift
Swift
import Foundation   let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close()   if let bytes = success { ...
Give a code snippet in #Swift Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out"...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#PARI.2FGP
PARI/GP
str = externstr("hostname")[1]; str = externstr("uname -n")[1];
Give a code snippet in #PARI.2FGP Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Unicode_output
Terminal control/Unicode output
The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note that it is permissible to use sys...
#PicoLisp
PicoLisp
(if (sub? "UTF-8" (or (sys "LC_ALL") (sys "LC_CTYPE") (sys "LANG"))) (prinl (char (hex "25b3"))) (quit "UTF-8 capable terminal required") )
Give a code snippet in #PicoLisp The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note...
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...
#Kotlin
Kotlin
// version 1.1.2   fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true }   fun ...
Give a code snippet in #Kotlin 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 woul...
christopher/rosetta-code
http://rosettacode.org/wiki/Kronecker_product_based_fractals
Kronecker product based fractals
This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the matrix   (filled with 0/1)   we ...
#11l
11l
F kroneckerProduct(a, b) V m = a.len V n = a[0].len V p = b.len V q = b[0].len V result = [[0] * (n * q)] * (m * p) L(i) 0 .< m L(j) 0 .< n L(k) 0 .< p L(l) 0 .< q result[i * p + k][j * q + l] = a[i][j] * b[k][l] R result   F kroneckerPower(m, n) V resul...
Give a code snippet in #11l This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the mat...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Brainf.2A.2A.2A
Brainf***
>++++++++++>>>+>+[>>>+[-[<<<<<[+<<<<<]>>[[-]>[<<+>+>-]<[>+<-]<[>+<-[>+<-[> +<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>>>>+>+<<<<<<-[>+<-]]]]]]]]]]]>[<+>- ]+>>>>>]<<<<<[<<<<<]>>>>>>>[>>>>>]++[-<<<<<]>>>>>>-]+>>>>>]<[>++<-]<<<<[<[ >+<-]<<<<]>>[->[-]++++++[<++++++++>-]>>>>]<<<<<[<[>+>+<<-]>.<<<<<]>.>>>>]
Give a code snippet in #Brainf.2A.2A.2A Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factor...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Vedit_macro_language
Vedit macro language
#90 = Time_Tick // seed for random number generator #91 = 3 // random numbers in range 0 to 2 #1 = 0 // wins for "always stay" strategy #2 = 0 // wins for "always switch" strategy for (#10 = 0; #10 < 10000; #10++) { // 10,000 iterations Call("RANDOM") #3 = Return_Value // #3 = winning door Cal...
Give a code snippet in #Vedit_macro_language Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 ...
#PHP
PHP
<?php   function counting_sort(&$arr, $min, $max) { $count = array(); for($i = $min; $i <= $max; $i++) { $count[$i] = 0; }   foreach($arr as $number) { $count[$number]++; } $z = 0; for($i = $min; $i <= $max; $i++) { while( $count[$i]-- > 0 ) { $arr[$z++] = $i; } } }
Give a code snippet in #PHP Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#HolyC
HolyC
U8 n, *g; U8 min = 1, max = 100;   n = min + RandU16 % max;   Print("Guess the number between %d and %d: ", min, max);   while(1) { g = GetStr;   if (Str2I64(g) == n) { Print("You guessed correctly!\n"); break; }   if (Str2I64(g) < n) Print("Your guess was too low.\nTry again: "); if (Str2I64(g) >...
Give a code snippet in #HolyC Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: hi...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Nim
Nim
type Luminance* = uint8 Index* = int   Color* = tuple r, g, b: Luminance   Image* = ref object w*, h*: Index pixels*: seq[Color]   Point* = tuple x, y: Index   proc color*(r, g, b: SomeInteger): Color = ## Build a color value from R, G and B values. result.r = r.uint8 result.g = g.uint8 ...
Give a code snippet in #Nim Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB colo...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Ela
Ela
open monad io number string   :::IO   take_numbers 0 xs = do return $ iter xs where f x = sqrt (toSingle x) + 5.0 * (x ** 3.0) p x = x < 400.0 iter [] = return () iter (x::xs) | p res = do putStrLn (format "f({0}) = {1}" x res) iter xs | else ...
Give a code snippet in #Ela The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, g...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Lua
Lua
math.exp(1) math.pi math.sqrt(x) math.log(x) math.log10(x) math.exp(x) math.abs(x) math.floor(x) math.ceil(x) x^y
Give a code snippet in #Lua Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "mag...
christopher/rosetta-code
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encod...
#Ruby
Ruby
open("outfile.dat", "w") do |out_f| open("infile.dat") do |in_f| while record = in_f.read(80) out_f << record.reverse end end end # both files automatically closed  
Give a code snippet in #Ruby Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Slate
Slate
'Hello, world!' length.
Give a code snippet in #Slate Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme cont...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Prolog
Prolog
priority-queue :- TL0 = [3-'Clear drains', 4-'Feed cat'],   % we can create a priority queue from a list list_to_heap(TL0, Heap0),   % alternatively we can start from an empty queue % get from empty_heap/1.   % now we add the other elements add_to_heap(Heap0, 5, 'Make tea', Heap1), add_to_heap(...
Give a code snippet in #Prolog A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in pri...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Red
Red
Red [ red-version: 0.6.4 description: "Find the sum and product of an array of numbers." ]   product: function [ "Returns the product of all values in a block." values [any-list! vector!] ][ result: 1 foreach value values [result: result * value] result ]   a: [1 2 3 4 5 6 7 8 9 10] print a ...
Give a code snippet in #Red Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer 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 |...
#360_Assembly
360 Assembly
INTCOMP PROLOG * Reg1=Addr(Addr(argA),Addr(argB)) L 2,0(1) Reg2=Addr(argA) L 3,4(1) Reg3=Addr(argB) L 4,0(2) Reg4=argA L 5,0(3) Reg5=argA ST 4,A Store R4 in A ST 5,B St...
Give a code snippet in #360_Assembly 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 Oper...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Printer
Colour pinstripe/Printer
The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence...
#Phix
Phix
(load "@lib/ps.l")   # Using circular lists for an endless supply of colors # (black red green blue magenta cyan yellow white) (setq Red (0 100 0 0 100 0 100 100 .) Green (0 0 100 0 0 100 100 100 .) Blue (0 0 0 100 100 100 0 100 .) )   (c...
Give a code snippet in #Phix The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#APL
APL
2|28 0 2|37 1
Give a code snippet in #APL Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Go
Go
package main   import "fmt"   func main() { var a, b int fmt.Print("enter two integers: ") fmt.Scanln(&a, &b) fmt.Printf("%d + %d = %d\n", a, b, a+b) fmt.Printf("%d - %d = %d\n", a, b, a-b) fmt.Printf("%d * %d = %d\n", a, b, a*b) fmt.Printf("%d / %d = %d\n", a, b, a/b) // truncates towards ...
Give a code snippet in #Go 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 Con...
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...
#Lasso
Lasso
local(x = 'Hello') local(y = #x + ', World!') #x // Hello #y // Hello, World!
Give a code snippet in #Lasso 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 lit...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Logtalk
Logtalk
  :- object(constants_and_functions).   :- public(show/0). show :- write('e = '), E is e, write(E), nl, write('pi = '), PI is pi, write(PI), nl, write('sqrt(2) = '), SQRT is sqrt(2), write(SQRT), nl, % only base e logorithm is avaialable as a standard built-in function wr...
Give a code snippet in #Logtalk Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Factor
Factor
"alphaBETA" >lower  ! "alphabeta" "alphaBETA" >upper  ! "ALPHABETA" "alphaBETA" >title  ! "Alphabeta" "ß" >case-fold  ! "ss"
Give a code snippet in #Factor Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not ...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Perl
Perl
# These variables are all different $dog='Benjamin'; $Dog='Samba'; $DOG='Bernie'; print "The three dogs are named $dog, $Dog, and $DOG \n"
Give a code snippet in #Perl Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Sam...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Racket
Racket
#lang racket   (define (digsum n) (for/sum ([c (number->string n)]) (string->number [string c])))   (define harshads (stream-filter (λ (n) (= (modulo n (digsum n)) 0)) (in-naturals 1)))   ; First 20 harshad numbers (displayln (for/list ([i 20]) (stream-ref harshads i)))   ; First harshad greater than 1000 (displa...
Give a code snippet in #Racket The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#BASH_.28feat._sed_.26_tr.29
BASH (feat. sed & tr)
  #!/bin/bash   # Basic principle: # # # x -> dxd d -> dd s -> s # xsx dd s # # In the end all 'd' and 's' are removed. # 0x7F800000 function rec(){ if [ $1 == 0 ] then echo "x" else rec $[ $1 - 1 ] | while read line ; do echo "$line" | sed "s/d/dd/g" | se...
Give a code snippet in #BASH_.28feat._sed_.26_tr.29 Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Julia
Julia
# v0.6.0   rad = π / 4 deg = 45.0   @show rad deg @show sin(rad) sin(deg2rad(deg)) @show cos(rad) cos(deg2rad(deg)) @show tan(rad) tan(deg2rad(deg)) @show asin(sin(rad)) asin(sin(rad)) |> rad2deg @show acos(cos(rad)) acos(cos(rad)) |> rad2deg @show atan(tan(rad)) atan(tan(rad)) |> rad2deg
Give a code snippet in #Julia Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evalu...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#Rust
Rust
extern crate rand;   use rand::{Rng, thread_rng};   fn one_of_n<R: Rng>(rng: &mut R, n: usize) -> usize { (1..n).fold(0, |keep, cand| { // Note that this will break if n is larger than u32::MAX if rng.gen_weighted_bool(cand as u32 + 1) { cand } else { keep } ...
Give a code snippet in #Rust A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Oz
Oz
declare fun {PrintFloat X Prec} {Property.put 'print.floatPrecision' Prec} S = {Float.toString X} in {Append for I in 1..Prec-{Length S}+1 collect:C do {C &0} end S} end in {System.showInfo {PrintFloat 7.125 8}}
Give a code snippet in #Oz Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Ada
Ada
with Ada.Directories, Ada.Direct_IO, Ada.Text_IO;   procedure Whole_File is   File_Name : String  := "whole_file.adb"; File_Size : Natural := Natural (Ada.Directories.Size (File_Name));   subtype File_String is String (1 .. File_Size); package File_String_IO is new Ada.Direct_IO (File_String); ...
Give a code snippet in #Ada Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished increme...
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...
#Tcl
Tcl
# Modify the List class to add the iterator methods oo::define List { method foreach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node next]} { set v [$node value] uplevel 1 $script } } method revforeach {varName script...
Give a code snippet in #Tcl 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 Rem...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Retro
Retro
here "HOME" getEnv here puts
Give a code snippet in #Retro Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#PicoLisp
PicoLisp
(scl 1)   (de mapRange (Val A1 A2 B1 B2) (+ B1 (*/ (- Val A1) (- B2 B1) (- A2 A1))) )     (for Val (range 0 10.0 1.0) (prinl (format (mapRange Val 0 10.0 -1.0 0) *Scl) ) )
Give a code snippet in #PicoLisp Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearl...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Racket
Racket
  #lang racket (require (planet neil/charterm:3:0)) (with-charterm (void (charterm-clear-screen)))  
Give a code snippet in #Racket Task Clear the terminal window.
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Neko
Neko
/** Read a file line by line, in Neko <doc><pre>Tectonics: nekoc readfile.neko neko readfile [filename]</pre></doc> */     var stdin = $loader.loadprim("std@file_stdin", 0)() var file_open = $loader.loadprim("std@file_open", 2) var file_read_char = $loader.loadprim("std@file_read_char", 1)   /* Read a line from...
Give a code snippet in #Neko Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
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
#MontiLang
MontiLang
|Hello, World!| PRINT .
Give a code snippet in #MontiLang 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 err...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Nemerle
Nemerle
using System; using System.Console;   module Fib { Fib(n : long) : long { def fib(m : long) { |0 => 1 |1 => 1 |_ => fib(m - 1) + fib(m - 2) }   match(n) { |n when (n < 0) => throw ArgumentException("Fib() not defined on nega...
Give a code snippet in #Nemerle While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwa...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#EchoLisp
EchoLisp
  (define-syntax-rule (string-copy s) (string-append s)) ;; copy = append nothing → #syntax:string-copy (define s "abc") (define t (string-copy s)) t → "abc" (eq? s t) → #t ;; same reference, same object  
Give a code snippet in #EchoLisp This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Ruby
Ruby
# Sample classes for reflection class Super CLASSNAME = 'super'   def initialize(name) @name = name def self.superOwn 'super owned' end end   def to_s "Super(#{@name})" end   def doSup 'did super stuff' end   def self.superClassStuff 'did super class stuff' end   protec...
Give a code snippet in #Ruby Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Scala
Scala
def soundex(s:String)={ var code=s.head.toUpper.toString var previous=getCode(code.head) for(ch <- s.drop(1); current=getCode(ch.toUpper)){ if (!current.isEmpty && current!=previous) code+=current previous=current } code+="0000" code.slice(0,4) }   def getCode(c:Char)={ val cod...
Give a code snippet in #Scala Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There i...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Picat
Picat
go => S1 = "1", foreach(_ in 1..11) println(S1), S1 := runs(S1) end, println(S1), nl.   runs(X) = V => S = "", Last = X[1], C = 1, foreach(I in 2..X.length) if X[I] == Last then C := C + 1 else S := S ++ C.to_string() ++ [X[I-1]], C := 1, Last...
Give a code snippet in #Picat The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#PL.2FI
PL/I
/* sum the first 1000 terms of the series 1/n**2. */ s = 0;   do i = 1000 to 1 by -1; s = s + 1/float(i**2); end;   put skip list (s);
Give a code snippet in #PL.2FI Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Home_primes
Home primes
This page uses content from Wikipedia. The original article was at Home 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 number theory, the home prime HP(n) of an integer n greater than 1 is...
#Go
Go
package main   import ( "fmt" "math/big" "rcu" "sort" )   var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2) var three = big.NewInt(3) var four = big.NewInt(4) var five = big.NewInt(5) var six = big.NewInt(6)   // simple wheel based prime factors routine for BigInt func primeFactors...
Give a code snippet in #Go This page uses content from Wikipedia. The original article was at Home 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 number theory, the home prime HP(n) of an...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings;   procedure Test_C_Interface is function strdup (s1 : Char_Array) return Chars_Ptr; pragma Import (C, strdup, "_strdup");   S1 : constant String := "Hello World!"; ...
Give a code snippet in #Ada Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
Find if a point is within a triangle
Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the algorithm you chose works. Re...
#FreeBASIC
FreeBASIC
  type p2d x as double 'define a two-dimensional point y as double end type   function in_tri( A as p2d, B as p2d, C as p2d, P as p2d ) as boolean 'uses barycentric coordinates to determine if point P is inside 'the triangle defined by points A, B, C dim as double AreaD = (-B.y*C.x + A.y*(-B.x + C...
Give a code snippet in #FreeBASIC Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#PureBasic
PureBasic
Procedure.i cntDiv(n.i) Define.i i, count If n < 2 : ProcedureReturn 1 : EndIf count = 2 : i = 2 While i <= n / 2 If n % i = 0 : count + 1 : EndIf i + 1 Wend ProcedureReturn count EndProcedure   ; - - - MAIN - - - Define.i n = 1, d, maxDiv = 0, count = 0 If OpenConsole("") PrintN("The...
Give a code snippet in #PureBasic The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#PureBasic
PureBasic
Global mutex = CreateMutex()   Procedure Printer(*str) LockMutex(mutex) PrintN( PeekS(*str) ) UnlockMutex(mutex) EndProcedure   If OpenConsole() LockMutex(mutex) thread1 = CreateThread(@Printer(), @"Enjoy") thread2 = CreateThread(@Printer(), @"Rosetta") thread3 = CreateThread(@Printer(), @"Code") UnlockMutex(mu...
Give a code snippet in #PureBasic Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in yo...
christopher/rosetta-code
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function Turn(base As Integer, n As Integer) As Integer Dim sum = 0 While n <> 0 Dim re = n Mod base n \= base sum += re End While Return sum Mod base End Function   Sub Fairshare(base As Integer, count As Integer) ...
Give a code snippet in #Visual_Basic_.NET The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Rust
Rust
use std::env;   fn main() { let mut args = env::args().skip(1).flat_map(|num| num.parse()); let rows = args.next().expect("Expected number of rows as first argument"); let cols = args.next().expect("Expected number of columns as second argument");   assert_ne!(rows, 0, "rows were zero"); assert_ne!(...
Give a code snippet in #Rust Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make do fizzbuzz end   fizzbuzz --Numbers up to 100, prints "Fizz" instead of multiples of 3, and "Buzz" for multiples of 5. --For multiples of both 3 and 5 prints "FizzBuzz". do across 1 |..| 100 as c loop if c.item \\ 15 = 0 th...
Give a code snippet in #Eiffel Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#Objective-C
Objective-C
  #import <Foundation/Foundation.h>   int main() { @autoreleasepool { NSLog(@"Hello, World!"); } }  
Give a code snippet in #Objective-C 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 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Fortran
Fortran
OPEN (F,FILE="SomeFileName.txt",STATUS="REPLACE") WRITE (F,*) "Whatever you like." WRITE (F) BIGARRAY
Give a code snippet in #Fortran Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#Prolog
Prolog
  :- initialization(main). main :- clause(less_than(1,2),B),writeln(B). less_than(A,B) :- A<B.    
Give a code snippet in #Prolog Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" m...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked ...
#D
D
struct SLinkedNode(T) { T data; typeof(this)* next; }   void main() { import std.stdio;   alias N = SLinkedNode!int; auto lh = new N(1, new N(2, new N(3, new N(4))));   for (auto p = lh; p; p = p.next) write(p.data, " "); writeln(); }
Give a code snippet in #D Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition,...
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 ...
#Phixmonti
Phixmonti
def multiply * enddef
Give a code snippet in #Phixmonti 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 distr...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#Forth
Forth
include lib/choose.4th \ target string s" METHINKS IT IS LIKE A WEASEL" sconstant target   27 constant /charset \ size of characterset 29 constant /target \ size of target string 32 constant #copies \ number of offspring   /t...
Give a code snippet in #Forth Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Fortran
Fortran
! Standard Fortran, should work with any modern compiler (tested gfortran 9) ! and ANSI supporting terminal (tested Linux, various terminals). program coloured_terminal_text use, intrinsic :: iso_fortran_env, only: ERROR_UNIT implicit none   ! Some parameters for our ANSI escape codes character(*), parameter ::...
Give a code snippet in #Fortran Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How t...
christopher/rosetta-code
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-digit law, refers to the freque...
#OCaml
OCaml
  open Num   let fib = let rec fib_aux f0 f1 = function | 0 -> f0 | 1 -> f1 | n -> fib_aux f1 (f1 +/ f0) (n - 1) in fib_aux (num_of_int 0) (num_of_int 1) ;;   let create_fibo_string = function n -> string_of_num (fib n) ;; let rec range i j = if i > j then [] else i :: (range (i + 1) j)   let n_max = ...
Give a code snippet in #OCaml This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_quantization
Color quantization
full color Example: Gimp 16 color Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There...
#PureBasic
PureBasic
  ; ColorQuantization.pb   Structure bestA_ ; table for our histogram nn.i ; 16,32,... rc.i ; red count within (0,1,...,255)/(number of colors) gc.i ; green count within (0,1,...,255)/(number of colors) bc.i ; blue count within (0,1,...,255)/(number of colors) EndStructure   ; these two functions appear to be rather...
Give a code snippet in #PureBasic full color Example: Gimp 16 color Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate...
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Liberty_BASIC
Liberty BASIC
  ' Almost prime for k = 1 to 5 print "k = "; k; ":"; i = 2 c = 0 while c < 10 if kPrime(i, k) then print " "; using("###", i); c = c + 1 end if i = i + 1 wend print next k end   function kPrime(n, k) f = 0 for i = 2 to n while n mod i ...
Give a code snippet in #Liberty_BASIC A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-prim...
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#Tailspin
Tailspin
  templates largestNonMcNuggetNumber @: { largest: 0, mcNuggetNumbers: [1..$+20 -> 0] }; @.mcNuggetNumbers([6,9,20]): 1..3 -> 1; 1..$ -> # $@.largest ! when <?($@.mcNuggetNumbers($) <=0>)> do @.largest: $; otherwise @.mcNuggetNumbers([$ + 6, $ + 9, $ + 20]): 1..3 -> 1; end largestNonMcNuggetNumber   100 -> ...
Give a code snippet in #Tailspin Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A M...
christopher/rosetta-code