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/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Lingo
Lingo
obj = script("MyClass").new() -- ... method = #foo arg1 = 23 res = call(method, obj, arg1)
Give a code snippet in #Lingo Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Num...
#Racket
Racket
#lang racket   (struct *straddling (header main original) #:reflection-name 'straddling #:methods gen:custom-write [(define (write-proc board port mode) (write-string "#<straddling " port) (write (*straddling-original board) port) (write-string ">" port))])   (define string->vector (compose list...
Give a code snippet in #Racket Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be ...
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)...
#11l
11l
F fft(x) V n = x.len I n <= 1 R x V even = fft(x[(0..).step(2)]) V odd = fft(x[(1..).step(2)]) V t = (0 .< n I/ 2).map(k -> exp(-2i * math:pi * k / @n) * @odd[k]) R (0 .< n I/ 2).map(k -> @even[k] + @t[k]) [+] (0 .< n I/ 2).map(k -> @even[k] - @t[k])   print(fft([Complex(1.0), 1.0, 1.0, 1....
Give a code snippet in #11l 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 magnitu...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#NewLISP
NewLISP
(map println '(a b c) '(A B C) '(1 2 3))
Give a code snippet in #NewLISP Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this ex...
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 ...
#Julia
Julia
function vanecksequence(N, startval=0) ret = zeros(Int, N) ret[1] = startval for i in 1:N-1 lastseen = findlast(x -> x == ret[i], ret[1:i-1]) if lastseen != nothing ret[i + 1] = i - lastseen end end ret end   println(vanecksequence(10)) println(vanecksequence(1000...
Give a code snippet in #Julia 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#68000_Assembly
68000 Assembly
JSR SYS_READ_CALENDAR ;outputs calendar date to BIOS RAM   MOVE.B #'2',D0 ;a character in single or double quotes refers to its ascii equivalent. JSR PrintChar MOVE.B #'0',D0 JSR PrintChar   LEA BIOS_YEAR,A1 MOVE.B (A1)+,D0 ;stores last 2 digits of year into D0, in binary coded decimal...
Give a code snippet in #68000_Assembly This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#PicoLisp
PicoLisp
(de lastSundays (Y) (for M 12 (prinl (dat$ (find '((D) (= "Sunday" (day D))) (mapcar '((D) (date Y M D)) `(range 31 22)) ) "-" ) ) ) )
Give a code snippet in #PicoLisp Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly
Old lady swallowed a fly
Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. Other tasks related to st...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   STRING sw=" swallow ",swd=sw[:UPB sw-1]+"ed ", tsa=". To"+sw+"a";   INT count prev := 0; [9]STRING prev;   PROC vs = (STRING in wot,[]STRING co)VOID: ( STRING wot = " "+in wot; printf(($g$,"I know an old lady who",swd,"a",wot,".",$l$)); IF UPB co = 1 THEN printf(($gl$,co)) ...
Give a code snippet in #ALGOL_68 Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical out...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#Objeck
Objeck
use Data.XML; use Collection.Generic;   class Test { function : Main(args : String[]) ~ Nil { # list of name names := Vector->New()<String>; names->AddBack("April"); names->AddBack("Tam O'Shanter"); names->AddBack("Emily"); # list of comments comments := Vector->New()<String>; comments...
Give a code snippet in #Objeck Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> e...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Ring
Ring
  pi = 3.14 decimals(8) see "sin(pi/4.0) = " + sin(pi/4.0) + nl see "cos(pi/4.0) = " + cos(pi/4.0) + nl see "tan(pi/4.0) = " + tan(pi/4.0)+ nl see "asin(sin(pi/4.0)) = " + asin(sin(pi/4.0)) + nl see "acos(cos(pi/4.0)) = " + acos(cos(pi/4.0)) + nl see "atan(tan(pi/4.0)) = " + atan(tan(pi/4.0)) + nl see "atan2(3,4) = ...
Give a code snippet in #Ring Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evalua...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#SQL
SQL
  -- test.sql -- Tested in SQL*plus   DROP TABLE test;   CREATE TABLE test (a INTEGER, b INTEGER);   INSERT INTO test VALUES ('&&A','&&B');   commit;   SELECT a-b difference FROM test;   SELECT a*b product FROM test;   SELECT trunc(a/b) integer_quotient FROM test;   SELECT MOD(a,b) remainder FROM test;   SELECT POWER...
Give a code snippet in #SQL 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 Co...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Scheme
Scheme
  #!r6rs   (import (rnrs) (rnrs eval) (only (srfi :1 lists) append-map delete-duplicates iota))   (define (map* fn . lis) (if (null? lis) (list (fn)) (append-map (lambda (x) (apply map* (lambda xs (apply fn x xs)) (c...
Give a code snippet in #Scheme task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
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) ...
#ML
ML
local fun fbstr i = case (i mod 3 = 0, i mod 5 = 0) of (true , true ) => "FizzBuzz" | (true , false) => "Fizz" | (false, true ) => "Buzz" | (false, false) => Int.toString i   fun fizzbuzz' (n, j) = if n = j then () else (print (fbstr j ^ "\n"); fizzbuzz' (n, j+1)) in ...
Give a code snippet in #ML 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/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in th...
#ooRexx
ooRexx
all =.set~new Call time 'R' cnt.=0 do a=2 to 100 do b=a+1 to 100-2 p=a b if a+b>100 then leave b all~put(p) prd=a*b cnt.prd+=1 End End Say "There are" all~items "pairs where X+Y <=" max "(and X<Y)"   spairs=.set~new Do Until all~items=0 do p over all d=decompositions(p) If tak...
Give a code snippet in #ooRexx Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#OCaml
OCaml
type fruit = | Apple | Banana | Cherry
Give a code snippet in #OCaml Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Icon_and_Unicon
Icon and Unicon
# record type to store a 3D vector record Vector3D(x, y, z)   # procedure to display vector as a string procedure toString (vector) return "(" || vector.x || ", " || vector.y || ", " || vector.z || ")" end   procedure dotProduct (a, b) return a.x * b.x + a.y * b.y + a.z * b.z end   procedure crossProduct (a, b) x...
Give a code snippet in #Icon_and_Unicon A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a tri...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#AutoHotkey
AutoHotkey
URLDownloadToFile, http://www.gutenberg.org/files/135/135-0.txt, % A_temp "\tempfile.txt" FileRead, H, % A_temp "\tempfile.txt" FileDelete,  % A_temp "\tempfile.txt" words := [] while pos := RegExMatch(H, "\b[[:alpha:]]+\b", m, A_Index=1?1:pos+StrLen(m)) words[m] := words[m] ? words[m] + 1 : 1 for word, count in words...
Give a code snippet in #AutoHotkey Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to defi...
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Logo
Logo
to interpolate :s :a1 :a2 :b1 :b2 output (:s-:a1) / (:a2-:a1) * (:b2-:b1) + :b1 end   for [i 0 10] [print interpolate :i 0 10 -1 0]
Give a code snippet in #Logo Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   import java.util.List   placesList = [String - "UK London", "US New York", "US Boston", "US Washington" - , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - ]   lists = [ - placesList - ...
Give a code snippet in #NetRexx 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/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#Common_Lisp
Common Lisp
(defun levenshtein (a b) (let* ((la (length a)) (lb (length b)) (rec (make-array (list (1+ la) (1+ lb)) :initial-element nil))) (labels ((leven (x y) (cond ((zerop x) y) ((zerop y) x) ((aref rec x y) (aref rec x y)) ...
Give a code snippet in #Common_Lisp This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome 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 ...
#C.23
C#
  public static void gnomeSort(int[] anArray) { int first = 1; int second = 2;   while (first < anArray.Length) { if (anArray[first - 1] <= anArray[first]) { first = second; second++; ...
Give a code snippet in #C.23 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/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#SenseTalk
SenseTalk
properties cards: [] end properties to initialize set pips to (2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace") set suits to ("Clubs", "Spades", "Diamonds", "Hearts") repeat for each suit in suits repeat for each pip in pips set card to pip && "of" && suit insert card into my cards end repeat ...
Give a code snippet in #SenseTalk Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the curre...
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
With[{a = 5, b = 4}, PolarPlot[a + b t, {t, 0, 10 Pi}]]
Give a code snippet in #Mathematica.2FWolfram_Language The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#EasyLang
EasyLang
func shuffle . a[] . for i = len a[] downto 2 r = random i swap a[r] a[i - 1] . . arr[] = [ 1 2 3 ] call shuffle arr[] print arr[]  
Give a code snippet in #EasyLang 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Tree_datastructures
Tree datastructures
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of...
#Julia
Julia
const nesttext = """ RosettaCode rocks code comparison wiki mocks trolling """   function nesttoindent(txt) ret = "" windent = gcd(length.([x.match for x in eachmatch(r"\s+", txt)]) .- 1) for lin in split(txt, "\n") ret *= isempty(lin) ? "\n" : isspace(lin[1])...
Give a code snippet in #Julia The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list...
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...
#Fennel
Fennel
;; Fennel, like Lua, supports base 10 and hex literals (with a leading 0x). 1234  ;1234 0x1234  ;4660   ;; Optionally, underscores can be used to split numbers into readable chunks. 123_456_789  ;123456789 0x1234_5678  ;305419896
Give a code snippet in #Fennel 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 b...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#Batch_File
Batch File
::Draw a Clock Task from Rosetta Code Wiki ::Batch File Implementation :: ::Directly open the Batch File... @echo off & mode 44,8 title Sample Batch Clock setlocal enabledelayedexpansion chcp 65001 ::Set the characters... set "#0_1=█████" set "#0_2=█ █" set "#0_3=█ █" set "#0_4=█ █" set "#0_5=█████"   set "#1_1...
Give a code snippet in #Batch_File Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 ...
#AutoHotkey
AutoHotkey
MsgBox % ShellSort("") MsgBox % ShellSort("xxx") MsgBox % ShellSort("3,2,1") MsgBox % ShellSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z") MsgBox % ShellSort("12,11,10,9,8,4,5,6,7,3,2,1,10,13,14,15,19,17,18,16,20,10")   ShellSort(var) { ; SORT COMMA SEPARATED LIST StringSplit a, var, `, ...
Give a code snippet in #AutoHotkey 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 | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#Swift
Swift
import Foundation   func soeDictOdds() -> UnfoldSequence<Int, Int> { var bp = 5; var q = 25 var bps: UnfoldSequence<Int, Int>.Iterator? = nil var dict = [9: 6] // Dictionary<Int, Int>(9 => 6) return sequence(state: 2, next: { n in if n < 9 { if n < 3 { n = 3; return 2 }; defer {n += 2}; return n } while...
Give a code snippet in #Swift Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or prog...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Modula-3
Modula-3
MODULE Concat EXPORTS Main;   IMPORT IO;   VAR string: TEXT := "String"; string1: TEXT;   BEGIN IO.Put(string & " literal.\n"); string1 := string & " literal.\n"; IO.Put(string1); END Concat.
Give a code snippet in #Modula-3 String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string ...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#J
J
selPrime=: #~ 1&p: seed=: selPrime digits=: 1+i.9 step=: selPrime@,@:(,&.":/&>)@{@;
Give a code snippet in #J A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable p...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#F.23
F#
let divMod n d = n / d, n % d   let join = String.concat ", "   let rec nonzero = function | _, 0 -> "" | c, n -> c + (spellInteger n)   and tens n = [| ""; ""; "twenty"; "thirty"; "forty"; "fifty"; "sixty"; "seventy"; "eighty"; "ninety" |].[n]   and small n = [| "zero"; "one"; "two"; "three"; "fou...
Give a code snippet in #F.23 Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than posit...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Picat
Picat
main => dna(DNA, ChunkSize), Count = 0, println("Sequence:"), Map = new_map(['A'=0,'C'=0,'G'=0,'T'=0]), foreach(Chunk in DNA.chunks_of(ChunkSize)) printf("%4d: %s\n", Count, Chunk), Count := Count + Chunk.len, foreach(C in Chunk) Map.put(C,Map.get(C)+1) end end, println("\nBase count...
Give a code snippet in #Picat Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAAT...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#ALGOL-M
ALGOL-M
  BEGIN   INTEGER N, LEN, YES, NO, LIMIT, LONGEST, NLONG;   % RETURN P MOD Q % INTEGER FUNCTION MOD(P, Q); INTEGER P, Q; BEGIN MOD := P - Q * (P / Q); END;   % COMPUTE AND OPTIONALLY DISPLAY HAILSTONE SEQUENCE FOR N. % % RETURN LENGTH OF SEQUENCE OR ZERO ON OVERFLOW. % INTEGER FUNCTION HAILSTONE(N, DISPLAY); INTEGER ...
Give a code snippet in #ALGOL-M The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + ...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#WebAssembly
WebAssembly
(module  ;; function isOdd: returns 1 if its argument is odd, 0 if it is even. (func $isOdd (param $n i32) (result i32) get_local $n i32.const 1 i32.and  ;; computes (n & 1), i.e. returns low bit of n ) (export "isOdd" (func $isOdd)) )
Give a code snippet in #WebAssembly Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd....
christopher/rosetta-code
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C
C
  #include<stdlib.h> #include<stdio.h>   typedef struct{ int score; char name[100]; }entry;   void ordinalRanking(entry* list,int len){   int i;   printf("\n\nOrdinal Ranking\n---------------");   for(i=0;i<len;i++) printf("\n%d\t%d\t%s",i+1,list[i].score,list[i].name); }   void standardRanking(entry* list,int l...
Give a code snippet in #C Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Nemerle
Nemerle
using System.Console; using System.IO;   WriteLine(File.Exists("input.txt")); WriteLine(File.Exists("/input.txt")); WriteLine(Directory.Exists("docs")); WriteLine(Directory.Exists("/docs"));
Give a code snippet in #Nemerle Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works w...
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...
#Tcl
Tcl
set ch [read $channel 1]
Give a code snippet in #Tcl 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Swift
Swift
extension BinaryInteger { @inlinable public var isNarcissistic: Bool { let digits = String(self).map({ Int(String($0))! }) let m = digits.count   guard m != 1 else { return true }   return digits.map({ $0.power(m) }).reduce(0, +) == self }   @inlinable public func power(_ n: Self) ->...
Give a code snippet in #Swift A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#AppleScript
AppleScript
set dist to findLevenshteinDistance for "sunday" against "saturday" to findLevenshteinDistance for s1 against s2 script o property l : s1 property m : s2 end script if s1 = s2 then return 0 set ll to length of s1 set lm to length of s2 if ll = 0 then return lm if lm = 0 then ...
Give a code snippet in #AppleScript This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory a...
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...
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de reversalGame () (let (Lst (shuffle (range 1 9)) Cnt 0) (while (apply < Lst) (setq Lst (shuffle Lst)) ) (loop (printsp Lst) (T (apply < Lst) Cnt) (NIL (num? (read))) (setq Lst (flip Lst @)) (inc 'Cnt) ) ) )
Give a code snippet in #PicoLisp 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Nim
Nim
if true: echo "yes" if false: echo "no"   # Other objects never represent true or false: if 2: echo "compile error"
Give a code snippet in #Nim Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#ALGOL_68
ALGOL 68
FORMAT hay stack := $c("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")$;   FILE needle exception; STRING ref needle; associate(needle exception, ref needle);   PROC index = (FORMAT haystack, REF STRING needle)INT:( INT out; ref needle := needle; getf(needle exception,(haystack, out));...
Give a code snippet in #ALGOL_68 Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle...
christopher/rosetta-code
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Go
Go
// +build <expression>
Give a code snippet in #Go Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate ho...
christopher/rosetta-code
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#Kotlin
Kotlin
// version 1.2.21   fun median(x: DoubleArray, start: Int, endInclusive: Int): Double { val size = endInclusive - start + 1 require (size > 0) { "Array slice cannot be empty" } val m = start + size / 2 return if (size % 2 == 1) x[m] else (x[m - 1] + x[m]) / 2.0 }   fun fivenum(x: DoubleArray): DoubleArr...
Give a code snippet in #Kotlin Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#EchoLisp
EchoLisp
  (lib 'plot) (lib 'types)   (define (move iter x dir constant: plane turns cmax width xmax (cidx 0)) (while (> iter 0) ;; get color index of current square (set! cidx (vector-ref plane x))   ;; turn (if (vector-ref turns cidx) (set! dir (if (= dir 3) 0 (1+ dir))) ;; right is #t (set! dir (if (= dir 0) 3...
Give a code snippet in #EchoLisp Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#VBA
VBA
Private Function lngHalve(Nb As Long) As Long lngHalve = Nb / 2 End Function   Private Function lngDouble(Nb As Long) As Long lngDouble = Nb * 2 End Function   Private Function IsEven(Nb As Long) As Boolean IsEven = (Nb Mod 2 = 0) End Function
Give a code snippet in #VBA Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wri...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Go
Go
package main   import ( "fmt" "hash/crc32" )   func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
Give a code snippet in #Go Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the in...
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 ...
#Haskell
Haskell
import Data.Bifunctor (bimap)   ----------- SHOELACE FORMULA FOR POLYGONAL AREA ----------   -- The area of a polygon formed by -- the list of (x, y) coordinates.   shoelace :: [(Double, Double)] -> Double shoelace = let calcSums ((x, y), (a, b)) = bimap (x * b +) (a * y +) in (/ 2) . abs . uncurry...
Give a code snippet in #Haskell 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/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Lua
Lua
local _M = {}   local bit = require('bit') local math = require('math')   _M.encode = function(number) return bit.bxor(number, bit.rshift(number, 1)); end   _M.decode = function(gray_code) local value = 0 while gray_code > 0 do gray_code, value = bit.rshift(gray_code, 1), bit.bxor(gray_code, value) end r...
Give a code snippet in #Lua Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many po...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Smalltalk
Smalltalk
String extend [ ltrim [ ^self replacingRegex: '^\s+' with: ''. ] rtrim [ ^self replacingRegex: '\s+$' with: ''. ] trim [ ^self ltrim rtrim. ] ]   |a| a := ' this is a string '.   ('"%1"' % {a}) displayNl. ('"%1"' % {a ltrim}) displayNl. ('"%1"' % {a rtrim}) displayNl. ('"%...
Give a code snippet in #Smalltalk Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespac...
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) ...
#Ceylon
Ceylon
shared void run() => {for (i in 1..100) {for (j->k in [3->"Fizz", 5->"Buzz"]) if (j.divides(i)) k}.reduce(plus) else i}.each(print);
Give a code snippet in #Ceylon Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#360_Assembly
360 Assembly
* Permutations/Derangements 01/04/2017 DERANGE CSECT USING DERANGE,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST...
Give a code snippet in #360_Assembly A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactor...
christopher/rosetta-code
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#Delphi
Delphi
  program Yellowstone_sequence;   {$APPTYPE CONSOLE}   uses System.SysUtils, Boost.Generics.Collection, Boost.Process;   function gdc(x, y: Integer): Integer; begin while y <> 0 do begin var tmp := x; x := y; y := tmp mod y; end; Result := x; end;   function Yellowstone(n: Integer): TArray<Int...
Give a code snippet in #Delphi The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence i...
christopher/rosetta-code
http://rosettacode.org/wiki/Halt_and_catch_fire
Halt and catch fire
Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an...
#FreeBASIC
FreeBASIC
poke 0,0
Give a code snippet in #FreeBASIC Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help d...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Print["Hello world!"]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   H...
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.)
#DWScript
DWScript
(* This is a comment. It may extend across multiple lines. *)   { Alternatively curly braces can be used. }   /* C-style multi-line comments are supported */   // and single-line C++ style comments too
Give a code snippet in #DWScript 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/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Datalog
Datalog
.decl A(text: symbol) .decl B(text: symbol) .decl SymmetricDifference(text: symbol) .output SymmetricDifference   A("this"). A("is"). A("a"). A("test"). B("also"). B("part"). B("of"). B("a"). B("test").   SymmetricDifference(x) :- A(x), !B(x). SymmetricDifference(x) :- B(x), !A(x).
Give a code snippet in #Datalog Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Pike
Pike
  string hello = "hello "; write(hello + "world" + "\n"); string all_of_it = hello + "world"; write(all_of_it + "\n");  
Give a code snippet in #Pike String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string lite...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Fortran
Fortran
program intersect_two_lines implicit none   type point real::x,y end type point   integer, parameter :: n = 4 type(point) :: p(n)   p(1)%x = 4; p(1)%y = 0; p(2)%x = 6; p(2)%y = 10 ! fist line p(3)%x = 0; p(3)%y = 3; p(4)%x = 10; p(4)%y = 7 ! second line   call intersect(p, n)   contains ...
Give a code snippet in #Fortran [1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#ATS
ATS
(********************************************************************) (* The public interface *)   abstype dllist_t (t : t@ype+, is_root : bool) (* An abstract type. *) typedef dllist_t (t : t@ype+) = [b : bool] dllist_t (t, b)   (* Make a new dllist_t, consisting of a root ...
Give a code snippet in #ATS Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type ...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Rust
Rust
fn aks_coefficients(k: usize) -> Vec<i64> { let mut coefficients = vec![0i64; k + 1]; coefficients[0] = 1; for i in 1..(k + 1) { coefficients[i] = -(1..i).fold(coefficients[0], |prev, j|{ let old = coefficients[j]; coefficients[j] = old - prev; old }); ...
Give a code snippet in #Rust The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the c...
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.
#Yacas
Yacas
Concat({1,2,3}, {4,5,6})   Out> {1, 2, 3, 4, 5, 6}
Give a code snippet in #Yacas 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/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Gambas
Gambas
' Gambas module file   Public DrawerArray As Long[] Public NumberFromDrawer As Long Public FoundOwnNumber As Long   Public Sub Main()   Dim NumberOfPrisoners As Long Dim Selections As Long Dim Tries As Long   Print "Number of prisoners (default, 100)?" Try Input NumberOfPrisoners If Error Then NumberOfPriso...
Give a code snippet in #Gambas The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start ...
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#SequenceL
SequenceL
import <Utilities/Sequence.sl>; import <Utilities/Conversion.sl>; import <Utilities/Math.sl>;   //region Types   Point ::= (x: int(0), y: int(0)); Color ::= (red: int(0), green: int(0), blue: int(0)); Image ::= (kind: char(1), iColor: Color(0), vert1: Point(0), vert2: Point(0), vert3: Point(0), center: Point(0), ...
Give a code snippet in #SequenceL One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum a...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Yabasic
Yabasic
system("dir") //It will return the exit code of the command; its output (if any) will be lost.     print system$("dir") //Returns the output as a large string.
Give a code snippet in #Yabasic Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#PARI.2FGP
PARI/GP
sizebyte(x)
Give a code snippet in #PARI.2FGP Demonstrate how to get the size of a variable. See also: Host introspection
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Batch_File
Batch File
@echo off setlocal enableDelayedExpansion ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: LIFO stack usage :: Define the stack call :newStack myStack :: Push some values onto the stack for %%A in (value1 value2 value3) do call :pushStack myStack %%A :: Test if stack is empty by examining th...
Give a code snippet in #Batch_File Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack ...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Logo
Logo
print first butfirst shell [ls -a]  ; ..
Give a code snippet in #Logo Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows;   namespace Sutherland { public static class SutherlandHodgman { #region Class: Edge   /// <summary> /// This represents a line segment /// </summary> private class...
Give a code snippet in #C.23 The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#Wren
Wren
import "/pattern" for Pattern   var s = "\t\n\r\x01\0\fabc\v\v\b\a\x1f\x7f🌇Páez😃É"   // strip control codes only var p = Pattern.new("+1/c") var r = p.replaceAll(s, "") System.print("%(r) -> length %(r.count)")   // strip extended characters as well p = Pattern.new("[+1/c|+1/R]") r = p.replaceAll(s, "") System.print(...
Give a code snippet in #Wren Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped ...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Forth
Forth
45e pi f* 180e f/ \ radians   cr fdup fsin f. \ also available: fsincos ( r -- sin cos ) cr fdup fcos f. cr fdup ftan f. cr fdup fasin f. cr fdup facos f. cr fatan f. \ also available: fatan2 ( r1 r2 -- atan[r1/r2] )
Give a code snippet in #Forth Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evalu...
christopher/rosetta-code
http://rosettacode.org/wiki/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,...
#Visual_Basic
Visual Basic
Sub mersenne() Dim q As Long, k As Long, p As Long, d As Long Dim factor As Long, i As Long, y As Long, z As Long Dim prime As Boolean q = 929 'input value For k = 1 To 1048576 '2**20 p = 2 * k * q + 1 If (p And 7) = 1 Or (p And 7) = 7 Then 'p=*001 or p=*111 'p is ...
Give a code snippet in #Visual_Basic 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 b...
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Smalltalk
Smalltalk
|A B| A := Set new. B := Set new. A addAll: #( 'John' 'Bob' 'Mary' 'Serena' ). B addAll: #( 'Jim' 'Mary' 'John' 'Bob' ).   ( (A - B) + (B - A) ) displayNl.
Give a code snippet in #Smalltalk Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#BBC_BASIC
BBC BASIC
MODE 8 GCOL 15 CIRCLE FILL 640, 512, 500 GCOL 0 CIRCLE FILL 500, 600, 200 GCOL 3 PROCflood(600, 200, 15) GCOL 4 PROCflood(600, 700, 0) END   DEF PROCflood(X%, Y%, C%) LOCAL L%, R% IF POINT(X%,Y%) <> C% ENDPROC L% = X% R% = X% ...
Give a code snippet in #BBC_BASIC Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point tow...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#XL
XL
use XL.UI.CONSOLE WriteLn "Hello world!"
Give a code snippet in #XL Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   H...
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) ...
#LiveScript
LiveScript
[1 to 100] map -> [k + \zz for k, v of {Fi: 3, Bu: 5} | it % v < 1] * '' || it
Give a code snippet in #LiveScript 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   Fiz...
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. ...
#Logo
Logo
for [i 1 5] [repeat :i [type "*] (print)] repeat 5 [repeat repcount [type "*] (print)]
Give a code snippet in #Logo “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structur...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#PowerShell
PowerShell
1..5 | ForEach-Object { $_ * $_ }
Give a code snippet in #PowerShell Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
n=4;Grid[CellularAutomaton[90,{{1},0},2^n-1]/.{0->" ",1->"*"},ItemSize->All]
Give a code snippet in #Mathematica.2FWolfram_Language Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Objeck
Objeck
use IO;   bundle Default { class Test { function : Main(args : String[]) ~ Nil { BitWise(3, 4); }   function : BitWise(a : Int, b : Int) ~ Nil { Console->GetInstance()->Print("a and b: ")->PrintLine(a and b); Console->GetInstance()->Print("a or b: ")->PrintLine(a or b); Console->...
Give a code snippet in #Objeck 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#Perl
Perl
#!perl use 5.010; use strict; use warnings; use bigint;   sub leftfact { my ($n) = @_; state $cached = 0; state $factorial = 1; state $leftfact = 0; if( $n < $cached ) { ($cached, $factorial, $leftfact) = (0, 1, 0); } while( $n > $cached ) { $leftfact += $factorial; $factorial *= ++$cached; } return $lef...
Give a code snippet in #Perl Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#zkl
zkl
fcn dotp(a,b){ a.zipWith('*,b).sum() } //1 slow but concise fcn crossp([(a1,a2,a3)],[(b1,b2,b3)]) //2 { return(a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) }
Give a code snippet in #zkl A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Racket
Racket
#lang lazy (define nats (cons 1 (map add1 nats))) (define (sift n l) (filter (λ(x) (not (zero? (modulo x n)))) l)) (define (sieve l) (cons (first l) (sieve (sift (first l) (rest l))))) (define primes (sieve (rest nats))) (!! (take 25 primes))
Give a code snippet in #Racket Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a...
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#ALGOL_68
ALGOL 68
INT scale x=2, scale y=1; CHAR black="#", white=".", clear=" ";   PROC print yin yang = (REAL radius)VOID:(   PROC in circle = (REAL centre x, centre y, radius, x, y)BOOL: (x-centre x)**2+(y-centre y)**2 <= radius**2;   PROC (REAL, REAL)BOOL in big circle = in circle(0, 0, radius, , ), in white semi cir...
Give a code snippet in #ALGOL_68 One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Scala
Scala
def binarySearch[A <% Ordered[A]](a: IndexedSeq[A], v: A) = { def recurse(low: Int, high: Int): Option[Int] = (low + high) / 2 match { case _ if high < low => None case mid if a(mid) > v => recurse(low, mid - 1) case mid if a(mid) < v => recurse(mid + 1, high) case mid => Some(mid) } recurse(0, a....
Give a code snippet in #Scala A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret n...
christopher/rosetta-code
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Ruby
Ruby
fs = proc { |f, s| s.map &f } f1 = proc { |n| n * 2 } f2 = proc { |n| n ** 2 } fsf1 = fs.curry[f1] fsf2 = fs.curry[f2]   [0..3, (2..8).step(2)].each do |e| p fsf1[e] p fsf2[e] end
Give a code snippet in #Ruby Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#S-BASIC
S-BASIC
  rem - compute p mod q function mod(p, q = integer) = integer end = p - q * (p/q)   rem - return true (-1) if y is a leap year, otherwise 0 function isleapyear(y = integer) = integer end = mod(y,4)=0 and mod(y,100)<>0 or mod(y,400)=0   rem - exercise the function var y = integer   print "Test of century years" for y ...
Give a code snippet in #S-BASIC Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Python
Python
# Search for an odd factor of a using brute force: for i in range(n): if (n%2) == 0: continue if (n%i) == 0: result = i break else: result = None print "No odd factors found"
Give a code snippet in #Python Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#OCaml
OCaml
open Graphics   let round v = int_of_float (floor (v +. 0.5))   let middle (x1, y1) (x2, y2) = ((x1 +. x2) /. 2.0, (y1 +. y2) /. 2.0)   let draw_line (x1, y1) (x2, y2) = moveto (round x1) (round y1); lineto (round x2) (round y2); ;;   let draw_triangle (p1, p2, p3) = draw_line p1 p2; draw_line p2 p3; d...
Give a code snippet in #OCaml Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#PARI.2FGP
PARI/GP
dsum(n,base)=my(s); while(n, s += n%base; n \= base); s
Give a code snippet in #PARI.2FGP Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Cuban_primes
Cuban primes
The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.   primes of the form:   n3 - ...
#Transd
Transd
  #lang transd   MainModule: { primes: Vector<ULong>([3, 5]), lim: 200, bigUn: 100000, chunks: 50, little: 0, c: 0, showEach: true, u: ULong(0), v: ULong(1),   _start: (λ found Bool() fnd Bool() mx Int() z ULong() (= little (/ bigUn chunks)) (for i in Range(1 (pow...
Give a code snippet in #Transd The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Nim
Nim
import os   echo fileExists "input.txt" echo fileExists "/input.txt" echo dirExists "docs" echo dirExists "/docs"
Give a code snippet in #Nim Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#C.2B.2B.2FCLI
C++/CLI
  using namespace System::Windows::Forms;   int main(array<System::String^> ^args) { MessageBox::Show("Goodbye, World!", "Rosetta Code"); return 0; }  
Give a code snippet in #C.2B.2B.2FCLI Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given f...
#Julia
Julia
using Cxx   cxx""" #include <stdio.h> #include <sys/mman.h> #include <string.h>   int test (int a, int b) { /* mov EAX, [ESP+4] add EAX, [ESP+8] ret */ char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3}; void *buf; int c; /* copy code to executable buffer */ buf = mmap ...
Give a code snippet in #Julia The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assem...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#OpenEdge.2FProgress
OpenEdge/Progress
  FUNCTION csvToHtml RETURNS CHARACTER ( i_lhas_header AS LOGICAL, i_cinput AS CHARACTER ):   DEFINE VARIABLE coutput AS CHARACTER NO-UNDO.   DEFINE VARIABLE irow AS INTEGER NO-UNDO. DEFINE VARIABLE icolumn AS INTEGER NO-UNDO. DEFINE VARIABLE crow AS CHARACTER NO-UNDO. DEFI...
Give a code snippet in #OpenEdge.2FProgress Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HT...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#C.2B.2B
C++
#include <string> #include <boost/regex.hpp> #include <boost/asio.hpp> #include <vector> #include <utility> #include <iostream> #include <sstream> #include <cstdlib> #include <algorithm> #include <iomanip>   struct Sort { //sorting programming languages according to frequency bool operator( ) ( const std::pair<std::...
Give a code snippet in #C.2B.2B Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 jui...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Common_Lisp
Common Lisp
;; * Loading the split-sequence library (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload '("split-sequence")))   ;; * The package definition (defpackage :mean-time-of-day (:use :common-lisp :iterate :split-sequence)) (in-package :mean-time-of-day)   ;; * The data (defparameter *time-values* '(...
Give a code snippet in #Common_Lisp Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Wren
Wren
import "/math" for Int import "/fmt" for Fmt import "/big" for BigInt   var hickerson = Fn.new { |n| var fact = BigInt.new(Int.factorial(n)) // accurate up to n == 18 var ln2 = BigInt.new("693147180559945309417232121458176568075500134360255254120680009") // 63 digits var mult = BigInt.new("1e64").pow(n+1) ...
Give a code snippet in #Wren The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle ...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). T...
#Ela
Ela
pi # private pi = 3.14159   sum # private sum x y = x + y
Give a code snippet in #Ela Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scop...
christopher/rosetta-code