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/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#QB64
QB64
_Title "Barnsley Fern" Dim As Integer sw, sh sw = 400: sh = 600 Screen _NewImage(sw, sh, 8)   Dim As Long i, ox, oy Dim As Single sRand Dim As Double x, y, x1, y1, sx, sy sx = 60: sy = 59 ox = 180: oy = 4 Randomize Timer   x = 0 y = 0 For i = 1 To 400000 sRand = Rnd Select Case sRand Case Is < 0.01 ...
Give a code snippet in #QB64 A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#APL
APL
freq←{(⍪∪⍵),+/(∪⍵)∘.⍷⍵}   freq 0 1 2 3 2 3 4 3 4 4 4 0 1 1 1 2 2 3 3 4 4   freq 'balloon' b 1 a 1 l 2 o 2 n 1
Give a code snippet in #APL Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assig...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#bc
bc
/* * Return the _n_th term of the van der Corput sequence. * Uses the current _ibase_. */ define v(n) { auto c, r, s   s = scale scale = 0 /* to use integer division */   /* * c = count digits of n * r = reverse the digits of n */ for (0; n != 0; n /= 10) { c += 1 r = (10 * r) + (n % 10) }   /* mov...
Give a code snippet in #bc When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Cowgol
Cowgol
include "cowgol.coh"; include "strings.coh"; include "malloc.coh";   ############################################################################### ########################## Turing machine definition ########################## ############################################################################### typedef Sym...
Give a code snippet in #Cowgol One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machin...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: brainF (in string: source, inout file: input, inout file: output) is func local var array char: memory is 100000 times '\0;'; var integer: dataPointer is 50000; var integer: instructionPointer is 1; var integer: nestingLevel is 0; begin while instructionPo...
Give a code snippet in #Seed7 Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implem...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Prolog
Prolog
test :- read(Name), atomics_to_string([Name, "= 50, writeln('", Name, "' = " , Name, ")"], String), term_string(Term, String), Term.
Give a code snippet in #Prolog Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Liberty_BASIC
Liberty BASIC
for n =1 to 10000 if perfect( n) =1 then print n; " is perfect." next n   end   function perfect( n) sum =0 for i =1 TO n /2 if n mod i =0 then sum =sum +i end if next i if sum =n then perfect= 1 else perfect =0 end if end function
Give a code snippet in #Liberty_BASIC Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (includin...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Plain_English
Plain English
To run: Start up. Write "Enter the first number: " to the console without advancing. Read a first number from the console. Write "Enter the second number: " to the console without advancing. Read a second number from the console. If the first number is less than the second number, write "Less than!" to the console. If ...
Give a code snippet in #Plain_English 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 Ope...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Swift
Swift
  // Extend the Collection protocol. Any type that conforms to extension where its Element type conforms to Hashable will automatically gain this method. extension Collection where Element: Hashable {   /// Return a Mode of the function, or nil if none exist. func mode() -> Element? { var frequencies = ...
Give a code snippet in #Swift Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if po...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ChineseRemainder[{2, 3, 2}, {3, 5, 7}] 23
Give a code snippet in #Mathematica_.2F_Wolfram_Language Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Yabasic
Yabasic
print " X| 1 2 3 4 5 6 7 8 9 10 11 12" print "---+------------------------------------------------"   for i = 1 to 12 nums$ = right$(" " + str$(i), 3) + "|" for j = 1 to 12 if i <= j then if j >= 1 then nums$ = nums$ + left$(" ", (4 - len(str$(i * j)...
Give a code snippet in #Yabasic Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#Ruby
Ruby
def farey(n, length=false) if length (n*(n+3))/2 - (2..n).sum{|k| farey(n/k, true)} else (1..n).each_with_object([]){|k,a|(0..k).each{|m|a << Rational(m,k)}}.uniq.sort end end   puts 'Farey sequence for order 1 through 11 (inclusive):' for n in 1..11 puts "F(#{n}): " + farey(n).join(", ") end puts 'Numb...
Give a code snippet in #Ruby The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   ...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#Racket
Racket
#lang racket (require srfi/14)   (define 0-char (char->integer #\0)) (define A-char (char->integer #\A))   (define (cusip-value c) (cond [(char-set-contains? char-set:digit c) (- (char->integer c) 0-char)] [(char-set-contains? char-set:upper-case c) (+ 10 (- (char->integer c) A-char))] [(char=...
Give a code snippet in #Racket This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeri...
christopher/rosetta-code
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#BASIC
BASIC
CONST x = 1
Give a code snippet in #BASIC Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
christopher/rosetta-code
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
reduce[x_] := Block[{pairs, unique}, pairs = DeleteCases[ Subsets[Range@ Length@x, {2}], _?(Intersection @@ x[[#]] == {} &)]; unique = Complement[Range@Length@x, Flatten@pairs]; Join[Union[Flatten[x[[#]]]] & /@ pairs, x[[unique]]]] consolidate[x__] := FixedPoint[reduce, {x}]
Give a code snippet in #Mathematica.2FWolfram_Language Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#APL
APL
median←{v←⍵[⍋⍵]⋄.5×v[⌈¯1+.5×⍴v]+v[⌊.5×⍴v]} ⍝ Assumes ⎕IO←0
Give a code snippet in #APL Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#VHDL
VHDL
LIBRARY std; USE std.TEXTIO.all;   entity test is end entity test;   architecture beh of test is begin process variable line_out : line; begin write(line_out, string'("Hello world!")); writeline(OUTPUT, line_out); wait; -- needed to stop the execution end process; end architecture beh;
Give a code snippet in #VHDL Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error  ...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#AutoIt
AutoIt
  #include <array.au3> $doors = 100   ;door array, 0 = closed, 1 = open Local $door[$doors +1]   For $ii = 1 To $doors For $i = $ii To $doors Step $ii $door[$i] = Not $door[$i] next Next   ;display to screen For $i = 1 To $doors ConsoleWrite (Number($door[$i])& " ") If Mod($i,10) = 0 Then ConsoleWrite(@CRLF) Next...
Give a code snippet in #AutoIt There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ....
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Pascal
Pascal
program example(output);   function first(function f(x: real): real): real; begin first := f(1.0) + 2.0; end;   function second(x: real): real; begin second := x/2.0; end;   begin writeln(first(second)); end.
Give a code snippet in #Pascal Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Icon_and_Unicon
Icon and Unicon
link hexcvt,printf   procedure main() s := "The quick brown fox jumps over the lazy dog" a := "414FA339" printf("crc(%i)=%s - implementation is %s\n", s,r := crc32(s),if r == a then "correct" else "in error") end   procedure crc32(s) #: return crc-32 (ISO 3309, ITU-T V.42, Gzip, PNG) of s static...
Give a code snippet in #Icon_and_Unicon Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main()   every r := &pi | -r | 100-r do { write(r," <=== no printf") every p := "|%r|" | "|%9.3r|" | "|%-9.3r|" | "|%0.3r|" | "|%e|" | "|%d|" do write(sprintf(p,r)," <=== sprintf ",p) } end
Give a code snippet in #Icon_and_Unicon Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#zkl
zkl
fcn quadratic(a,b,c){ b=b.toFloat(); println("Roots of a quadratic function %s, %s, %s".fmt(a,b,c)); d,a2:=(b*b - 4*a*c), a+a; if(d>0){ sd:=d.sqrt(); println(" the real roots are %s and %s".fmt((-b + sd)/a2,(-b - sd)/a2)); } else if(d==0) println(" the single root is ",-b/a2); else{ ...
Give a code snippet in #zkl This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#SVG
SVG
  <svg viewBox="0 0 100 100" stroke="#000" stroke-width="0.3"> <g> <line x1="50" y1="50" x2="54" y2="50"></line> <animateTransform attributeName="transform" type="rotate" from="-120 50 50" to="240 50 50" dur="2400s" repeatCount="indefinite"></animateTransform> <g> <line x1="54" y1="50" x2="58.16" y2...
Give a code snippet in #SVG A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the ang...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Sidef
Sidef
func group(str) { gather { while (var match = (str =~ /((.)\g{-1}*)/g)) { take(match[0]) } } }   say group(ARGV[0] \\ 'gHHH5YY++///\\').join(', ')
Give a code snippet in #Sidef Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Factor
Factor
MACRO: variadic-print ( n -- quot ) [ print ] n*quot ;
Give a code snippet in #Factor Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#J
J
array1 =: 1 2 3 array2 =: 4 5 6 array1 , array2 1 2 3 4 5 6
Give a code snippet in #J Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Bracmat
Bracmat
( 1:?seed & ( rand = . mod$(!seed*1103515245+12345.4294967296):?seed & mod$(div$(!seed.65536).32768) ) & ( rangerand = from to b h i m n r length .  !arg:(?from,?to) & !to+-1*!from+1:?m & @(!m:? [?length) & div$(!length+1.2)+1:?h & 100^mod$(!h.!m):?b & whl ...
Give a code snippet in #Bracmat This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin pri...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Julia
Julia
using Dates   fname, _ = mktemp()   println("The modification time of $fname is ", Dates.unix2datetime(mtime(fname))) println("\nTouch this file.") touch(fname) println("The modification time of $fname is now ", Dates.unix2datetime(mtime(fname)))
Give a code snippet in #Julia Task Get and set the modification time of a file.
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...
#F.23
F#
  //Produce a zig zag matrix - Nigel Galloway: April 7th., 2015 let zz l a = let N = Array2D.create l a 0 let rec gng (n, i, g, e) = N.[n,i] <- g match e with | _ when i=a-1 && n=l-1 -> N | 1 when n = l-1 -> gng (n, i+1, g+1, 2) | 2 when i = a-1 -> gng (n+1, i, g+1, 1) | 1 when...
Give a code snippet in #F.23 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 enco...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#C.2B.2B
C++
#include <iostream> #include <numeric>   int main() { int a[] = { 1, 3, -5 }; int b[] = { 4, -2, -1 };   std::cout << std::inner_product(a, a + sizeof(a) / sizeof(a[0]), b, 0) << std::endl;   return 0; }
Give a code snippet in #C.2B.2B Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#PHP
PHP
$radians = M_PI / 4; $degrees = 45 * M_PI / 180; echo sin($radians) . " " . sin($degrees); echo cos($radians) . " " . cos($degrees); echo tan($radians) . " " . tan($degrees); echo asin(sin($radians)) . " " . asin(sin($radians)) * 180 / M_PI; echo acos(cos($radians)) . " " . acos(cos($radians)) * 180 / M_PI; echo atan(t...
Give a code snippet in #PHP Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluat...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#Sidef
Sidef
func quicksort (a) { a.len < 2 && return(a); var p = a.pop_rand; # to avoid the worst cases __FUNC__(a.grep{ .< p}) + [p] + __FUNC__(a.grep{ .>= p}); }
Give a code snippet in #Sidef 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. 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 Generate and show a maze, using the simple Depth...
#Ada
Ada
generic Height : Positive; Width : Positive; package Mazes is   type Maze_Grid is private;   procedure Initialize (Maze : in out Maze_Grid);   procedure Put (Item : Maze_Grid);   private   type Directions is (North, South, West, East);   type Cell_Walls is array (Directions) of Boolean; type Cel...
Give a code snippet in #Ada This page uses content from Wikipedia. The original article was at Maze generation algorithm. 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 Generate and show a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PureBasic
PureBasic
#MAXNUM=100   Dim MyData(Random(15)+5) Global Dim Abacus(0,0)   Declare BeadSort(Array InData(1)) Declare PresentData(Array InData(1))   If OpenConsole() Define i ;- Generate a random array For i=0 To ArraySize(MyData()) MyData(i)=Random(#MAXNUM) Next i PresentData(MyData()) ; ;- Sort the array Bead...
Give a code snippet in #PureBasic 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/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#FOCAL
FOCAL
01.10 F K=1,5;D 3 01.20 Q   02.10 S N=I;S P=1;S G=0 02.20 S P=P+1 02.30 I (K-G)2.7,2.7;I (N-P*P)2.7 02.40 S Z=FITR(N/P) 02.50 I (Z*P-N)2.2 02.60 S N=Z;S G=G+1;G 2.4 02.70 I (1-N)2.8;R 02.80 S G=G+1   03.10 T "K",%1,K,":" 03.20 S I=2;S C=0 03.30 D 2;I (G-K)3.6,3.4,3.6 03.40 T " ",%3,I 03.50 S C=C+1 03.60 S I=I+1 03.70 I...
Give a code snippet in #FOCAL A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Exam...
#Prolog
Prolog
/* * Solver */ solve([A|T]) :- numlist(1,81,S), select(A,S,R), solve_([A|T],R).   solve_([_],[]). solve_([A,B|T],R) :- move(A,B), select(B,R,Rt), solve_([B|T],Rt).   move(A,B) :- lr(A,B) ; lr(B,A) ; ud(A,B) ; ud(B,A).   % create the left-right mapping rules at compile time term_expansion(lr(0,0),LrList) :- f...
Give a code snippet in #Prolog Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end ...
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#bc
bc
$ bc # trying for negative zero -0 0 # trying to underflow to negative zero -1 / 2 0 # trying for NaN (not a number) 0 / 0 dc: divide by zero 0 sqrt(-1) dc: square root of negative number dc: stack empty dc: stack empty
Give a code snippet in #bc The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#QB64
QB64
#include<math.h> //save as inf.h double inf(void){ return HUGE_VAL; }
Give a code snippet in #QB64 Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Self_numbers
Self numbers
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. You should either confirm or d...
#Go
Go
package main   import ( "fmt" "time" )   func sumDigits(n int) int { sum := 0 for n > 0 { sum += n % 10 n /= 10 } return sum }   func max(x, y int) int { if x > y { return x } return y }   func main() { st := time.Now() count := 0 var selfs []int ...
Give a code snippet in #Go A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. Yo...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#MATLAB_.2F_Octave
MATLAB / Octave
character = char(asciiNumber)
Give a code snippet in #MATLAB_.2F_Octave Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Uni...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#J
J
load 'viewmat' size=. 2{.".wd'qm' NB. J6 size=. getscreenwh_jgtk_ '' NB. J7 'rgb'viewmat (4<.@%~{:size)# ({.size) $&> 1 2 3 4#&.> <256#.255*#:i.8
Give a code snippet in #J The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta...
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...
#MATLAB_.2F_Octave
MATLAB / Octave
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0);   fid = fopen('data.out.csv','w+'); fprintf(fid,'%s,sum\n',header); for k=1:size(X,1), fprintf(fid,"%i,",X(k,:)); fprintf(fid,"%i\n",sum(X(k,:))); end; fclose(fid);
Give a code snippet in #MATLAB_.2F_Octave 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 CS...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Julia
Julia
  function isltruncprime{T<:Integer}(n::T, base::T=10) isprime(n) || return false p = n f = prevpow(base, p) while 1 < f (d, p) = divrem(p, f) isprime(p) || return false d != 0 || return false f = div(f, base) end return true end   function isrtruncprime{T<:Intege...
Give a code snippet in #Julia A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatab...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Oz
Oz
declare %% maps items to pairs of Weight(hectogram) and Value Problem = knapsack('map':9#150 'compass':13#35 'water':153#200 'sandwich':50#160 'glucose':15#60 'tin':68#45 'banana':27#60 ...
Give a code snippet in #Oz A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Sidef
Sidef
var langs = %w(ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart visualfoxpro mirc make javascript cpp sdlbasic...
Give a code snippet in #Sidef Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
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 ...
#Nim
Nim
from strutils import parseInt   proc ackermann(m, n: int64): int64 = if m == 0: result = n + 1 elif n == 0: result = ackermann(m - 1, 1) else: result = ackermann(m - 1, ackermann(m, n - 1))   proc getNumber(): int = try: result = stdin.readLine.parseInt except ValueError: echo "An integer,...
Give a code snippet in #Nim 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#REXX
REXX
/*REXX program demonstrates a method to perform a flood fill of an area. */ black= '000000000000000000000000'b /*define the black color (using bits).*/ red = '000000000000000011111111'b /* " " red " " " */ green= '000000001111111100000000'b ...
Give a code snippet in #REXX Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards ...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
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 |...
#Elena
Elena
import extensions;   public program() { var s := "0123456789"; var n := 3; var m := 2; var c := $51; var z := "345";   console.writeLine(s.Substring(n, m)); console.writeLine(s.Substring(n, s.Length - n)); console.writeLine(s.Substring(0, s.Length - 1)); console.writeLine(s.Substring...
Give a code snippet in #Elena 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/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#jq
jq
# ss for an input array: def ss: map(.*.) | add;   # ss for a stream, S, without creating an intermediate array: def ss(S): reduce S as $x (0; . + ($x * $x) );
Give a code snippet in #jq Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#J
J
is_perfect=: +: = >:@#.~/.~&.q:@(6>.<.)
Give a code snippet in #J Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#FreeBASIC
FreeBASIC
dim as string yy(0 to 1) = {"yang", "yin"} dim as string elements(0 to 4) = {"Wood", "Fire", "Earth", "Metal", "Water"} dim as string animals(0 to 11) = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",_ "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}   dim as uinteger yr, y, e, ...
Give a code snippet in #FreeBASIC Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities re...
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...
#C
C
#include<stdlib.h> #include<locale.h> #include<wchar.h> #include<stdio.h> #include<time.h>   char rank[9];   int pos[8];   void swap(int i,int j){ int temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; }   void generateFirstRank(){ int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;   for(i=0;i<8;i++){ rank[i] =...
Give a code snippet in #C 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 pl...
christopher/rosetta-code
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#CLU
CLU
% Get all digits of a number digits = iter (n: int) yields (int) while n > 0 do yield(n // 10) n := n / 10 end end digits   % Get all prime factors of a number prime_factors = iter (n: int) yields (int)  % Take factors of 2 out first (the compiler should optimize) while n // 2 = 0 do yiel...
Give a code snippet in #CLU Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are al...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Quackery
Quackery
[ say "Guess the number (1-100 inclusive.)" cr cr 100 random 1+ [ $ "Your guess... " input trim reverse trim reverse $->n not iff [ drop say "That is not a number." cr ] again 2dup != while over < iff [ say "Too small." cr ] again ...
Give a code snippet in #Quackery Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#Elixir
Elixir
strs = ~w[this is a set of strings to sort This Is A Set Of Strings To Sort]   comparator = fn s1,s2 -> if String.length(s1)==String.length(s2), do: String.downcase(s1) <= String.downcase(s2), else: String.length(s1) >= String.length(s2) end IO.inspect Enum.sort(s...
Give a code snippet in #Elixir 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/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#AutoHotkey
AutoHotkey
Gui, -MinimizeBox Gui, Add, Edit, w300 r5 vText Gui, Add, Button, x105 w100 Default, Check Pangram Gui, Show,, Pangram Checker Return   GuiClose: ExitApp Return   ButtonCheckPangram: Gui, Submit, NoHide Loop, 26 If Not InStr(Text, Char := Chr(64 + A_Index)) { MsgBox,, Pangram, Character ...
Give a code snippet in #AutoHotkey Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#CLU
CLU
% Split string by whitespace split = iter (expr: string) yields (string) own whitespace: string := " \r\n\t" cur: array[char] := array[char]$[] for c: char in string$chars(expr) do if string$indexc(c, whitespace) = 0 then array[char]$addh(cur, c) else if array[char]$e...
Give a code snippet in #CLU Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN ...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#Kotlin
Kotlin
// version 1.1.0   import java.awt.* import java.awt.Color.* import javax.swing.*   class ColourPinstripeDisplay : JPanel() { private companion object { val palette = arrayOf(black, red, green, blue, magenta, cyan, yellow, white) }   private val bands = 4   init { preferredSize = Dimensi...
Give a code snippet in #Kotlin The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Ada
Ada
with Ada.Text_IO;   procedure Intersection_Of_Two_Lines is Do_Not_Intersect : exception;   type Line is record a : Float; b : Float; end record;   type Point is record x : Float; y : Float; end record;   function To_Line(p1, p2 : in Point) return Line is a : constant F...
Give a code snippet in #Ada [1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#E
E
def makeLamportSlot := <import:org.erights.e.elib.slot.makeLamportSlot>   The rate counter:   /** Returns a function to call to report the event being counted, and an EverReporter slot containing the current rate, as a float64 in units of events per millisecond. */ def makeRateCounter(timer, reportPeriod) { ...
Give a code snippet in #E Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these g...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#VBA
VBA
Debug.Print Now()
Give a code snippet in #VBA Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Da...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Groovy
Groovy
def lookAndSay(sequence) { def encoded = new StringBuilder() (sequence.toString() =~ /(([0-9])\2*)/).each { matcher -> encoded.append(matcher[1].size()).append(matcher[2]) } encoded.toString() }
Give a code snippet in #Groovy The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is c...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Interfaces; use Interfaces; with Interfaces.C; use Interfaces.C; with System; use System;   with Ada.Unchecked_Conversion;   procedure Shared_Library_Call is -- -- Interface to kernel32.dll which is responsible for loading DLLs under Windows. -- There are re...
Give a code snippet in #Ada Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language ...
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Go
Go
package main   import ( "encoding/binary" "log" "math" "os" "strings" )   func main() { const ( sampleRate = 44100 duration = 8 dataLength = sampleRate * duration hdrSize = 44 fileLen = dataLength + hdrSize - 8 )   // buffers buf1 := ma...
Give a code snippet in #Go Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, F...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Python
Python
>>> def horner(coeffs, x): acc = 0 for c in reversed(coeffs): acc = acc * x + c return acc   >>> horner( (-19, 7, -4, 6), 3) 128
Give a code snippet in #Python A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Golfscript
Golfscript
~)`
Give a code snippet in #Golfscript Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Clay
Clay
main() { for(i in range(1,100)) { if(i % 3 == 0 and i % 5 == 0) println("fizzbuzz"); else if(i % 3 == 0) println("fizz"); else if(i % 5 == 0) println("buzz"); else print(i); } }
Give a code snippet in #Clay Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz ...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Racket
Racket
  #lang racket   (define table '([0 #f] [0.06 0.10] [0.11 0.18] [0.16 0.26] [0.21 0.32] [0.26 0.38] [0.31 0.44] [0.36 0.50] [0.41 0.54] [0.46 0.58] [0.51 0.62] [0.56 0.66] [0.61 0.70] [0.66 0.74] [0.71 0.78] [0.76 0.82] [0.81 0.86] [0.86 0.90] [0.91 0.94] [0.96 0.98] [1.01 1.00])    ;; returns #f for...
Give a code snippet in #Racket A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and...
christopher/rosetta-code
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the i...
#Racket
Racket
#lang racket   (require net/url)   (define (lookup-MAC-address addr) (port->string (get-pure-port (url "http" #f "api.macvendors.com" #f #t (list (path/param addr null)) null #f))))   (module+ test (for ((i (in-list '("88:53:2E:67:07:BE" "FC:FB:FB:01:FA:21" "D4:F4:6F:C9:...
Give a code snippet in #Racket Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Logtalk
Logtalk
  | ?- create_object(Id, [], [set_logtalk_flag(dynamic_declarations,allow)], []), write('Variable name: '), read(Name), write('Variable value: '), read(Value), Fact =.. [Name, Value], Id::assertz(Fact).   Variable name: foo. Variable value: 42. Id = o1, Name = foo, Value = 42, Fact = foo(42).   ?...
Give a code snippet in #Logtalk Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Nim
Nim
proc slice[T](iter: iterator(): T {.closure.}; sl: Slice[T]): seq[T] = var i = 0 for n in iter(): if i > sl.b: break if i >= sl.a: result.add(n) inc i   iterator harshad(): int {.closure.} = for n in 1 ..< int.high: var sum = 0 for ch in $n: sum += ord(ch) - ord('0') if n mod sum ==...
Give a code snippet in #Nim The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Ada
Ada
with Gtk.Button; use Gtk.Button; with Gtk.GEntry; use Gtk.GEntry; with Gtk.Label; use Gtk.Label; with Gtk.Window; use Gtk.Window; with Gtk.Widget; use Gtk.Widget; with Gtk.Table; use Gtk.Table;   with Gtk.Handlers; with Gtk.Main;   procedure Graphic_Input is Window  : Gtk_Window; Grid  : Gtk_Tnetable; ...
Give a code snippet in #Ada In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Forth
Forth
: sum ( fn start count -- fsum ) 0e bounds do i s>d d>f dup execute f+ loop drop ;   :noname ( x -- 1/x^2 ) fdup f* 1/f ; ( xt ) 1 1000 sum f. \ 1.64393456668156 pi pi f* 6e f/ f. \ 1.64493406684823
Give a code snippet in #Forth Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#D
D
import core.stdc.stdio, core.stdc.stdlib;   extern(C) void foo() nothrow { "foo at exit".puts; }   extern(C) void bar() nothrow { "bar at exit".puts; }   extern(C) void spam() nothrow { "spam at exit".puts; }   int baz(in int x) pure nothrow in { assert(x != 0); } body { if (x < 0) return 10...
Give a code snippet in #D Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/des...
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#DCL
DCL
$ list = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0" $ i = 0 $ loop: $ number = f$element( i, ",", list ) $ if number .eqs. "," then $ exit $ abs_number = number - "-" $ len = f$length( abs_number ) $ if len .lt. 3 .or. .not. len $ then $ write sys$output f$fao( "!9SL...
Give a code snippet in #DCL Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be test...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#ALGOL_W
ALGOL W
begin  % check values of the function: f(n) = n + floor(1/2 + sqrt(n))  %  % are not squares  %   integer procedure f ( integer value n ) ; begin n + entier( 0.5 + sqrt( n ) ) end f ;   logical noSquares;    % first 22 values...
Give a code snippet in #ALGOL_W Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Perl
Perl
use 5.10.0; use strict; use warnings;   sub horner(\@$){ my ($coef, $x) = @_; my $result = 0; $result = $result * $x + $_ for reverse @$coef; return $result; }   my @coeff = (-19.0, 7, -4, 6); my $x = 3; say horner @coeff, $x;
Give a code snippet in #Perl A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#Java
Java
void insertNode(Node<T> anchor_node, Node<T> new_node) { new_node.next = anchor_node.next; anchor_node.next = new_node; }
Give a code snippet in #Java Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition...
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#AutoHotkey
AutoHotkey
r := InitR(292929)   Loop, 10 Out .= (A_Index + 219) ":`t" GetRand(r) "`n"   MsgBox, % Out   GetRand(r) { i := Mod(r["j"], 55) , r[i] := Mod(r[i] - r[Mod(i + 31, 55)], r["m"]) , r["j"] += 1 return, (r[i] < 0 ? r[i] + r["m"] : r[i]) }   InitR(Seed) { r := {"j": 0, "m": 10 ** 9}, s := {0: Seed, 1: 1} Loop, 53 s[...
Give a code snippet in #AutoHotkey A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\p...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#Perl
Perl
say "$_ = " . eval($_) for qw/5**3**2 (5**3)**2 5**(3**2)/;
Give a code snippet in #Perl This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show t...
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 ...
#zkl
zkl
var [private] seed = 0; fcn srand(s){ seed = s }   const TWO31=(1).shiftLeft(31);   //#define BSD_RAND 1   #ifdef BSD_RAND const A=1103515245, C=12345; fcn rand{ seed = (seed * A + C) % TWO31 } #else // MS rand const A=214013, C=2531011, TWO16=(1).shiftLeft(16); fcn rand{ (seed = (seed * A + C) % TWO31) / ...
Give a code snippet in #zkl 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/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
$Epilog := Print["Another instance is running "]; If[Attributes[Global`Mutex] == {Protected}, Exit[], Global`Mutex[x_] := Locked; Protect[Global`Mutex]; ]
Give a code snippet in #Mathematica_.2F_Wolfram_Language This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Gosu
Gosu
var valid = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345} valid.each(\ num ->print(middleThree(num)))   var errant = {1, 2, -1, -10, 2002, -2002, 0} errant.each(\ num ->print(middleThree(num)))   function middleThree(x: int) : String { var s = Math.abs(x) as String if(s.length < 3) return...
Give a code snippet in #Gosu Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tes...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 ...
#Objeck
Objeck
  bundle Default { class Stooge { function : Main(args : String[]) ~ Nil { nums := [1, 4, 5, 3, -6, 3, 7, 10, -2, -5]; StoogeSort(nums); each(i : nums) { IO.Console->Print(nums[i])->Print(","); }; IO.Console->PrintLine(); }   function : native : StoogeSort(l : Int[]) ...
Give a code snippet in #Objeck 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/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Inform_7
Inform 7
[This is a single-line comment.]   [This is a multi-line comment.]   [Comments can [be nested].]
Give a code snippet in #Inform_7 Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Fortran
Fortran
module bac implicit none   contains   subroutine Gennum(n) integer, intent(out) :: n(4) integer :: i, j real :: r   call random_number(r) n(1) = int(r * 9.0) + 1 i = 2   outer: do while (i <= 4) call random_number(r) n(i) = int(r * 9.0) + 1 inner: do j = i-1 , 1, -1 ...
Give a code snippet in #Fortran Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if th...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#PHP
PHP
<?php function horner($coeff, $x) { $result = 0; foreach (array_reverse($coeff) as $c) $result = $result * $x + $c; return $result; }   $coeff = array(-19.0, 7, -4, 6); $x = 3; echo horner($coeff, $x), "\n"; ?>
Give a code snippet in #PHP A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Wren
Wren
import "/fmt" for Fmt   class ChineseZodiac { static init() { __animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"] __aspects = ["Yang","Yin"] __elements = ["Wood", "Fire", "Earth", "Metal", "Water"] __stems ...
Give a code snippet in #Wren Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#Ring
Ring
  see sedol("710889") + nl see sedol("B0YBKJ") + nl see sedol("406566") + nl see sedol("B0YBLH") + nl see sedol("228276") + nl see sedol("B0YBKL") + nl see sedol("557910") + nl see sedol("B0YBKR") + nl see sedol("585284") + nl see sedol("B0YBKT") + nl see sedol("B00030") + nl   func sedol d d = upper(d) s = 0...
Give a code snippet in #Ring Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 ...
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...
#Zoea_Visual
Zoea Visual
str='Hello,How,Are,You,Today' tokens=(${(s:,:)str}) print ${(j:.:)tokens}
Give a code snippet in #Zoea_Visual 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 ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Haxe
Haxe
class InsertionSort { @:generic public static function sort<T>(arr:Array<T>) { for (i in 1...arr.length) { var value = arr[i]; var j = i - 1; while (j >= 0 && Reflect.compare(arr[j], value) > 0) { arr[j + 1] = arr[j--]; } arr[j + 1] = value; } } }   class Main { sta...
Give a code snippet in #Haxe Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Lambdatalk
Lambdatalk
  1) using the builtin primitive   {max 556 1 7344 4 7 52 22 55 88 122 55 99 1222 578} -> 7344   2) buidling a function   {def my-max {def max-h {lambda {:l :greatest} {if {A.empty? :l} then :greatest else {max-h {A.rest :l} {if {> {A.first :l} :greatest} then {A.first :...
Give a code snippet in #Lambdatalk Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor
Terminal control/Hiding the cursor
The task is to hide the cursor and show it again.
#zkl
zkl
print("\e[?25l"); Atomic.sleep(3); print("\e[?25h");
Give a code snippet in #zkl The task is to hide the cursor and show it again.
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#ACL2
ACL2
(let ((elem 8) (next (list 6 7 5 3 0 9))) (cons elem next))
Give a code snippet in #ACL2 singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element defi...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Z80_Assembly
Z80 Assembly
waitChar equ &BB06 ;wait for a key press PrintChar equ &BB5A ;print accumulator to screen   org &8000   ld ix,VerseTable inc ix inc ix ld iy,SongLookup   ld b,12 ;12 verses total outerloop_song: push af ;new line ld a,13 call PrintChar ld a,10 call PrintChar pop af push bc push i...
Give a code snippet in #Z80_Assembly Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string op...
christopher/rosetta-code
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming langua...
#PARI.2FGP
PARI/GP
#include <pari/pari.h>   #define HAILSTONE1 "n=1;print1(%d,\": \");apply(x->while(x!=1,if(x/2==x\\2,x/=2,x=x*3+1);n++;print1(x,\", \")),%d);print(\"(\",n,\")\n\")" #define HAILSTONE2 "m=n=0;for(i=2,%d,h=1;apply(x->while(x!=1,if(x/2==x\\2,x/=2,x=x*3+1);h++),i);if(m<h,m=h;n=i));print(n,\": \",m)"   void hailsto...
Give a code snippet in #PARI.2FGP The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared ...
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...
#jq
jq
def stripchars(string; banish): (string | explode) - (banish | explode) | implode;
Give a code snippet in #jq 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Nemerle
Nemerle
def i = 255; def j = 2;   WriteLine($"$i and $j is $(i & j)"); WriteLine($"$i or $j is $(i | j)"); WriteLine($"$i xor $j is $(i ^ j)"); WriteLine($"not $i is $(~i)"); WriteLine($"$i lshift $j is $(i << j)"); WriteLine($"$i arshift $j is $(i >> j)"); // When the left operand of the >> operator is of a signed in...
Give a code snippet in #Nemerle 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 Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#FreeBASIC
FreeBASIC
' version 14-01-2019 ' compile with: fbc -s console   Function nth_root(n As Integer, number As Double) As Double   Dim As Double a1 = number / n, a2 , a3   Do a3 = Abs(a2 - a1) a2 = ((n -1) * a1 + number / a1 ^ (n -1)) / n Swap a1, a2 Loop Until Abs(a2 - a1) = a3   Return a1   E...
Give a code snippet in #FreeBASIC Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Apex
Apex
System.debug(new String[] { 'apple', 'banana' }.size()); // Prints 2
Give a code snippet in #Apex Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter freque...
christopher/rosetta-code