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/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write ...
#Racket
Racket
#lang racket/base   (struct P (x y))   (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2))   (module+ main (area ...
Give a code snippet in #Racket Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program beadSort.s */ /* En français tri par gravité ou tri par bille (ne pas confondre avec tri par bulle (bubble sort) */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conver...
Give a code snippet in #ARM_Assembly 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 | Q...
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...
#Jsish
Jsish
/* Factorial, in Jsish */   /* recursive */ function fact(n) { return ((n < 2) ? 1 : n * fact(n - 1)); }   /* iterative */ function factorial(n:number) { if (n < 0) throw format("factorial undefined for negative values: %d", n);   var fac = 1; while (n > 1) fac *= n--; return fac; }   if (Interp.conf('u...
Give a code snippet in #Jsish 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 n...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#BQN
BQN
Avg ← +´÷≠   Avg 1‿2‿3‿4
Give a code snippet in #BQN Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an establ...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have m...
#Python
Python
def longest_increasing_subsequence(X): """Returns the Longest Increasing Subsequence in the Given List/Array""" N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): ...
Give a code snippet in #Python Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\...
christopher/rosetta-code
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#C.2B.2B
C++
#include <iostream> #include <cmath>   int main() { int n = 1; int count = 0; int sq; int cr;   for (; count < 30; ++n) { sq = n * n; cr = cbrt(sq); if (cr * cr * cr != sq) { count++; std::cout << sq << '\n'; } else { std::cout << s...
Give a code snippet in #C.2B.2B Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Raven
Raven
# To print the squared elements [1 2 3 4 5] each dup * print
Give a code snippet in #Raven Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Phix
Phix
function RandomNormal() return sqrt(-2*log(rnd())) * cos(2*PI*rnd()) end function sequence s = repeat(0,1000) for i=1 to length(s) do s[i] = 1 + 0.5 * RandomNormal() end for
Give a code snippet in #Phix Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related ...
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.)
#XQuery
XQuery
(: This is a XQuery comment :)
Give a code snippet in #XQuery 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/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#Common_Lisp
Common Lisp
(defun top-n-by-group (n data value-key group-key predicate &key (group-test 'eql)) (let ((not-pred (complement predicate)) (group-data (make-hash-table :test group-test))) (labels ((value (datum) (funcall value-key datum)) (insert (x list) (merge 'list (list x) ...
Give a code snippet in #Common_Lisp Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Perl
Perl
use SDL; use SDL::Events; use SDLx::App;   my $app = SDLx::App->new; $app->add_event_handler( sub { my $event = shift; if( $event->type == SDL_MOUSEMOTION ) { printf( "x=%d y=%d\n", $event->motion_x, $event->motion_y ); $app->stop } } ); $app->run;  
Give a code snippet in #Perl Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Ada
Ada
generic type Element_Type is private; type Array_Type is array (Positive range <>) of Element_Type;   procedure Generic_Shuffle (List : in out Array_Type);
Give a code snippet in #Ada The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to...
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#PicoLisp
PicoLisp
  LEAVE The LEAVE statement terminates execution of a loop. Execution resumes at the next statement after the loop. ITERATE The ITERATE statement causes the next iteration of the loop to commence. Any statements between ITERATE and the end of the loop are not executed. STOP Terminates execution of ei...
Give a code snippet in #PicoLisp 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   constru...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#NewLisp
NewLisp
  ;;; The list (1 .. n-1) of integers is generated ;;; then each non-divisor of n is replaced by 0 ;;; finally all these numbers are summed. ;;; fn defines an anonymous function inline. (define (sum-divisors n) (apply + (map (fn (x) (if (> (% n x) 0) 0 x)) (sequence 1 (- n 1))))) ; ;;; Returns the symbols -, p or + fo...
Give a code snippet in #NewLisp These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficie...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#DWScript
DWScript
PrintLn(Lcm(12, 18));
Give a code snippet in #DWScript Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that ...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Logtalk
Logtalk
number_chars(Number, "123"), Number2 is Number+1, number_chars(Number2, String2)
Give a code snippet in #Logtalk Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Self_numbers
Self numbers
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. You should either confirm or d...
#Raku
Raku
# 20201127 Raku programming solution   my ( $st, $count, $i, $pow, $digits, $offset, $lastSelf, $done, @selfs) = now, 0, 1, 10, 1, 9, 0, False;   # while ( $count < 1e8 ) { until $done { my $isSelf = True; my $sum = (my $start = max ($i-$offset), 0).comb.sum; loop ( my $j = ...
Give a code snippet in #Raku A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Racket
Racket
#lang racket (require racket/draw math/statistics racket/require (filtered-in (lambda (name) (regexp-replace #rx"unsafe-" name "")) racket/unsafe/ops))   ;; CIE formula as discussed in "Greyscale image" task (define (L r g b)  ;; In fact there is no need, statistically for L to be divided...
Give a code snippet in #Racket Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must h...
christopher/rosetta-code
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Tcl
Tcl
Public Sub jump() Debug.Print "VBA only allows" GoTo 1 Debug.Print "no global jumps" 1: Debug.Print "jumps in procedures with GoTo" Debug.Print "However," On 2 GoSub one, two Debug.Print "named in the list after 'GoSub'" Debug.Print "and execution will continue on the next line" On 1...
Give a code snippet in #Tcl Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#VBA
VBA
Public c As Variant Public pi As Double Dim arclists() As Variant Public Enum circles_ xc = 0 yc rc End Enum Public Enum arclists_ rho x_ y_ i_ End Enum Public Enum shoelace_axis u = 0 v End Enum Private Sub give_a_list_of_circles() c = Array(Array(1.6417233788, 1.6121789534, 0.0...
Give a code snippet in #VBA Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (...
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....
#zkl
zkl
const target = "METHINKS IT IS LIKE A WEASEL"; const C = 100; // Number of children in each generation. const P = 0.05; // Mutation probability. const A2ZS = ["A".."Z"].walk().append(" ").concat(); fcn fitness(s){ Utils.zipWith('!=,target,s).sum(0) } // bigger is worser fcn rnd{ A2ZS[(0).random(27)] } fcn mutate(s){ s...
Give a code snippet in #zkl 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 a...
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...
#PHP
PHP
<?php function powers($m) { for ($n = 0; ; $n++) { yield pow($n, $m); } }   function filtered($s1, $s2) { while (true) { list($v, $f) = [$s1->current(), $s2->current()]; if ($v > $f) { $s2->next(); continue; } else if ($v < $f) { yield $v; ...
Give a code snippet in #PHP 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 th...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Common_Lisp
Common Lisp
(defun next-life (array &optional results) (let* ((dimensions (array-dimensions array)) (results (or results (make-array dimensions :element-type 'bit)))) (destructuring-bind (rows columns) dimensions (labels ((entry (row col) "Return array(row,col) for valid (row,col) else 0." ...
Give a code snippet in #Common_Lisp The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when d...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Haskell
Haskell
swap :: (a, b) -> (b, a) swap (x, y) = (y, x)
Give a code snippet in #Haskell Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides generic...
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...
#AWK
AWK
  # syntax: GAWK -f ASCENDING_PRIMES.AWK BEGIN { start = 1 stop = 23456789 for (i=start; i<=stop; i++) { if (is_prime(i)) { primes++ leng = length(i) flag = 1 for (j=1; j<leng; j++) { if (substr(i,j,1) >= substr(i,j+1,1)) { flag = 0 bre...
Give a code snippet in #AWK 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Erlang
Erlang
% Implemented by Arjun Sunel -module(guess_the_number). -export([main/0]).   main() -> io:format("Guess my number between 1 and 10 until you get it right:\n"), N = random:uniform(10), guess(N).   guess(N) -> {ok, [K]} = io:fread("Guess number : ","~d"),   if K=:=N -> io:format("Well guessed!!\n"); true ->...
Give a code snippet in #Erlang Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#BBC_BASIC
BBC BASIC
VDU 8  : REM Move one position to the left VDU 9  : REM Move one position to the right VDU 11  : REM Move up one line VDU 10  : REM Move down one line VDU 13  : REM Move to the beginning of the line VDU 30  : REM Move to the top left corner VDU 23,16,16;0;0;0; : REM Dis...
Give a code snippet in #BBC_BASIC Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Seed7
Seed7
$include "seed7_05.s7i";   const array string: name is [] ( " *** * ***** ", "* * * ", "* *** *** **** * ", "* * * * * * * * ", " *** * * * * * * * ", " * ***** ***** * * * ", " * * * * * *...
Give a code snippet in #Seed7 Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Sather
Sather
class MAIN is main is doors :ARRAY{BOOL} := #(100); loop pass::= doors.ind!; loop i::= pass.stepto!(doors.size - 1, pass + 1); doors[i] := ~doors[i]; end; end; loop #OUT + (doors.ind! + 1) + " " + doors.elt! + "\n"; end; end; end;
Give a code snippet in #Sather There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ....
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Yabasic
Yabasic
sub leapyear(year) if mod(year, 4) <> 0 then return false : fi if mod(year, 100) = 0 and mod(year, 400) <> 0 then return false : fi return TRUE end sub   for year = 1800 to 2900 step 100 print year; if leapyear(year) then print " is a leap year" else print " is not a leap year" : fi next year   print ...
Give a code snippet in #Yabasic Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#ooRexx
ooRexx
  delegator = .delegator~new -- no delegate say delegator~operation -- an invalid delegate type delegator~delegate = "Some string" say delegator~operation -- a good delegate delegator~delegate = .thing~new say delegator~operation -- a directory object with a thing entry defined d = .directory~new d~thing = "delegate ...
Give a code snippet in #ooRexx A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also ...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or f...
#NewLISP
NewLISP
(module "smtp.lsp") (SMTP:send-mail "user@asite.com" "somebody@isp.com" "Greetings" "How are you today? - john doe -" "smtp.asite.com" "user" "password")
Give a code snippet in #NewLISP Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Batch_File
Batch File
@echo off if "%2" equ "" goto fail setlocal enabledelayedexpansion set char=%1 set num=%2 for /l %%i in (1,1,%num%) do set res=!res!%char% echo %res% :fail
Give a code snippet in #Batch_File Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*"...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#zkl
zkl
var [const] MsgHash=Import.lib("zklMsgHash"); // SHA-256, etc   const symbols = "123456789" // 58 characters: no cap i,o; ell, zero "ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz";   fcn base58Encode(bytes){ //Data-->String bytes=bytes.copy(); sink:=Sink(String); do(33){ bytes.len().reduce('wrap...
Give a code snippet in #zkl Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in orde...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int X, Y, C, R2; [SetVid($13); \set 320x200x8 graphics mode C:= 0; \initialize point counter repeat X:= Ran(31)-15; \range -15..+15 Y:= Ran(31)-15; R2:= X*X + Y*Y; if R2>=10*10 & R2<=15*15 then [Po...
Give a code snippet in #XPL0 Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#D
D
import std.array, bitmap;   void floodFill(Color)(Image!Color img, in uint x, in uint y, in Color color) /*pure*/ nothrow in { assert (y < img.ny && x < img.nx); } body { immutable target = img[x, y]; static struct Pos { uint x, y; } auto stack = [Pos(x, y)];   while (!stack.em...
Give a code snippet in #D Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the...
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.)
#Blast
Blast
# A hash symbol at the beginning of a line marks the line as a comment  
Give a code snippet in #Blast 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/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Raku
Raku
sub gauss-jordan-solve (@a, @b) { @b.kv.map: { @a[$^k].append: $^v }; @a.&rref[*]»[*-1]; }   # reduced row echelon form sub rref (@m) { my ($lead, $rows, $cols) = 0, @m, @m[0];   for ^$rows -> $r { $lead < $cols or return @m; my $i = $r; until @m[$i;$lead] { ++$i == $...
Give a code snippet in #Raku Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function ProperDivisors(number As Integer) As IEnumerable(Of Integer) Return Enumerable.Range(1, number / 2).Where(Function(divisor As Integer) number Mod divisor = 0) End Function   Sub Main() For Each number In Enumerable.Range(1, 10) Console.WriteLine("{0}: {{...
Give a code snippet in #Visual_Basic_.NET The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Textonyms
Textonyms
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -...
#J
J
require'regex strings web/gethttp'   strip=:dyad define (('(?s)',x);'') rxrplc y )   fetch=:monad define txt=. '.*<pre>' strip '</pre>.*' strip gethttp y cutopen tolower txt-.' ' )   keys=:noun define 2 abc 3 def 4 ghi 5 jkl 6 mno 7 pqrs 8 tuv 9 wxyz )   reporttext=:noun define There are #{0} words in #{1...
Give a code snippet in #J When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -...
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Fortran
Fortran
program Bias_Unbias implicit none   integer, parameter :: samples = 1000000 integer :: i, j integer :: c1, c2, rand   do i = 3, 6 c1 = 0 c2 = 0 do j = 1, samples rand = bias(i) if (rand == 1) c1 = c1 + 1 rand = unbias(i) if (rand == 1) c2 = c2 + 1 end do write(*, "(...
Give a code snippet in #Fortran P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generato...
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...
#TorqueScript
TorqueScript
fileCopy("Input.txt", "Output.txt"); fileDelete("Input.txt");   for(%File = FindFirstFile("Path/*.*"); %File !$= ""; %File = FindNextFile("Path/*.*")) { fileCopy(%File, "OtherPath/" @ %File); fileDelete(%File); }
Give a code snippet in #TorqueScript 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...
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import javax.swing.   msgText = 'Goodbye, World!' JOptionPane.showMessageDialog(null, msgText)  
Give a code snippet in #NetRexx 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/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...
#Nim
Nim
import math import strformat   type   # Non zero digit range. Digit = range[1..9]   # Count array used to compute a distribution. Count = array[Digit, Natural]   # Array to store frequencies. Distribution = array[Digit, float]     #############################################################################...
Give a code snippet in #Nim 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-di...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#jq
jq
def popcount: def bin: recurse( if . == 0 then empty else ./2 | floor end ) % 2; [bin] | add;   def firstN(count; condition): if count > 0 then if condition then ., (1+.| firstN(count-1; condition)) else (1+.) | firstN(count; condition) end else empty end;   def task: def pow(n): . as $m | red...
Give a code snippet in #jq Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count  ...
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
#Fermat
Fermat
Func Istau(t) = if t<3 then Return(1) else numdiv:=2; for q = 2 to t\2 do if Divides(q, t) then numdiv:=numdiv+1 fi; od; if Divides(numdiv, t)=1 then Return(1) else Return(0) fi; fi; .;   numtau:=0; i:=0;   while numtau<100 do i:=i+1; if Istau(i) = 1 then ...
Give a code snippet in #Fermat 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/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
#min
min
"Hello world!" puts
Give a code snippet in #min 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/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)=(...
#Crystal
Crystal
require "big"   def is_prime(n) # P3 Prime Generator primality test return n | 1 == 3 if n < 5 # n: 0,1,4|false, 2,3|true return false if n.gcd(6) != 1 # for n a P3 prime candidate (pc) pc1, pc2 = -1, 1 # use P3's prime candidates sequence ...
Give a code snippet in #Crystal 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 ) ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#PureBasic
PureBasic
; Known; ; A. ; [ 151] ; [a ][b ] ; [40][c ][d ] ; [e ][f ][g ][h ] ; [ X][11][ Y][ 4][ Z] ; ; B. ; Y = X + Z   Procedure.i SolveForZ(x) Protected a,b,c,d,e,f,g,h,z For z=0 To 20 e=x+11: f=11+(x+z): g=(x+z)+4: h=4+z If e+f=40 c=f+g : d=g+h: a=40+c: b=c+d If a+b=151 ...
Give a code snippet in #PureBasic This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#lang5
lang5
[] 1 append ['foo 'bar] append 2 reshape 0 remove 2 swap 2 compress collapse .
Give a code snippet in #lang5 This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retri...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Processing
Processing
MySketch/ MySketch.pde one.pde two.pde MyClass.java
Give a code snippet in #Processing Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Common_Lisp
Common Lisp
(defparameter *earth-radius* 6372.8)   (defparameter *rad-conv* (/ pi 180))   (defun deg->rad (x) (* x *rad-conv*))   (defun haversine (x) (expt (sin (/ x 2)) 2))   (defun dist-rad (lat1 lng1 lat2 lng2) (let* ((hlat (haversine (- lat2 lat1))) (hlng (haversine (- lng2 lng1))) (root (sqrt (+ hlat ...
Give a code snippet in #Common_Lisp This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Liberty_BASIC
Liberty BASIC
  do read in$ if in$ ="END" then wait w =wordCount( in$) select case w case 0 o$ ="{}" case 1 o$ ="{" +in$ +"}" case 2 o$ ="{" +word$( in$, 1) +" and " +word$( in$, 2) +"}" case else ...
Give a code snippet in #Liberty_BASIC Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}"...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#Haskell
Haskell
if2 :: Bool -> Bool -> a -> a -> a -> a -> a if2 p1 p2 e12 e1 e2 e = if p1 then if p2 then e12 else e1 else if p2 then e2 else e   main = print $ if2 True False (error "TT") "TF" (error "FT") (error "FF")  
Give a code snippet in #Haskell Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e....
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Draco
Draco
proc nonrec tau(word n) word: word count, total, p; total := 1; while n & 1 = 0 do total := total + 1; n := n >> 1 od; p := 3; while p*p <= n do count := 1; while n % p = 0 do count := count + 1; n := n / p od; total := tota...
Give a code snippet in #Draco Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Python
Python
  import turtle as tt import inspect   stack = [] # Mark the current stacks in run. def peano(iterations=1): global stack   # The turtle Ivan: ivan = tt.Turtle(shape = "classic", visible = True)     # The app window: screen = tt.Screen() screen.title("Desenhin do Peano") screen.bgcolor("#232...
Give a code snippet in #Python Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#EasyLang
EasyLang
func bin_search val . a[] res . low = 0 high = len a[] - 1 res = -1 while low <= high and res = -1 mid = (low + high) div 2 if a[mid] > val high = mid - 1 elif a[mid] < val low = mid + 1 else res = mid . . . a[] = [ 2 4 6 8 9 ] call bin_search 8 a[] r print r
Give a code snippet in #EasyLang A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secre...
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...
#11l
11l
F hash_join(table1, table2) DefaultDict[String, [(Int, String)]] h L(s) table1 h[s[1]].append(s)   [((Int, String), (String, String))] res L(r) table2 L(s) h[r[0]] res [+]= (s, r) R res   V table1 = [(27, ‘Jonah’), (18, ‘Alan’), (28, ‘Glory’), (18,...
Give a code snippet in #11l 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" a...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#D
D
import bitmap: Image, RGB;   void circle(Color)(Image!Color img, in int x0, in int y0, in int radius, in Color color) pure nothrow @nogc @safe { int f = 1 - radius; int ddfX = 1; int ddfY = -2 * radius; int x = 0; int y = radius; img[x0, y0 + radius] = color; img[x0, y0 - ...
Give a code snippet in #D Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#BASIC
BASIC
'PROGRAM : BIG MULTIPLICATION VER #1 'LRCVS 01.01.2010 'THIS PROGRAM SIMPLY MAKES A MULTIPLICATION 'WITH ALL THE PARTIAL PRODUCTS. '............................................................   DECLARE SUB A.INICIO (A$, B$) DECLARE SUB B.STORE (CAD$, N$) DECLARE SUB C.PIZARRA () DECLARE SUB D.ENCABEZADOS (A$, B$) DECL...
Give a code snippet in #BASIC Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#MiniScript
MiniScript
makeList = function(sep) counter = 0 makeItem = function(item) outer.counter = counter + 1 return counter + sep + item end function return [makeItem("first"), makeItem("second"), makeItem("third")] end function   print makeList(". ")
Give a code snippet in #MiniScript In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting o...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#AutoHotkey
AutoHotkey
Coefficients = -19, 7, -4, 6 x := 3   MsgBox, % EvalPolynom(Coefficients, x)       ;--------------------------------------------------------------------------- EvalPolynom(Coefficients, x) { ; using Horner's rule ;--------------------------------------------------------------------------- StringSplit, Co, coefficie...
Give a code snippet in #AutoHotkey A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#zkl
zkl
words:=Dictionary(25000); //-->Dictionary(sorted word:all anagrams, ...) File("unixdict.txt").read().pump(Void,'wrap(w){ w=w.strip(); key:=w.sort(); words[key]=words.find(key,T).append(w); });   nws:=words.values.pump(List,fcn(ws){ //-->( (len,words), ...) if(ws.len()>1){ // two or more anagrams r:=List();...
Give a code snippet in #zkl Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[e...
christopher/rosetta-code
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Erlang
Erlang
20> re:split("a!===b=!=c", "==|!=|=",[{return, list}]). ["a",[],"b",[],"c"]
Give a code snippet in #Erlang It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task ...
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 ...
#Pascal
Pascal
program Spiralmat; type tDir = (left,down,right,up); tdxy = record dx,dy: longint; end; tdeltaDir = array[tDir] of tdxy; const Nextdir : array[tDir] of tDir = (down,right,up,left); cDir : tDeltaDir = ((dx:1;dy:0),(dx:0;dy:1),(dx:-1;dy:0),(dx:0;dy:-1)); cMaxN = 32; type tSpiral = array...
Give a code snippet in #Pascal 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 1...
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...
#Ol
Ol
  (define (compose f g) (lambda (x) (f (g x))))   ;; or:   (define ((compose f g) x) (f (g x)))  
Give a code snippet in #Ol 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   t...
christopher/rosetta-code
http://rosettacode.org/wiki/Hough_transform
Hough transform
Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\displaystyle (\rho ,\theta )} , ...
#Julia
Julia
using ImageFeatures   img = fill(false,5,5) img[3,:] .= true   println(hough_transform_standard(img))  
Give a code snippet in #Julia Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\di...
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
#Delphi
Delphi
program HelloWorldGraphical;   uses Dialogs;   begin ShowMessage('Goodbye, World!'); end.
Give a code snippet in #Delphi 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/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL #COMPILER PBCC 6   FUNCTION LuhnCheckPassed(BYVAL dgts AS STRING) AS INTEGER LOCAL i, s, s1 AS DWORD dgts = STRREVERSE$(dgts) FOR i = 1 TO LEN(dgts) STEP 2 s += VAL(MID$(dgts, i, 1)) NEXT i FOR i = 2 TO LEN(dgts) STEP 2 s1 = 2 * VAL(MID$(dgts, i, 1)) IF s1 >= ...
Give a code snippet in #PowerBASIC The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the ord...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Haskell
Haskell
  import Data.List   main = do f <- readFile "./../Puzzels/Rosetta/inout.txt" let (ioo,dt) = unzip. map ((\(_:io:_:t:_)-> (io,t)). words) . lines $ f cio = drop 1 . scanl (\c io -> if io == "IN" then pred c else succ c) 0 $ ioo mo = maximum cio putStrLn $ "Maximum simultaneous license use is " ++ sho...
Give a code snippet in #Haskell A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a c...
christopher/rosetta-code
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return succe...
#Wren
Wren
import "io" for FileSystem   class Main { construct new() {}   init() { FileSystem.createDirectory("path/to/dir") }   update() {}   draw(alpha) {} }   var Game = Main.new()
Give a code snippet in #Wren Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the director...
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 ...
#Standard_ML
Standard ML
val nbr1 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn); val nbr2 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn); val array = Array2.array (nbr1, nbr2, 0.0); Array2.update (array, 0, 0, 3.5); print (Real.toString (Array2.sub (array, 0, 0)) ^ "\n");
Give a code snippet in #Standard_ML 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 thos...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#REXX
REXX
/*REXX pgm prompts (using the OS GUI) for a string & then prompts for a specific number.*/ #= 75000 /*the number that must be entered. */ x= N= do while x=' '; say /*string can't be blanks or null string*/ say 'Please enter a string: ' p...
Give a code snippet in #REXX In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Emacs_Lisp
Emacs Lisp
(file-exists-p "input.txt") (file-directory-p "docs") (file-exists-p "/input.txt") (file-directory-p "/docs")
Give a code snippet in #Emacs_Lisp Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it work...
christopher/rosetta-code
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Scala
Scala
/** Roll our own pared-down BigFraction class just for these Bernoulli Numbers */ case class BFraction( numerator:BigInt, denominator:BigInt ) { require( denominator != BigInt(0), "Denominator cannot be zero" )   val gcd = numerator.gcd(denominator)   val num = numerator / gcd val den = denominator / gcd   de...
Give a code snippet in #Scala Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as pe...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Smalltalk
Smalltalk
foo := 41. ... self assert: (foo == 42).
Give a code snippet in #Smalltalk Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#DCL
DCL
* matches any number of characters & matches exactly any one character
Give a code snippet in #DCL Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, no...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Perl
Perl
use Math::Complex;   foreach my $n (2 .. 10) { printf "%2d", $n; my @roots = root(1,$n); foreach my $root (@roots) { $root->display_format(style => 'cartesian', format => '%.3f'); print " $root"; } print "\n"; }
Give a code snippet in #Perl The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
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...
#Python
Python
gifts = '''\ A partridge in a pear tree. Two turtle doves Three french hens Four calling birds Five golden rings Six geese a-laying Seven swans a-swimming Eight maids a-milking Nine ladies dancing Ten lords a-leaping Eleven pipers piping Twelve drummers drumming'''.split('\n')   days = '''first second third fourth fift...
Give a code snippet in #Python 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 operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#NetRexx
NetRexx
  import java.text.SimpleDateFormat say SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(Date())
Give a code snippet in #NetRexx Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#Common_Lisp
Common Lisp
(dolist (system '(:xpath :cxml-stp :cxml)) (asdf:oos 'asdf:load-op system))   (defparameter *doc* (cxml:parse-file "xml" (stp:make-builder)))   (xpath:first-node (xpath:evaluate "/inventory/section[1]/item[1]" *doc*))   (xpath:do-node-set (node (xpath:evaluate "/inventory/section/item/price/text()" *doc*)) (format ...
Give a code snippet in #Common_Lisp Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp S...
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 ...
#Java
Java
import java.io.*; import java.util.Scanner;   public class ReadFastaFile {   public static void main(String[] args) throws FileNotFoundException {   boolean first = true;   try (Scanner sc = new Scanner(new File("test.fasta"))) { while (sc.hasNextLine()) { String line = s...
Give a code snippet in #Java 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: >Rosett...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#zkl
zkl
__DATE__, __DEBUG__, __FILE__, __LINE__, __NAME__, __TIME__
Give a code snippet in #zkl Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
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 ...
#TMG
TMG
prog: ignore(spaces) loop: parse(line)\loop parse(( = {*} )); line: ( name | * = {} | seqns ); name: <>> ignore(none) smark string(nonl) scopy * ( [f>0?] = {} | = {*} ) [f=0] = { 1 2 <: > }; seqns: smark string(nonl) scopy * [f=0];   none: <<>>; nonl:  !<< >>; spaces: << >>;   f: 1;
Give a code snippet in #TMG 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#C
C
#include <string.h>   int palindrome(const char *s) { int i,l; l = strlen(s); for(i=0; i<l/2; i++) { if ( s[i] != s[l-i-1] ) return 0; } return 1; }
Give a code snippet in #C A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a w...
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...
#PHP
PHP
<?php function montyhall($iterations){ $switch_win = 0; $stay_win = 0;   foreach (range(1, $iterations) as $i){ $doors = array(0, 0, 0); $doors[array_rand($doors)] = 1; $choice = array_rand($doors); do { $shown = array_rand($doors); } while($shown == $choice || $doors[$shown] == 1);   $stay_win += $do...
Give a code snippet in #PHP 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 t...
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
#Phix
Phix
puts(1,"Hello world!")
Give a code snippet in #Phix 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/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#Elena
Elena
import system'routines; import extensions;   public program() { var a1 := new string[]{"a","b","c"}; var a2 := new string[]{"A","B","C"}; var a3 := new int[]{1,2,3};   for(int i := 0, i < a1.Length, i += 1) { console.printLine(a1[i], a2[i], a3[i]) };   console.readChar() }
Give a code snippet in #Elena Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this exam...
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#J
J
class Singleton { private static Singleton myInstance; public static Singleton getInstance() { if (myInstance == null) { synchronized(Singleton.class) { if (myInstance == null) { myInstance = new Singleton(); ...
Give a code snippet in #J A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#PowerShell
PowerShell
  [datetime]$start = Get-Date   [int]$count = 3   [timespan[]]$times = for ($i = 0; $i -lt $count; $i++) { Measure-Command {0..999999 | Out-Null} }   [datetime]$end = Get-Date   $rate = [PSCustomObject]@{ StartTime = $start EndTime = $end Duration = ($end - $start).TotalSeconds Ti...
Give a code snippet in #PowerShell Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplis...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Factor
Factor
USING: math.parser splitting ; : a+b ( -- ) readln " " split1 [ string>number ] bi@ + number>string print ;
Give a code snippet in #Factor A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separat...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Amazing_Hopper
Amazing Hopper
  #include <flow.h>   #import lib/input.bas.lib #include include/flow-input.h   DEF-MAIN(argv,argc) CLR-SCR MSET( número, cadena ) LOCATE(2,2), PRNL( "Input an string : "), LOC-COL(20), LET( cadena := READ-STRING( cadena ) ) LOCATE(3,2), PRNL( "Input an integer: "), LOC-COL(20), LET( número := INT( VAL(READ...
Give a code snippet in #Amazing_Hopper User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Simula
Simula
BEGIN   BOOLEAN PROCEDURE A(BOOL); BOOLEAN BOOL; BEGIN OUTCHAR('A'); A := BOOL; END A;   BOOLEAN PROCEDURE B(BOOL); BOOLEAN BOOL; BEGIN OUTCHAR('B'); B := BOOL; END B;   PROCEDURE OUTBOOL(BOOL); BOOLEAN BOOL; OUTCHAR(IF BOOL THEN 'T' ELSE 'F');   PROCEDURE TEST; BEGIN ...
Give a code snippet in #Simula 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 re...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#jq
jq
# include "rational"; # a reminder that r/2 and power/1 are required   # Input: any JSON number, not only a decimal # Output: a rational, constructed using r/2 # Requires power/1 (to take advantage of gojq's support for integer arithmetic) # and r/2 (for rational number constructor) def number_to_r:   # input: a deci...
Give a code snippet in #jq This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is no...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Scala
Scala
object BrazilianNumbers { private val PRIME_LIST = List( 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, ...
Give a code snippet in #Scala Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Vedit_macro_language
Vedit macro language
Num_Type(File_Stamp_Time("input.txt"))
Give a code snippet in #Vedit_macro_language Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#R
R
y=1 digital_root=function(n){ x=sum(as.numeric(unlist(strsplit(as.character(n),"")))) if(x<10){ k=x }else{ y=y+1 assign("y",y,envir = globalenv()) k=digital_root(x) } return(k) } print("Given number has additive persistence",y)
Give a code snippet in #R The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repe...
christopher/rosetta-code
http://rosettacode.org/wiki/Hough_transform
Hough transform
Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\displaystyle (\rho ,\theta )} , ...
#Rust
Rust
  //! Contributed by Gavin Baker <gavinb@antonym.org> //! Adapted from the Go version   use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Read, Write}; use std::iter::repeat;   /// Simple 8-bit grayscale image struct ImageGray8 { width: usize, height: usize, data: Vec<u8>, }   fn load_pg...
Give a code snippet in #Rust Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#APL
APL
∇numrev;list;in;swaps list←{9?9}⍣{⍺≢⍳9}⊢⍬ swaps←0 read: swaps+←1 in←{⍞←⍵⋄(≢⍵)↓⍞}(⍕list),': swap how many? ' list←⌽@(⍳⍎in)⊢list →(list≢⍳9)/read ⎕←(⍕list),': Congratulations!' ⎕←'Swaps:',swaps ∇
Give a code snippet in #APL Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The scor...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Agena
Agena
do print( "SPAM" ) od
Give a code snippet in #Agena Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loop...
christopher/rosetta-code