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/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#zkl
zkl
ppm:=PPM(200,200,0xFF|FF|FF); ppm.line(50,100, 100,190, 0); ppm.line(100,190, 150,100, 0); ppm.line(150,100, 100,10, 0); ppm.line(100,10, 50,100, 0);   ppm.writeJPGFile("line.jpg");
Give a code snippet in #zkl Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Forth
Forth
include ffl/car.fs   10 car-create ar \ create a dynamic array with initial size 10   2 0 ar car-set \ ar[0] = 2 3 1 ar car-set \ ar[1] = 3 1 0 ar car-insert \ ar[0] = 1 ar[1] = 2 ar[2] = 3  
Give a code snippet in #Forth This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Cr...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Scala
Scala
scala> 16 res10: Int = 16 scala> 020L res11: Long = 16 scala> 0x10 : Byte res12: Byte = 16 scala> 16 : Short res13: Short = 16 scala> 020 : Int res14: Int = 16 scala> 0x10 : Long res15: Long = 16
Give a code snippet in #Scala Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be...
christopher/rosetta-code
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Fortran
Fortran
SUBROUTINE TSORT(NL,ND,IDEP,IORD,IPOS,NO) IMPLICIT NONE INTEGER NL,ND,NO,IDEP(ND,2),IORD(NL),IPOS(NL),I,J,K,IL,IR,IPL,IPR DO 10 I=1,NL IORD(I)=I 10 IPOS(I)=I K=1 20 J=K K=NL+1 DO 30 I=1,ND IL=IDEP(I,1) IR=IDEP(I,2) IPL=IPOS(IL) IPR=IPOS(IR) ...
Give a code snippet in #Fortran Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Component_Pascal
Component Pascal
  MODULE Brackets; IMPORT StdLog, Args, Stacks (* See Task Stacks *); TYPE   Character = POINTER TO RECORD (Stacks.Object) c: CHAR END;   PROCEDURE NewCharacter(c: CHAR): Character; VAR n: Character; BEGIN NEW(n);n.c:= c;RETURN n END NewCharacter;   PROCEDURE (c: Character) Show*; BEGIN StdLog.String("Character(...
Give a code snippet in #Component_Pascal Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of ...
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 ...
#VBScript
VBScript
  Function build_spiral(n) botcol = 0 : topcol = n - 1 botrow = 0 : toprow = n - 1 'declare a two dimensional array Dim matrix() ReDim matrix(topcol,toprow) dir = 0 : col = 0 : row = 0 'populate the array For i = 0 To n*n-1 matrix(col,row) = i Select Case dir Case 0 If col < topcol Then col = co...
Give a code snippet in #VBScript 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...
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 ...
#Isabelle
Isabelle
theory Insertionsort imports Main begin   fun insert :: "int ⇒ int list ⇒ int list" where "insert x [] = [x]" | "insert x (y#ys) = (if x ≤ y then (x#y#ys) else y#(insert x ys))"   text‹Example:› lemma "insert 4 [1, 2, 3, 5, 6] = [1, 2, 3, 4, 5, 6]" by(code_simp)   fun insertionsort :: "int list ⇒ int list" where ...
Give a code snippet in #Isabelle Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Phix
Phix
-- -- demo\rosetta\hilbert_curve.exw -- ============================== -- -- Draws a hilbert curve. -- with javascript_semantics include pGUI.e constant title = "Hilbert Curve" Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas constant width = 64 sequence points = {} procedure hilbert(integer x, y, lg, i1, i2) ...
Give a code snippet in #Phix Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
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...
#Scheme
Scheme
  (import (scheme base) (scheme read) (scheme write) (srfi 1) ; list functions (srfi 27)) ; random numbers   (random-source-randomize! default-random-source)   (define (make-randomised-list) (let ((vec (apply vector (iota 9 1)))) (do ((c 0 (+ 1 c))) ((and (>= c 20) ...
Give a code snippet in #Scheme 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/Equal_prime_and_composite_sums
Equal prime and composite sums
Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes. P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ... P = 2, 5, 10, 17, 28, etc. Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites. C = (4...
#FreeBASIC
FreeBASIC
#include "isprime.bas"   Dim As Integer i = 0 Dim As Integer IndN = 1, IndM = 1 Dim As Integer NumP = 2, NumC = 4 Dim As Integer SumP = 2, SumC = 4 Print " sum prime sum composite sum" Do If SumC > SumP Then Do NumP += 1 Loop Until isPrime(NumP) SumP += NumP...
Give a code snippet in #FreeBASIC Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes. P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ... P = 2, 5, 10, 17, 28, etc. Further; suppose we have a sequence of composite sums, where each term Cm is the sum...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Jq
Jq
- functionally, e.g. using map on an array - by enumeration, i.e. by generating a stream - by performing a reduction
Give a code snippet in #Jq Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compou...
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...
#Cowgol
Cowgol
include "cowgol.coh";   loop print("Spam\n"); end loop;
Give a code snippet in #Cowgol 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   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS
HTTPS
Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request task, and also the task on HTT...
#Delphi
Delphi
  program ShowHTTPS;   {$APPTYPE CONSOLE}   uses IdHttp, IdSSLOpenSSL;   var s: string; lHTTP: TIdHTTP; begin lHTTP := TIdHTTP.Create(nil); try lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP); lHTTP.HandleRedirects := True; s := lHTTP.Get('https://sourceforge.net/'); Writeln(s); ...
Give a code snippet in #Delphi Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Reques...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Nim
Nim
import sequtils, sets, strutils   iterator recaman(num: Positive = Natural.high): tuple[n, a: int; duplicate: bool] = var a = 0 yield (0, a, false) var known = [0].toHashSet for n in 1..<num: var next = a - n if next <= 0 or next in known: next = a + n a = next yield (n, a, a in known) ...
Give a code snippet in #Nim The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Racket
Racket
(define lowercase-letters (build-list 26 (lambda (x) (integer->char (+ x (char->integer #\a))))))
Give a code snippet in #Racket Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#BCPL
BCPL
get "libhdr"   static $( randstate = ? $)   let randdigit() = valof $( let x = ? $( randstate := random(randstate) x := (randstate >> 7) & 15 $) repeatuntil 0 < x <= 9 resultis x $)   let gensecret(s) be for i=0 to 3 s!i := randdigit() repeatuntil valof $( for j=0 to i-1 if s!...
Give a code snippet in #BCPL Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the g...
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...
#JavaScript
JavaScript
DoublyLinkedList.prototype.getTail = function() { var tail; this.traverse(function(node){tail = node;}); return tail; } DoublyLinkedList.prototype.traverseBackward = function(func) { func(this); if (this.prev() != null) this.prev().traverseBackward(func); } DoublyLinkedList.prototype.printB...
Give a code snippet in #JavaScript 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, Elem...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Common_Lisp
Common Lisp
  (defun string-of-brackets (n) (let* ((len (* 2 n)) (res (make-string len)) (opening (/ len 2)) (closing (/ len 2))) (dotimes (i len res) (setf (aref res i) (cond ((zerop opening) #\]) ((zerop closing) #\[) (t (if (= (random 2) 0) ...
Give a code snippet in #Common_Lisp Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#AWK
AWK
  # syntax: GAWK -f INTROSPECTION.AWK BEGIN { if (PROCINFO["version"] < "4.1.0") { print("version is too old") exit(1) } bloop = -1 if (PROCINFO["identifiers"]["abs"] == "user" && bloop != "") { printf("bloop = %s\n",bloop) printf("abs(bloop) = %s\n",abs(bloop)) } exit(0)...
Give a code snippet in #AWK Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(b...
christopher/rosetta-code
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If t...
#PureBasic
PureBasic
  Red [ Title: "Go Fish" Author: "gltewalt" ]   chand: []  ;-- c and p = computer and player cguesses: [] phand: [] cbooks: 0 pbooks: 0 gf: { *************** * GO FISH * *************** } pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant pile: []  ;-- whe...
Give a code snippet in #PureBasic Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Simulate_input/Keyboard
Simulate input/Keyboard
Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
#PureBasic
PureBasic
If AW_WinActivate("Calc") AW_SendKeys("123+3=") EndIf
Give a code snippet in #PureBasic Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
christopher/rosetta-code
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 ...
#Fortran
Fortran
DOUBLE PRECISION FUNCTION AREA(N,P) !Calculates the area enclosed by the polygon P. C Uses the mid-point rule for integration. Consider the line joining (x1,y1) to (x2,y2) C The area under that line (down to the x-axis) is the y-span midpoint (y1 + y2)/2 times the width (x2 - x1) C This is the trapezoidal rule ...
Give a code snippet in #Fortran 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#Run_BASIC
Run BASIC
cnt = 8 sig = int(log(cnt) /log(2) +0.9999)   pi = 3.14159265 real1 = 2^sig   real = real1 -1 real2 = int(real1 / 2) real4 = int(real1 / 4) real3 = real4 +real2   dim rel(real1) dim img(real1) dim cmp(real3)   for i = 0 to cnt -1 read rel(i) read img(i) next i   data 1,0, 1,0, 1,0, 1,0, 0,0, 0,0, 0,0...
Give a code snippet in #Run_BASIC Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the m...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#zkl
zkl
class Point{var x,y; fcn init(xyOrPoint=0,_=0){ if(Point.isInstanceOf(xyOrPoint)) set(xyOrPoint); else x,y=vm.arglist.apply("toFloat")} fcn set(p){x=p.x;y=p.y} fcn toString{"(%d,%d)".fmt(x,y)} } class Circle{var center, radius; fcn init(a=0.0,b=0.0,r=1.0){ switch [arglist]{ case(...
Give a code snippet in #zkl Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
numbers=RandomReal[{-2,6},11] tpk[numbers_,overflowVal_]:=Module[{revNumbers}, revNumbers=Reverse[numbers]; f[x_]:=Abs[x]^0.5+5 x^3; Do[ If[f[i]>overflowVal, Print["f[",i,"]= Overflow"] , Print["f[",i,"]= ",f[i]] ] , {i,revNumbers} ] ] tpk[numbers,400]
Give a code snippet in #Mathematica.2FWolfram_Language 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 language...
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#Wren
Wren
import "/math" for Int, Nums import "/sort" for Sort import "/fmt" for Fmt   var isInteger = Fn.new { |n| n is Num && n.isInteger }   var primHeronian = Fn.new { |a, b, c| if (!(isInteger.call(a) && isInteger.call(b) && isInteger.call(c))) return [false, 0, 0] if (Int.gcd(Int.gcd(a, b), c) != 1) return [false, ...
Give a code snippet in #Wren Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Factor
Factor
USING: accessors images images.loader kernel literals math math.vectors random sets ; FROM: sets => in? ; EXCLUDE: sequences => move ; IN: rosetta-code.brownian-tree   CONSTANT: size 512 CONSTANT: num-particles 30000 CONSTANT: seed { 256 256 } CONSTANT: spawns { { 10 10 } { 502 10 } { 10 502 } { 502 502 } } CONSTANT: b...
Give a code snippet in #Factor Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initi...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8
Read a file character by character/UTF8
Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support the reading of files contain...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "utf8.s7i";   const proc: main is func local var file: inFile is STD_NULL; var char: ch is ' '; begin OUT := STD_UTF8_OUT; inFile := openUtf8("readAFileCharacterByCharacterUtf8.in", "r"); if inFile <> STD_NULL then while hasNext(inFile) do ch := ...
Give a code snippet in #Seed7 Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should suppo...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#Phix
Phix
function count_jewels(string stones, jewels) integer res = 0 for i=1 to length(stones) do res += find(stones[i],jewels)!=0 end for return res end function ?count_jewels("aAAbbbb","aA") ?count_jewels("ZZ","z")
Give a code snippet in #Phix Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Java
Java
import java.util.Arrays; import java.util.Collections; import java.util.List;   public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');   public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().re...
Give a code snippet in #Java Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#PowerShell
PowerShell
function ackermann ([long] $m, [long] $n) { if ($m -eq 0) { return $n + 1 }   if ($n -eq 0) { return (ackermann ($m - 1) 1) }   return (ackermann ($m - 1) (ackermann $m ($n - 1))) }
Give a code snippet in #PowerShell The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Haskell
Haskell
import Data.Complex   main = do print $ 0 ^ 0 print $ 0.0 ^ 0 print $ 0 ^^ 0 print $ 0 ** 0 print $ (0 :+ 0) ^ 0 print $ (0 :+ 0) ** (0 :+ 0)
Give a code snippet in #Haskell Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     o...
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   say say 'Loops/Break' rn = Rexx rnd = Random()   loop label lb forever rn = rnd.nextInt(19) say rn.right(3)'\-' if rn = 10 then leave lb rn = rnd.nextInt(19) say rn.right(3)'\-' end lb say  
Give a code snippet in #NetRexx 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....
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Wren
Wren
import "./perm" for Powerset   var sets = [ [1, 2, 3, 4], [], [[]] ] for (set in sets) { System.print("The power set of %(set) is:") System.print(Powerset.list(set)) System.print() }
Give a code snippet in #Wren A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given ...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Befunge
Befunge
local bot:int = 99   repeat print string(bot)+" bottles of beer on the wall," print string(bot)+" bottles of beer." print "Take one down, pass it around," bot:-1 print string(bot)+" bottles of beer on the wall." print until bot = 1   print "1 bottle of beer on the wall," print "1 bottle of beer....
Give a code snippet in #Befunge Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall ...
christopher/rosetta-code
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h...
#zkl
zkl
a,_,c:=List(1,2,3,4,5,6) //-->a=1, c=3, here _ is used as "ignore" 3.0 : _.sqrt() : println(_) //-->"1.73205", _ (and :) is used to "explode" a computation // as syntactic sugar 1.0 + 2 : _.sqrt() : _.pow(4) // no variables used, the compiler "implodes" the computation // --> 9  
Give a code snippet in #zkl Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language...
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) ...
#C.23
C#
class Program { public void FizzBuzzGo() { Boolean Fizz = false; Boolean Buzz = false; for (int count = 1; count <= 100; count ++) { Fizz = count % 3 == 0; Buzz = count % 5 == 0; if (Fizz && Buzz) { Console.WriteLine...
Give a code snippet in #C.23 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 ...
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 ...
#Wart
Wart
def (multiply a b) a*b
Give a code snippet in #Wart A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract f...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#11l
11l
T Circle Float x, y, r F (x, y, r) .x = x .y = y .r = r   V circles = [ Circle(1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle(0.6110294452, -0.6907087527, 0.9089162485), Circle(0.3844862411, 0.2923344616, 0.2375743054), Circle(...
Give a code snippet in #11l 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/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coeffici...
#11l
11l
[(Int, Int) = BigInt] computed   F sterling1(n, k) V key = (n, k)   I key C :computed R :computed[key] I n == k == 0 R BigInt(1) I n > 0 & k == 0 R BigInt(0) I k > n R BigInt(0) V result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)  :computed[key] = result R r...
Give a code snippet in #11l Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of th...
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...
#Oforth
Oforth
: foo( n -- bl ) #[ n swap + dup ->n ] ;
Give a code snippet in #Oforth 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 pa...
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...
#Ela
Ela
fact = fact' 1L where fact' acc 0 = acc fact' acc n = fact' (n * acc) (n - 1)
Give a code snippet in #Ela 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 num...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. The original article was at P...
#Swift
Swift
import BigInt   func permutations(n: Int, k: Int) -> BigInt { let l = n - k + 1   guard l <= n else { return 1 }   return (l...n).reduce(BigInt(1), { $0 * BigInt($1) }) }   func combinations(n: Int, k: Int) -> BigInt { let fact = {() -> BigInt in guard k > 1 else { return 1 }   return (2...
Give a code snippet in #Swift This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia...
christopher/rosetta-code
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Kotlin
Kotlin
  data class Person(val name: String) { val preferences = mutableListOf<Person>() var matchedTo: Person? = null   fun trySwap(p: Person) { if (prefers(p)) { matchedTo?.matchedTo = null matchedTo = p p.matchedTo = this } }   fun prefers(p: Person) =...
Give a code snippet in #Kotlin Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Erlang
Erlang
% Implemented by Arjun Sunel -module(carpet). -export([main/0]).   main() -> sierpinski_carpet(3).   sierpinski_carpet(N) -> lists: foreach(fun(X) -> lists: foreach(fun(Y) -> carpet(X,Y) end,lists:seq(0,trunc(math:pow(3,N))-1)), io:format("\n") end, lists:seq(0,trunc(math:pow(3,N))-1)).   carpet(X,Y) -> if X=:=0...
Give a code snippet in #Erlang Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # #...
christopher/rosetta-code
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st...
#FreeBASIC
FreeBASIC
#include "ontimer.bi"   Randomize Timer Dim Shared As Uinteger nWorkers = 3 Dim Shared As Uinteger tID(nWorkers) Dim Shared As Integer cnt(nWorkers) Dim Shared As Integer checked = 0   Sub checkpoint() Dim As Boolean sync   If checked = 0 Then sync = False checked += 1 If (sync = False) And (checked = n...
Give a code snippet in #FreeBASIC The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part f...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Retro
Retro
  ( by creating a variable ) "" keepString variable: foo   ( by setting an existing variable 'foo' ) "" keepString !foo  
Give a code snippet in #Retro Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Oth...
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#Rust
Rust
fn runge_kutta4(fx: &dyn Fn(f64, f64) -> f64, x: f64, y: f64, dx: f64) -> f64 { let k1 = dx * fx(x, y); let k2 = dx * fx(x + dx / 2.0, y + k1 / 2.0); let k3 = dx * fx(x + dx / 2.0, y + k2 / 2.0); let k4 = dx * fx(x + dx, y + k3);   y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0 }   fn f(x: f64, y: f64) -...
Give a code snippet in #Rust Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#Go
Go
package main   import ( "fmt" "sort" )   const pow3_8 = 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 // 3^8 const pow3_9 = 3 * pow3_8 // 3^9 const maxExprs = 2 * pow3_8 // not 3^9 since first op can't be Join   type op uint8   const ( Add op = iota // insert a "+" Sub // or a "-...
Give a code snippet in #Go Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular su...
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...
#C
C
#include <sys/types.h> #include <regex.h> #include <stdio.h>   typedef struct { const char *s; int len, prec, assoc; } str_tok_t;   typedef struct { const char * str; int assoc, prec; regex_t re; } pat_t;   enum assoc { A_NONE, A_L, A_R }; pat_t pat_eos = {"", A_NONE, 0};   pat_t pat_ops[] = { {"^\\)", A_NONE, -1...
Give a code snippet in #C 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...
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.)
#BASIC
BASIC
100 REM Standard BASIC comments begin with "REM" (remark) and extend to the end of the line 110 PRINT "this is code": REM comment after statement
Give a code snippet in #BASIC 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/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble 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 ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated strings   proc BSort(A, N); \Bubble sort array in ascending order char A; \address of array int N; \number of items in array (size) int I...
Give a code snippet in #XPL0 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Scala
Scala
import java.awt.MouseInfo object MousePosition extends App { val mouseLocation = MouseInfo.getPointerInfo.getLocation println (mouseLocation) }
Give a code snippet in #Scala 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/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#VBScript
VBScript
' Factors of a Mersenne number for i=1 to 59 z=i if z=59 then z=929 ':) 61 turns into 929. if isPrime(z) then r=testM(z) zz=left("M" & z & space(4),4) if r=0 then Wscript.echo zz & " prime." else Wscript.echo...
Give a code snippet in #VBScript A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor befor...
christopher/rosetta-code
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} ) ...
#Phix
Phix
-- -- demo\rosetta\Canny_Edge_Detection.exw -- ===================================== -- without js -- imImage, im_width, im_height, im_pixel, IupImageRGB, -- imFileImageLoadBitmap, and IupImageFromImImage() include pGUI.e constant TITLE = "Canny Edge Detection", IMGFILE = "Valve.png", C_E...
Give a code snippet in #Phix Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y...
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...
#Applesoft_BASIC
Applesoft BASIC
10 I = RND(0) : REMRANDOM SEED   20 FOR J = 1 TO 1000000 : REMMAYBE TRY 100 ON A 1MHZ APPLE II 30 N = 10 : GOSUB 100"ONE_OF_N 40 C(C) = C(C) + 1 50 NEXT   60 FOR J = 1 TO 10 70 PRINT J, C(J) 80 NEXT 90 END   100 REMONE_OF_N 110 FOR I = 1 TO N 120 IF INT(RND(1) * I) = 0 THEN C = I 130 NEXT I 140 RETURN
Give a code snippet in #Applesoft_BASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#R
R
  visited <- vector('logical', 1e8)   terms <- vector('numeric')   in_a_interval <- function(v) { visited[[v+1]] }   add_value <- function(v) { visited[[v+1]] <<- TRUE terms <<- append(terms, v) }   add_value(0) step <- 1 value <- 0   founddup <- FALSE   repeat { if ((value-step>0) && (!in_a_interval(value-step)))...
Give a code snippet in #R The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#J
J
m&|@^
Give a code snippet in #J Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Sparkling
Sparkling
function numStrIncmt(s) { return fmtstr("%d", toint(s) + 1); }   spn:1> numStrIncmt("12345") = 12346
Give a code snippet in #Sparkling Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isPrime(n As UInteger) As Boolean If n < 2 Then Return False If n Mod 2 = 0 Then Return n = 2 If n Mod 3 = 0 Then Return n = 3 Dim d As Integer = 5 While d * d <= n If n Mod d = 0 Then Return False d += 2 If n Mod d = 0 Then Return False d += 4 Wend Return True...
Give a code snippet in #FreeBASIC An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000t...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if ...
#QB64
QB64
For x = -5 To 5 Step 10 For p = 2 To 3 Print "x = "; x; " p ="; p; " "; Print Using "-x^p is ####"; -x ^ p; Print Using ", -(x)^p is ####"; -(x) ^ p; Print Using ", (-x)^p is ####"; (-x) ^ p; Print Using ", -(x^p) is ####"; -(x ^ p) Next Next
Give a code snippet in #QB64 (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's ...
christopher/rosetta-code
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls
Numbers with equal rises and falls
When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall    is an index   i   such that   ...
#XPL0
XPL0
func RiseFall(N); \Return 'true' if N has equal rises and falls int N, R, F, D, D0; [R:= 0; F:= 0; N:= N/10; D0:= rem(0); while N do [N:= N/10; D:= rem(0); if D > D0 then R:= R+1; if D < D0 then F:= F+1; D0:= D; ]; return R = F; ];   int N, Cnt; [N:= 1; Cnt:= 0; loop [if RiseFall(N) t...
Give a code snippet in #XPL0 When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall    ...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DIM a$(10): REM This array will be 10 characters long 20 DIM b(10): REM this will hold a set of numbers. The fixed number of bytes per number is implementation specific 30 LET c=5: REM this is a single numerical value of fixed size
Give a code snippet in #ZX_Spectrum_Basic Task Demonstrate how to specify the minimum size of a variable or a data type.
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Wren
Wren
var s = "rosetta code phrase reversal" System.print("Input  : %(s)") System.print("String reversed  : %(s[-1..0])") System.print("Each word reversed  : %(s.split(" ").map { |w| w[-1..0] }.join(" "))") System.print("Word order reversed : %(s.split(" ")[-1..0].join(" "))")
Give a code snippet in #Wren Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each...
christopher/rosetta-code
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneous...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DynamicModule[{data = ArrayPad[PadRight[Characters /@ StringSplit["tH......... . . ... . . Ht.. ......", "\n"]] /. {" " -> 0, "t" -> 2, "H" -> 1, "." -> 3}, 1]}, Dynamic@ArrayPlot[ data = CellularAutomaton[{{{_, _, _}, {_, 0, _}, {_, _, _}} -> 0, {{_, _, _}...
Give a code snippet in #Mathematica.2FWolfram_Language Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one ...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#REXX
REXX
/*REXX program generates some random numbers, shows bin histogram, finds mean & stdDev. */ numeric digits 20 /*use twenty decimal digits precision, */ showDigs=digits()%2 /* ··· but only show ten decimal digits*/ parse arg size seed . ...
Give a code snippet in #REXX Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. The original article was at P...
#Visual_Basic_.NET
Visual Basic .NET
' Combinations and permutations - 10/04/2017 Imports System.Numerics 'BigInteger Module CombPermRc   Sub Main() Dim i, j As Long For i = 1 To 12 For j = 1 To i Console.Write("P(" & i & "," & j & ")=" & PermBig(i, j).ToString & " ") Next j Console...
Give a code snippet in #Visual_Basic_.NET This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content fr...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#LFE
LFE
  (: file write_file '"output.txt" '"Some data") (: file make_dir '"docs") (: file write_file '"/output.txt" '"Some data") (: file make_dir '"/docs")  
Give a code snippet in #LFE In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts She...
#Ring
Ring
  list1 = "1, 2, 1, 5, 2" list2 = "5, 2, 1, 5, 2, 2" list3 = "1, 2, 3, 4, 5" list4 = "1, 2, 3, 4, 5"   if order(list1, list2) = 0 see "list1=list2" + nl but order(list1, list2) < 0 see "list1<list2" + nl else see "list1>list2" + nl ok   if order(list2, list3) = 0 see "list2=list3" + nl but order(list2, list3) < 0 see "...
Give a code snippet in #Ring sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Delphi
Delphi
  [Pythagorean triples for Rosetta code. Counts (1) all Pythagorean triples (2) primitive Pythagorean triples, with perimeter not greater than a given value.   Library subroutine M3, Prints header and is then overwritten. Here, the last character sets the teleprinter to figures.] ..PZ [simulate blank tape] ...
Give a code snippet in #Delphi A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Euphoria
Euphoria
function aeval( sequence sArr, integer id ) for i = 1 to length( sArr ) do sArr[ i ] = call_func( id, { sArr[ i ] } ) end for return sArr end function   object biggun function biggest( object elem ) if compare(elem, biggun) > 0 then biggun = elem end if return elem end function  ...
Give a code snippet in #Euphoria Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#AutoHotkey
AutoHotkey
Start:=A_TickCount counter=0 SetTimer, timer, 500 return   timer: Send % ++Counter "`n" return   ^c:: SetTimer, timer, off SetFormat, float, 0.3 Send, % "Task took " (A_TickCount-Start)/1000 " Seconds" ExitApp return
Give a code snippet in #AutoHotkey Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Prolog
Prolog
:- use_module(library(lambda)).   stripchars(String, Exclude, Result) :- exclude(\X^(member(X, Exclude)), String, Result1), string_to_list(Result, Result1).  
Give a code snippet in #Prolog Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#Nim
Nim
import strutils   const   Small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]   Tens = ["", "", "t...
Give a code snippet in #Nim Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of cha...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#F.23
F#
open System   let convert seconds = let span = TimeSpan.FromSeconds(seconds |> float) let (wk, day) = Math.DivRem(span.Days, 7) let parts = [(wk, "wk"); (day, "day"); (span.Hours, "hr"); (span.Minutes, "min"); (span.Seconds, "sec")] let result = List.foldBack (fun (n, u) acc -> ...
Give a code snippet in #F.23 Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#PicoLisp
PicoLisp
(let Val 0 (loop (println (inc 'Val)) (T (=0 (% Val 6))) ) )
Give a code snippet in #PicoLisp Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#dodo0
dodo0
fun for -> var, test, body, return # define a for loop using recursion ( test(var) -> continue if (continue) -> ( body(var) -> var for (var, test, body, return) ) | return(var) ) | for   fun upToFive (-> index, return) '<='(index, 5, return) | upToFive   for (1, upToFive) -> index, r...
Give a code snippet in #dodo0 “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structu...
christopher/rosetta-code
http://rosettacode.org/wiki/Object_serialization
Object serialization
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o...
#Erlang
Erlang
  -module( object_serialization ).   -export( [task/0] ).   -record( entity, {name, date} ). -record( person, {entity, email} ).   task() -> Person = #person{entity=#entity{name="Cletus", date=20080808}, email="test+1@localhost.localdomain"}, print( Person ), Entity = #entity{name="Entity", date=20111111}, print( E...
Give a code snippet in #Erlang Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each ...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Tcl
Tcl
## Mathematically, the first term has index "0", not "1". We do that, also.   set ::vE 0   proc vanEck {n} { global vE vEocc while {$n >= [set k [expr {[llength $vE] - 1}]]} { set kv [lindex $vE $k] ## value $kv @ $k is not yet stuffed into vEocc() lappend vE [expr {[info exists vEocc($...
Give a code snippet in #Tcl The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured p...
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: menuSelect (in array string: items, in string: prompt) is func result var string: selection is ""; local var string: item is ""; var integer: index is 0; var integer: num is 0; begin if length(items) <> 0 then repeat for item key ind...
Give a code snippet in #Seed7 Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the stri...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Maple
Maple
numtheory:-order( a, n )
Give a code snippet in #Maple The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is effic...
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#Julia
Julia
  julia> using Sockets   julia> getaddrinfo("www.kame.net") ip"203.178.141.194"   julia> getaddrinfo("www.kame.net", IPv6) ip"2001:200:dff:fff1:216:3eff:feb1:44d7"    
Give a code snippet in #Julia DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#Maple
Maple
lst := StringTools:-Split(Import("http://www.puzzlers.org/pub/wordlists/unixdict.txt"), "\n"): longest := 0: words := Array(): i := 1: for word in lst do if StringTools:-IsSorted(word) then len := StringTools:-Length(word): if len > longest then longest := len: words := Array(): words(1) := word: i := ...
Give a code snippet in #Maple An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locall...
christopher/rosetta-code
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Racket
Racket
  #lang racket (define chr integer->char) (define ord char->integer)   (define (encrypt msg key) (define cleaned (list->string (for/list ([c (string-upcase msg)] #:when (char-alphabetic? c)) c))) (list->string (for/list ([c cleaned] [k (in-cycle key)]) (chr (+ (modulo (+ (ord c) (o...
Give a code snippet in #Racket Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of i...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Maple
Maple
toOrdinal := proc(n:: nonnegint) if 1 <= n and n <= 10 then if n >= 4 then printf("%ath", n); elif n = 3 then printf("%ard", n); elif n = 2 then printf("%and", n); else printf("%ast", n); end if: else printf(convert(n, 'ordinal')); end if: return NULL; end proc:   a := [[0, 25], [250, 265], ...
Give a code snippet in #Maple Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show...
christopher/rosetta-code
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local...
#Erlang
Erlang
-module(echo). -export([start/0]).   start() -> spawn(fun () -> {ok, Sock} = gen_tcp:listen(12321, [{packet, line}]), echo_loop(Sock) end).   echo_loop(Sock) -> {ok, Conn} = gen_tcp:accept(Sock), io:format("Got connection: ~p~n", [Conn]), Handler = spawn(fun () -> handle(Co...
Give a code snippet in #Erlang Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary t...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() show(shuffle([3,1,4,1,5,9,2,6,3])) show(shuffle("this is a string")) end   procedure shuffle(A) every A[i := *A to 1 by -1] :=: A[?i] return A end   procedure show(A) every writes(!A," ") write() end
Give a code snippet in #Icon_and_Unicon 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 rangi...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#D
D
import std.stdio: writeln;   void main() { int[] a = [1, 2]; int[] b = [4, 5, 6];   writeln(a, " ~ ", b, " = ", a ~ b); }
Give a code snippet in #D Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
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...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT PRINT "Find the luckynumber (7 tries)!" luckynumber=RANDOM_NUMBERS (1,10,1) COMPILE LOOP round=1,7 message=CONCAT ("[",round,"] Please insert a number") ASK $message: n="" IF (n!='digits') THEN PRINT "wrong insert: ",n," Please insert a digit" ELSEIF (n>10.or.n<1) THEN PRINT "wrong insert: ",...
Give a code snippet in #TUSCRIPT 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 ...
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...
#Visual_Basic_.NET
Visual Basic .NET
  Debug.Print(Replace(Space(5), " ", "Ha"))  
Give a code snippet in #Visual_Basic_.NET 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-c...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an 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 |...
#Niue
Niue
[ 'n ; [ negative-or-zero [ , ] if [ n not-factor [ , ] when ] else ] n times n ] 'factors ;   [ dup 0 <= ] 'negative-or-zero ; [ swap dup rot swap mod 0 = not ] 'not-factor ;   ( tests ) 100 factors .s .clr ( => 1 2 4 5 10 20 25 50 100 ) newline 53 factors .s .clr ( => 1 53 ) newline 64 factors .s .clr ( => 1 ...
Give a code snippet in #Niue 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/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Java
Java
import java.io.UnsupportedEncodingException; import java.net.URLEncoder;   public class Main { public static void main(String[] args) throws UnsupportedEncodingException { String normal = "http://foo bar/"; String encoded = URLEncoder.encode(normal, "utf-8"); System.out.println(encoded);...
Give a code snippet in #Java Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes i...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#NESL
NESL
function fib(n) = if n < 2 then n else fib(n - 2) + fib(n - 1);
Give a code snippet in #NESL The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Pascal
Pascal
  program primes(output)   const PrimeLimit = 1000;   var primes: set of 1 .. PrimeLimit; n, k: integer; needcomma: boolean;   begin { calculate the primes } primes := [2 .. PrimeLimit]; for n := 1 to trunc(sqrt(PrimeLimit)) do begin if n in primes then begin k := n*n; while k < PrimeLi...
Give a code snippet in #Pascal This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <string> #include <vector>   typedef unsigned char ubyte; const auto BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";   std::vector<ubyte> encode(const std::vector<ubyte>& source) { auto it = source.cbegin(); auto end = source.cend();...
Give a code snippet in #C.2B.2B See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output ...
christopher/rosetta-code
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#Julia
Julia
# Floyd-Warshall algorithm: https://rosettacode.org/wiki/Floyd-Warshall_algorithm # v0.6   function floydwarshall(weights::Matrix, nvert::Int) dist = fill(Inf, nvert, nvert) for i in 1:size(weights, 1) dist[weights[i, 1], weights[i, 2]] = weights[i, 3] end # return dist next = collect(j != i...
Give a code snippet in #Julia The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already be...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Jsish
Jsish
/* Arithmetic evaluation, in Jsish */ function evalArithmeticExp(s) { s = s.replace(/\s/g,'').replace(/^\+/,''); var rePara = /\([^\(\)]*\)/; var exp;   function evalExp(s) { s = s.replace(/[\(\)]/g,''); var reMD = /[0-9]+\.?[0-9]*\s*[\*\/]\s*[+-]?[0-9]+\.?[0-9]*/; var reM = /\*/...
Give a code snippet in #Jsish Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a si...
christopher/rosetta-code
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do ...
#Kotlin
Kotlin
import java.math.BigInteger import java.time.Duration import java.util.ArrayList import java.util.HashSet import kotlin.math.sqrt   const val ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|" var base: Byte = 0 var bmo: Byte = 0 var blim: Byte = 0 var ic: Byte = 0 var st0: Long = 0 var bllim:...
Give a code snippet in #Kotlin Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the sea...
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...
#Stata
Stata
program spheredist version 15.0 syntax varlist(min=4 max=4 numeric), GENerate(namelist max=1) /// [Radius(real 6371) ALTitude(real 0) LABel(string)] confirm new variable `generate' local lat1 : word 1 of `varlist' local lon1 : word 2 of `varlist' local lat2 : word 3 of `varlist' local lon2 : word 4 of `varlist...
Give a code snippet in #Stata 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 equa...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#AppleScript
AppleScript
stripChar("She was a soul stripper. She took my heart!", "aei")   on stripChar(str, chrs) tell AppleScript set oldTIDs to text item delimiters set text item delimiters to characters of chrs set TIs to text items of str set text item delimiters to "" set str to TIs as string ...
Give a code snippet in #AppleScript Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any character...
christopher/rosetta-code