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/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#PureBasic
PureBasic
[ say "Please use the shell to calculate a value" cr say "and leave it on the stack. Type 'leave' when" cr say "you have done this." cr shell ] constant is my-value
Give a code snippet in #PureBasic Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languag...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#Smalltalk
Smalltalk
Object subclass: #Animal instanceVariableNames: ' ' "* space separated list of names *" classVariableNames: ' ' poolDictionaries: ' ' category: ' ' !   "* declare methods here, separated with '!' *" "* !Animal methodsFor: 'a category'! *" "* methodName *" "* method body! !"   !Animal subclass: #Dog "* etc...
Give a code snippet in #Smalltalk This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent t...
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 ...
#Elixir
Elixir
defmodule AKS do def iterate(f, x), do: fn -> [x | iterate(f, f.(x))] end   def take(0, _lazy), do: [] def take(n, lazy) do [value | next] = lazy.() [value | take(n-1, next)] end   def pascal, do: iterate(fn row -> [1 | sum_adj(row)] end, [1])   defp sum_adj([_] = l), do: l defp sum_adj([a, b | _]...
Give a code snippet in #Elixir 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Ada
Ada
with Ada.Text_IO; procedure Program is Comment_Characters : String := "#;"; begin loop declare Line : String := Ada.Text_IO.Get_Line; begin exit when Line'Length = 0; Outer_Loop : for I in Line'Range loop for J in Comment_Characters'Range loop if Comment_Characters(J) = Line(I) then...
Give a code snippet in #Ada Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whi...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#RATFOR
RATFOR
    # Program to overwrite an existing file   open(11,FILE="file.txt") 101 format(A) write(11,101) "Hello World" close(11)   end  
Give a code snippet in #RATFOR Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#Nim
Nim
import math, complex   proc meanAngle(deg: openArray[float]): float = var c: Complex[float] for d in deg: c += rect(1.0, degToRad(d)) radToDeg(phase(c / float(deg.len)))   echo "The 1st mean angle is: ", meanAngle([350.0, 10.0]), " degrees" echo "The 2nd mean angle is: ", meanAngle([90.0, 180.0, 270.0, 360.0]...
Give a code snippet in #Nim When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first readin...
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...
#GAP
GAP
CollatzSequence := function(n) local v; v := [ n ]; while n > 1 do if IsEvenInt(n) then n := QuoInt(n, 2); else n := 3*n + 1; fi; Add(v, n); od; return v; end;   CollatzLength := function(n) local m; m := 1; while n > 1 do if IsEvenInt(n) then n := QuoInt(n, 2); ...
Give a code snippet in #GAP 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Perl
Perl
print join('.', split /,/, 'Hello,How,Are,You,Today'), "\n";
Give a code snippet in #Perl Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks rel...
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...
#Robotic
Robotic
  set "$string" to "" if "$string.length" = 0 then "empty" * "Not an empty string." end   : "empty" * "Empty string" end  
Give a code snippet in #Robotic 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. O...
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...
#Avail
Avail
Print: "0b11001101 = " ++ “0b11001101”; Print: "0o755 = " ++ “0o755”; Print: "0xDEADBEEF = " ++ “0xDEADBEEF”;
Give a code snippet in #Avail 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/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...
#X86-64_Assembly
X86-64 Assembly
  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Linux Build: ;; $ uasm -elf64 mexec.asm ;; $ gcc -o mexec mexec.o -no-pie ;; With MUSL libc ;; $ musl-gcc -o mexec mexec.o -e main -nostartfiles -no-pie ;; ;; Windows Build: ;; $ uasm64 -win64 mexec.asm ;; $ link /machine:x64 ...
Give a code snippet in #X86-64_Assembly 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 follo...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Ol
Ol
  (filter even? '(1 2 3 4 5 6 7 8 9 10))  
Give a code snippet in #Ol Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#Swift
Swift
public func mianChowla(n: Int) -> [Int] { var mc = Array(repeating: 0, count: n) var ls = [2: true] var sum = 0   mc[0] = 1   for i in 1..<n { var lsx = [Int]()   jLoop: for j in (mc[i-1]+1)... { mc[i] = j   for k in 0...i { sum = mc[k] + j   if ls[sum] ?? false { ...
Give a code snippet in #Swift The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwis...
christopher/rosetta-code
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encod...
#REXX
REXX
/*REXX pgm reads fixed─length 80 byte records; reverses each record, displays to term. */ iFID= 'FIXEDLEN.TXT' /*the file's filename (used for input).*/ call charin iFID, 1, 0 /*open the file, point rec pointer to 1*/ ...
Give a code snippet in #REXX Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had ...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#RLaB
RLaB
  >> x = rand(2,4) 0.707213207 0.275298961 0.396757763 0.232312312 0.215619868 0.207078017 0.565700032 0.666090571 >> sin(x) 0.649717845 0.271834652 0.386430003 0.230228332 0.213952984 0.205601224 0.536006923 0.617916954  
Give a code snippet in #RLaB Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#M2000_Interpreter
M2000 Interpreter
  module checkit { Dim Base 1, a(6, 6), b(6) a(1,1)= 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 1.00, 3.14, 9.87, 31.01, 97.41, 306.02 \\ remove \\ to feed nex...
Give a code snippet in #M2000_Interpreter Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Kotlin
Kotlin
// version 1.0.6   import java.io.File   fun main(args: Array<String>) { val filePaths = arrayOf("input.txt", "c:\\input.txt", "zero_length.txt", "`Abdu'l-Bahá.txt") val dirPaths = arrayOf("docs", "c:\\docs") for (filePath in filePaths) { val f = File(filePath) println("$filePath ${if (f.ex...
Give a code snippet in #Kotlin 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 wi...
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...
#Run_BASIC
Run BASIC
for i = 1 to 9 ' get numbers 1 to 9 n(i) = i next i numShuffles = 3 ' ---------------------------------- ' shuffle numbers ' ---------------------------------- for i = 1 to 9 * numShuffles i1 = int(rnd(1)*9) + 1 i2 = int(rnd(1)*9) + 1 h2 = n(i1) n(i1) = n(i2) n(i2) = h2 next i   for i = 1 to 9 a$ = a$ + str$(...
Give a code snippet in #Run_BASIC 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. Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_identity
Euler's identity
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, Euler's identity is the equality: ...
#Rust
Rust
use std::f64::consts::PI;   extern crate num_complex; use num_complex::Complex;   fn main() { println!("{:e}", Complex::new(0.0, PI).exp() + 1.0); }
Give a code snippet in #Rust This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, Euler's identity i...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Pascal
Pascal
program shortcircuit(output);   function a(value: boolean): boolean; begin writeln('a(', value, ')'); a := value end;   function b(value:boolean): boolean; begin writeln('b(', value, ')'); b := value end;   procedure scandor(value1, value2: boolean); var result: boolean; begin {and} if a(value1) ...
Give a code snippet in #Pascal Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable re...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Clojure
Clojure
(def precedence '{* 0, / 0 + 1, - 1})   (defn order-ops "((A x B) y C) or (A x (B y C)) depending on precedence of x and y" [[A x B y C & more]] (let [ret (if (<= (precedence x) (precedence y)) (list (list A x B) y C) (list A x (list B y C)))] (if more (recur (concat ret more))...
Give a code snippet in #Clojure 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid...
#Nim
Nim
import random, sequtils, strformat, strscans, strutils   const LMargin = 4   type   Cell = object isMine: bool display: char   Grid = seq[seq[Cell]]   Game = object grid: Grid mineCount: Natural minesMarked: Natural isOver: bool     proc initGame(m, n: Positive): Game = result.grid = new...
Give a code snippet in #Nim There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordin...
christopher/rosetta-code
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ...
#C
C
#include <stdio.h> #include <stdlib.h>   size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else {...
Give a code snippet in #C You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\m...
#F.23
F#
let rec r2cf n d = if d = LanguagePrimitives.GenericZero then [] else let q = n / d in q :: (r2cf d (n - q * d))   [<EntryPoint>] let main argv = printfn "%A" (r2cf 1 2) printfn "%A" (r2cf 3 1) printfn "%A" (r2cf 23 8) printfn "%A" (r2cf 13 11) printfn "%A" (r2cf 22 7) printfn "%A" (r2c...
Give a code snippet in #F.23 Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c...
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#Ring
Ring
  nr = 1000 num = 0 for n = 1 to nr sum = 0 for m = 1 to len(string(n)) sum += pow(number(substr(string(n),m,1)),2) if sum = 89 num += 1 see "" + n + " " + sum + nl ok next next see "Total under 1000 is : " + num + nl  
Give a code snippet in #Ring If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lamb...
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 |...
#Python
Python
x = int(raw_input("Number 1: ")) y = int(raw_input("Number 2: "))   print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) # or x // y for newer python versions. # truncates towards negative infinity print "Remaind...
Give a code snippet in #Python 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/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 algor...
#11l
11l
F combsort(&input) V gap = input.len V swaps = 1B L gap > 1 | swaps gap = max(1, Int(gap / 1.25)) swaps = 0B L(i) 0 .< input.len - gap V j = i + gap I input[i] > input[j] swap(&input[i], &input[j]) swaps = 1B   V y = [88, 18, 31, 44, 4, 0, 8, 81, 14, ...
Give a code snippet in #11l Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 sor...
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...
#Python
Python
>>> def accumulator(sum): def f(n): f.sum += n return f.sum f.sum = sum return f   >>> x = accumulator(1) >>> x(5) 6 >>> x(2.3) 8.3000000000000007 >>> x = accumulator(1) >>> x(5) 6 >>> x(2.3) 8.3000000000000007 >>> x2 = accumulator(3) >>> x2(5) 8 >>> x2(3.3) 11.300000000000001 >>> x(0) 8.3000000000000007 ...
Give a code snippet in #Python 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/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#Go
Go
package main   import ( "fmt" "unicode" )   const ( lcASCII = "abcdefghijklmnopqrstuvwxyz" ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" )   func main() { fmt.Println("ASCII lower case:") fmt.Println(lcASCII) for l := 'a'; l <= 'z'; l++ { fmt.Print(string(l)) } fmt.Println()   fmt.Println("\nASCII upper case:") f...
Give a code snippet in #Go Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task req...
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...
#Julia
Julia
const sequence = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" * "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" * "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" * "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" * "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" * "TCAGTCCCAATGTGCGGGGTTTCTTT...
Give a code snippet in #Julia Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAAT...
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...
#Oz
Oz
declare proc {Shuffle Arr} Low = {Array.low Arr} High = {Array.high Arr} in for I in High..Low;~1 do J = Low + {OS.rand} mod (I - Low + 1) OldI = Arr.I in Arr.I := Arr.J Arr.J := OldI end end   X = {Tuple.toArray unit(0 1 2 3 4 5 6 7 8 9)} in {Show {Array.toRecord un...
Give a code snippet in #Oz The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Nim
Nim
import strutils   let text = """---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I   ... elided paragraph last ...   Frost Robert -----------------------"""   proc reversed*[T](a: openArray[T], first, last: int):...
Give a code snippet in #Nim Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces...
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
#Action.21
Action!
PROC Test(BYTE v) PrintF("Variable v has value %B%E",v) IF v THEN PrintE("Condition IF v is satisfied.") ELSE PrintE("Condition IF v is not satisfied.") FI IF v=0 THEN PrintE("Condition IF v=0 is satisfied.") ELSE PrintE("Condition IF v=0 is not satisfied.") FI IF v<>0 THEN PrintE("C...
Give a code snippet in #Action.21 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/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#D
D
import std.stdio;   class Foo { // abstract methods can have an implementation for // use in super calls. abstract void foo() { writeln("Test"); } }   interface Bar { void bar();   // Final interface methods are allowed. final int spam() { return 1; } }   class Baz : Foo, Bar { // Su...
Give a code snippet in #D Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations a...
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#Sidef
Sidef
module LCG {   # Creates a linear congruential generator and remembers the initial seed. class Common(r) { has seed = r }   # LCG::Berkeley generates 31-bit integers using the same formula # as BSD rand(). class Berkeley < Common { method rand { self.r = ((1103515245 * self.r + 12345) & 0x7ff...
Give a code snippet in #Sidef The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r...
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...
#Nim
Nim
{.checks: off, optimization: speed.} # Checks are deactivated and code is generated for speed.   # Define a type Color as pure which implies that value names are declared in their own scope # and may/should be accessed with their type qualifier (as Color.Red). type Color {.pure.} = enum Red, Green, Blue   # Declare ...
Give a code snippet in #Nim 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 h...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Java
Java
System.getenv("HOME") // get env var System.getenv() // get the entire environment as a Map of keys to values
Give a code snippet in #Java Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#FreeBASIC
FreeBASIC
#define FIN 255 'eof is already a reserved word #include "crt/stdio.bi" 'provides the C functions getchar and putchar dim as ubyte char do char = getchar() if char = FIN then exit do else putchar(char) loop
Give a code snippet in #FreeBASIC Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
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...
#Logo
Logo
to powerset :set if empty? :set [output [[]]] localmake "rest powerset butfirst :set output sentence map [sentence first :set ?] :rest  :rest end   show powerset [1 2 3] [[1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []]
Give a code snippet in #Logo 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/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#ATS
ATS
  (* ****** ****** *) // #include "share/atspre_define.hats" // defines some names #include "share/atspre_staload.hats" // for targeting C #include "share/HATS/atspre_staload_libats_ML.hats" // for ... // (* ****** ****** *) // extern fun Zig_zag_matrix(n: int): void // (* ****** ****** *)   fun max(a: int, b: int): in...
Give a code snippet in #ATS Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encod...
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...
#PARI.2FGP
PARI/GP
stripchars(s, bad)={ bad=Set(Vec(Vecsmall(bad))); s=Vecsmall(s); my(v=[]); for(i=1,#s,if(!setsearch(bad,s[i]),v=concat(v,s[i]))); Strchr(v) }; stripchars("She was a soul stripper. She took my heart!","aei")
Give a code snippet in #PARI.2FGP 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 ...
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 ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program ackermann64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include ".....
Give a code snippet in #AArch64_Assembly 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/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Smalltalk
Smalltalk
'file.txt' asFilename contents:'Hello World'
Give a code snippet in #Smalltalk Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#Factor
Factor
USE: locals [let 1 :> Δ! Δ 1 + Δ! Δ . ]
Give a code snippet in #Factor Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Visual_Basic_.NET
Visual Basic .NET
  Imports System.Linq Function ValidLuhn(value As String) Return value.Select(Function(c, i) (AscW(c) - 48) << ((value.Length - i - 1) And 1)).Sum(Function(n) If(n > 9, n - 9, n)) Mod 10 = 0 End Function Sub Main() Console.WriteLine(ValidLuhn("49927398716")) Console.WriteLine(Val...
Give a code snippet in #Visual_Basic_.NET The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Elixir
Elixir
  defmodule Csv do defstruct header: "", data: "", separator: ","   def from_file(path) do [header | data] = path |> File.stream! |> Enum.to_list |> Enum.map(&String.trim/1)    %Csv{ header: header, data: data } end   def sums_of_rows(csv) do Enum.map(csv.data, fn (row) -> sum_of_row(row,...
Give a code snippet in #Elixir CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, cha...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Yabasic
Yabasic
w = 256   open window w, w   For x = 0 To w-1 For y = 0 To w-1 r =and(xor(x, y), 255) color r, and(r*2, 255), and(r*3, 255) dot x, y Next Next
Give a code snippet in #Yabasic Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#Tcl
Tcl
package require Tcl 8.6; # For easy scanning of binary   # The strings to parse set dec1 "0123459" set hex2 "abcf123" set oct3 "7651" set bin4 "101011001"   # Parse the numbers scan $dec1 "%d" v1 scan $hex2 "%x" v2 scan $oct3 "%o" v3 scan $bin4 "%b" v4; # Only 8.6-specific operation; others work in all versions   # Pr...
Give a code snippet in #Tcl It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of su...
christopher/rosetta-code
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#Vlang
Vlang
import math   fn min_of(x int, y int) int { if x < y { return x } return y }   fn throw_die(n_sides int, n_dice int, s int, mut counts []int) { if n_dice == 0 { counts[s]++ return } for i := int(1); i <= n_sides; i++ { throw_die(n_sides, n_dice - 1, s + i, mut cou...
Give a code snippet in #Vlang Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player...
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)
#Arc
Arc
  (= leap? (fn (year) (if (and (is 0 (mod year 4)) (isnt 0 (mod year 100))) year (unless (< 0 (+ (mod year 100) (mod year 400))) year))))  
Give a code snippet in #Arc 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/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#mIRC_Scripting_Language
mIRC Scripting Language
echo -ag $file(input.txt).size bytes echo -ag $file(C:\input.txt).size bytes
Give a code snippet in #mIRC_Scripting_Language Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#NetLogo
NetLogo
;; Division by zero detection using CAREFULLY ;; The CAREFULLY clause exists in NetLogo since version 2.0 ;; In prior versions of NetLogo, you must examine the divisor prior to performing the division. ;; The variables result, a, and b must all be previously created global, local, or agent -own'd variables. ;; NetL...
Give a code snippet in #NetLogo Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Print[StringJoin[ RandomChoice[ Select[Union[ Permutations[{"\[WhiteKing]", "\[WhiteQueen]", "\[WhiteRook]", "\[WhiteRook]", "\[WhiteBishop]", "\[WhiteBishop]", "\[WhiteKnight]", "\[WhiteKnight]"}]], MatchQ[#, {___, "\[WhiteRook]", ___, "\[WhiteKing]", ___, "\[WhiteRook]",...
Give a code snippet in #Mathematica_.2F_Wolfram_Language 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, a...
christopher/rosetta-code
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#FreeBASIC
FreeBASIC
Const max_N = 20, max_ciclos = 1000000   Function Factorial(Byval N As Integer) As Double Dim As Double d: d = 1 If N = 0 Then Factorial = 1: Exit Function While (N > 1) d *= N N -= 1 Wend Factorial = d End Function   Function Analytical(N As Integer) As Double Dim As Double i, s...
Give a code snippet in #FreeBASIC Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a num...
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
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 ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' Although it's possible to create generic sorting routines using macros in FreeBASIC ' here we will just use Integer arrays.   Sub quicksort(a() As Integer, first As Integer, last As Integer) Dim As Integer length = last - first + 1 If length < 2 Then Return Dim pivot As Integer = a(first + ...
Give a code snippet in #FreeBASIC 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Modula-3
Modula-3
GENERIC INTERFACE GenericSwap(Elem);   PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T);   END GenericSwap.
Give a code snippet in #Modula-3 Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides generi...
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 ...
#Ada
Ada
with Ada.Text_IO;   procedure Strip_ASCII is   Full: String := 'a' & Character'Val(11) & 'b' & Character'Val(166) & 'c' & Character'Val(127) & Character'Val(203) & Character'Val(202) & "de"; -- 5 ordinary characters ('a' .. 'e') -- 2 control characters (11, 127); note that...
Give a code snippet in #Ada 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/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...
#Picat
Picat
go => foreach(I in 0..2**5-1) G = gray_encode1(I), E = gray_decode1(G), printf("%2d %6w %2d %6w %6w %2d\n",I,I.to_binary_string, G, G.to_binary_string, E.to_binary_string, E) end, nl, println("Checking 2**13...
Give a code snippet in #Picat 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity...
#Scala
Scala
$ syntax expr: .(). + .() is -> 7;
Give a code snippet in #Scala This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   p...
christopher/rosetta-code
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Lua
Lua
  target, board, moves, W, H = {}, {}, 0, 3, 3   function getIndex( i, j ) return i + j * W - W end   function flip( d, r ) function invert( a ) if a == 1 then return 0 end return 1 end local idx if d == 1 then for i = 1, W do idx = getIndex( i, r ) board[idx] = invert( board...
Give a code snippet in #Lua The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move)...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#Go
Go
package main   import "fmt"   func pernicious(w uint32) bool { const ( ff = 1<<32 - 1 mask1 = ff / 3 mask3 = ff / 5 maskf = ff / 17 maskp = ff / 255 ) w -= w >> 1 & mask1 w = w&mask3 + w>>2&mask3 w = (w + w>>4) & maskf return 0xa08a28ac>>(w*maskp>>24)&1...
Give a code snippet in #Go A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,  ...
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...
#Nemerle
Nemerle
using System; using System.Console;   module Maprange { Maprange(a : double * double, b : double * double, s : double) : double { def (a1, a2) = a; def (b1, b2) = b;   b1 + (((s - a1) * (b2 - b1))/(a2 - a1)) }   Main() : void { foreach (i in [0 .. 10]) WriteLine(...
Give a code snippet in #Nemerle 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#PicoLisp
PicoLisp
(let N 1024 (while (gt0 N) (println N) (setq N (/ N 2)) ) )
Give a code snippet in #PicoLisp Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Down...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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 ...
#Haskell
Haskell
import Data.List (sort)   sortedTriple :: Ord a => (a, a, a) -> (a, a, a) sortedTriple (x, y, z) = let [a, b, c] = sort [x, y, z] in (a, b, c)   sortedListfromTriple :: Ord a => (a, a, a) -> [a] sortedListfromTriple (x, y, z) = sort [x, y, z]   -- TEST -------------------------------------------------------...
Give a code snippet in #Haskell 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/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#D
D
import std.stdio, std.algorithm, std.string;   bool canMakeWord(in string word, in string[] blocks) pure /*nothrow*/ @safe { auto bs = blocks.dup; outer: foreach (immutable ch; word.toUpper) { foreach (immutable block; bs) if (block.canFind(ch)) { bs = bs.remove(bs.countUntil...
Give a code snippet in #D ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#NewLISP
NewLISP
;; local file (load "file.lsp")   ;; URLs (both http:// and file:// URLs are supported) (load "http://www.newlisp.org/code/modules/ftp.lsp")
Give a code snippet in #NewLISP Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
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 |...
#jq
jq
# startswith/1 is boolean: "abc" | startswith("ab") #=> true
Give a code snippet in #jq Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Con...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#AWK
AWK
#!/usr/bin/awk -f   /.ei/ {nei+=cnt($3)} /cei/ {cei+=cnt($3)}   /.ie/ {nie+=cnt($3)} /cie/ {cie+=cnt($3)}   function cnt(c) { if (c<1) return 1; return c; }   END { printf("cie: %i\nnie: %i\ncei: %i\nnei: %i\n",cie,nie-cie,cei,nei-cei); v = v2 = ""; if (nie < 3 * cie) { v =" not"; } print "I before E when no...
Give a code snippet in #AWK The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Haskell
Haskell
import Data.Array.Unboxed   type Grid = UArray (Int,Int) Bool -- The grid is indexed by (y, x).   life :: Int -> Int -> Grid -> Grid {- Returns the given Grid advanced by one generation. -} life w h old = listArray b (map f (range b)) where b@((y1,x1),(y2,x2)) = bounds old f (y, x) = ( c && (n == 2 || n ...
Give a code snippet in #Haskell The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Picat
Picat
main => L=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1], Map3 = new_map([p=3]), Map5 = new_map([p=5]), foreach(N in L) printf("n: %-2d sma3: %-17w sma5: %-17w\n",N, sma(N,Map3), sma(N,Map5)) end.   sma(N,Map) = Average => Stream = Map.get(stream,[]) ++ [N], if Stream.len > Map.get(p) then Stream := Stream.tail ...
Give a code snippet in #Picat Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to rais...
#Seed7
Seed7
$ include "seed7_05.s7i";   const EXCEPTION: U0 is enumlit; const EXCEPTION: U1 is enumlit;   const proc: baz (in integer: num) is func begin if num = 1 then raise U0; else raise U1; end if; end func;   const proc: bar (in integer: num) is func begin baz(num); end func;   const proc:...
Give a code snippet in #Seed7 Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arran...
christopher/rosetta-code
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#Phix
Phix
with javascript_semantics constant X=1, Y=2, bCoeff=7, INF = 1e300*1e300 type point(object pt) return sequence(pt) and length(pt)=2 and atom(pt[X]) and atom(pt[Y]) end type function zero() point pt = {INF, INF} return pt end function function is_zero(point p) return p[X]>1e20 or p[X]<-1e20 end fun...
Give a code snippet in #Phix Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nu...
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
#Crystal
Crystal
class String def sum_digits(base : Int) : Int32 self.chars.reduce(0) { |acc, c| value = c.to_i(base) acc += value } end end   puts("1".sum_digits 10) puts("1234".sum_digits 10) puts("fe".sum_digits 16) puts("f0e".sum_digits 16)
Give a code snippet in #Crystal 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/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...
#11l
11l
F maprange(a, b, s) R b[0] + (Float(s - a[0]) * (b[1] - b[0]) / (a[1] - a[0]))   L(s) 0..10 print(‘#2 maps to #.’.format(s, maprange((0, 10), (-1, 0), s)))
Give a code snippet in #11l 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 map...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#QBasic
QBasic
DECLARE FUNCTION Fibonacci! (num!)   PRINT Fibonacci(20) PRINT Fibonacci(30) PRINT Fibonacci(-10) PRINT Fibonacci(10) END   FUNCTION Fibonacci (num) IF num < 0 THEN PRINT "Invalid argument: "; Fibonacci = num END IF   IF num < 2 THEN Fibonacci = num ELSE Fibonacci = Fibonacci(num - 1) + Fibonacc...
Give a code snippet in #QBasic While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwan...
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#Scala
Scala
import java.nio.ByteOrder   object ShowByteOrder extends App { println(ByteOrder.nativeOrder()) println(s"Word size: ${System.getProperty("sun.arch.data.model")}") println(s"Endianness: ${System.getProperty("sun.cpu.endian")}") }
Give a code snippet in #Scala Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#BASIC
BASIC
10 DEFINT A-Z 20 N = 4 30 W = 3^(N-1) 40 S = W 50 L$ = STRING$(W, "#") 60 PRINT L$ 70 IF S = 1 THEN END 80 S = S\3 90 P = 1 100 IF P >= W-S GOTO 60 110 P = P+S 120 MID$(L$,P,S) = SPACE$(S) 130 P = P+S 140 GOTO 100
Give a code snippet in #BASIC Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted...
#REXX
REXX
/*REXX pgm finds primes whose values in other bases (2──►36) have the most diff. bases. */ parse arg widths . /*obtain optional argument from the CL.*/ if widths=='' | widths=="," then widths= 5 /*Not specified? Then use the default.*/ call genP ...
Give a code snippet in #REXX Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different...
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...
#Objeck
Objeck
bundle Default { class VectorProduct { function : Main(args : String[]) ~ Nil { a := Vector3D->New(3.0, 4.0, 5.0); b := Vector3D->New(4.0, 3.0, 5.0); c := Vector3D->New(-5.0, -12.0, -13.0);   a->Dot(b)->Print(); a->Cross(b)->Print(); a->ScaleTrip(b, c)->Print(); a->Vecto...
Give a code snippet in #Objeck 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 n...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Lua
Lua
require("LuaXML") local dom = xml.new("root") local element = xml.new("element") table.insert(element, "Some text here") dom:append(element) dom:save("dom.xml")
Give a code snippet in #Lua Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h>   char *sortedWord(const char *word, char *wbuf) { char *p1, *p2, *endwrd; char t; int swaps;   strcpy(wbuf, word); endwrd = wbuf+strlen(wbuf); do { swaps = 0; p1 = wbuf; p2 = endwrd-1; ...
Give a code snippet in #C When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them....
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Raku
Raku
class KnapsackItem { has $.volume; has $.weight; has $.value; has $.name;   method new($volume,$weight,$value,$name) { self.bless(:$volume, :$weight, :$value, :$name) } };   my KnapsackItem $panacea .= new: 0.025, 0.3, 3000, "panacea"; my KnapsackItem $ichor .= new: 0.015, 0.2, 1800, "ichor"; my Knaps...
Give a code snippet in #Raku A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25  ...
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
#Oxygene
Oxygene
  <?xml version="1.0" standalone="no"?> <!--*- mode: xml -*--> <!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.24.dtd">   <glade-interface>   <widget class="GtkWindow" id="hworld"> <property name="visible">True</property> <property name="title">Hello World</property> <property name="modal">False<...
Give a code snippet in #Oxygene 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/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PUT$CHAR: PROCEDURE (CH); DECLARE CH BYTE; CALL BDOS(2,CH); END PUT$CHAR; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   PRINT$3: PROCEDURE (N); DECLARE N BYTE; CAL...
Give a code snippet in #PL.2FM Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#PARI.2FGP
PARI/GP
magicsquare(n)=matrix(n,n,i,j,k=i+j*n-n;if(bitand(38505,2^((j-1)%4*4+(i-1)%4)),k,n*n+1-k))
Give a code snippet in #PARI.2FGP A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative example of Currying in a specific la...
#Aime
Aime
ri(list l) { l[0] = apply.apply(l[0]); } curry(object o) { (o.__count - 1).times(ri, list(o)); } main(void) { o_wbfxinteger.curry()(16)(3)(12)(16)(1 << 30); 0; }  
Give a code snippet in #Aime This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative exampl...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#AutoHotkey
AutoHotkey
GUI, add, Edit,Number w50 vUserInput gMakeSure, 0 ; Number Specifies Numbers-only, but other characters can still be pasted in, ; Making our own check necessary. (MakeSure)   GUI, add, Button, gIncrement, Increment ; Instead of an increment button, the UpDown control could be used, but this was not sp...
Give a code snippet in #AutoHotkey Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and ch...
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 ...
#ALGOL_68
ALGOL 68
MODE LOOPINT = INT;   MODE POWMODSTRUCT = LONG INT; PR READ "prelude/pow_mod.a68" PR;   MODE SORTSTRUCT = LONG INT; PR READ "prelude/sort.a68" PR;   MODE GCDSTRUCT = LONG INT; PR READ "prelude/gcd.a68" PR;   PR READ "prelude/iterator.a68" PR;   PROC is prime = (LONG INT p)BOOL: ( p > 1 |#ANDF# ALL((YIELDBOOL yield)...
Give a code snippet in #ALGOL_68 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 ef...
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 ...
#Arturo
Arturo
selectionSort: function [items][ sorted: new [] tmp: new items while [not? empty? tmp][ minIndex: index tmp min tmp 'sorted ++ tmp\[minIndex] remove 'tmp .index minIndex ] return sorted ]   print selectionSort [3 1 2 8 5 7 9 4 6]
Give a code snippet in #Arturo Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#uBasic.2F4tH
uBasic/4tH
Push 5, 4, 3, 2, 1: s = Used() - 1 For x = 0 To s: @(x) = Pop(): Next   Print "Sum is  : "; FUNC(_reduce(0, s, _add)) Print "Difference is : "; FUNC(_reduce(0, s, _subtract)) Print "Product is  : "; FUNC(_reduce(0, s, _multiply)) Print "Maximum is  : "; FUNC(_reduce(0, s, _max)) Print "Minimum is  : "; FUNC...
Give a code snippet in #uBasic.2F4tH Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your langu...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Haskell
Haskell
import Graphics.UI.Gtk import Data.IORef   main :: IO () main = do initGUI window <- windowNew window `onDestroy` mainQuit windowSetTitle window "Simple Windowed App" set window [ containerBorderWidth := 10 ]   hbox <- hBoxNew True 5   set window [ containerChild := hbox ]   lab <- labelNew (Just "There...
Give a code snippet in #Haskell Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#TSE_SAL
TSE SAL
    // library: math: get: greatest: common: divisor <description>greatest common divisor whole numbers. Euclid's algorithm. Recursive version</description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmacdi.s) [<Program>] [<Research>] [kn, ri, s...
Give a code snippet in #TSE_SAL Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greate...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#SNOBOL4
SNOBOL4
  DEFINE("countSubstring(t,s)")   OUTPUT = countSubstring("the three truths","th") OUTPUT = countSubstring("ababababab","abab")    :(END) countSubstring t ARB s = :F(RETURN) countSubstring = countSubstring + 1 :(countSubstring) END 3 2  
Give a code snippet in #SNOBOL4 Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Dyalect
Dyalect
//Static method on a built-in type Integer static func Integer.Div(x, y) { x / y }   //Instance method func Integer.Div(n) { this / n }   print(Integer.Div(12, 3)) print(12.Div(3))
Give a code snippet in #Dyalect In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static o...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Lua
Lua
filename = "NOTES.TXT"   if #arg == 0 then fp = io.open( filename, "r" ) if fp ~= nil then print( fp:read( "*all*" ) ) fp:close() end else fp = io.open( filename, "a+" )   fp:write( os.date( "%x %X\n" ) )   fp:write( "\t" ) for i = 1, #arg do fp:write( arg[i], " " ) end ...
Give a code snippet in #Lua Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT f...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Visual_Basic_.NET
Visual Basic .NET
Module Filter   Sub Main() Dim array() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Dim newEvenArray() As Integer   Console.WriteLine("Current Array:") For Each i As Integer In array Console.WriteLine(i) Next   newEvenArray = filterArrayIntoNewArray(array)...
Give a code snippet in #Visual_Basic_.NET Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#VBA
VBA
  Public Sub BuildHTMLTable() 'simple HTML table, represented as a string matrix "cells" Const nRows = 6 Const nCols = 4 Dim cells(1 To nRows, 1 To nCols) As String Dim HTML As String 'the HTML table Dim temp As String Dim attr As String   ' fill table ' first row with titles cells(1, 1) = "" cells(1, 2) = "X" cells(1,...
Give a code snippet in #VBA Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with ...
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.
#Julia
Julia
using Luxor using Colors using BoundaryValueDiffEq   # constants for differential equations and movie const g = 9.81 const L = 1.0 # pendulum length in meters const bobd = 0.10 # pendulum bob diameter in meters const framerate = 50.0 # intended frame rate/sec c...
Give a code snippet in #Julia 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#BASIC
BASIC
TRUE = 1 : FALSE = 0 NULL = TRUE IF NULL THEN PRINT "NULL" NULL = FALSE IF NOT NULL THEN PRINT "NOT NULL"
Give a code snippet in #BASIC Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your langu...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#Erlang
Erlang
    sdn(N) -> lists:map(fun(S)->length(lists:filter(fun(C)->C-$0==S end,N))+$0 end,lists:seq(0,length(N)-1))==N. gen(M) -> lists:filter(fun(N)->sdn(integer_to_list(N)) end,lists:seq(0,M)).    
Give a code snippet in #Erlang Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when d...
christopher/rosetta-code