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/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#CoffeeScript
CoffeeScript
  keys = ['a','b','c'] values = [1,2,3] map = {} map[key] = values[i] for key, i in keys  
Give a code snippet in #CoffeeScript Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
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.
#Raku
Raku
say max 10, 4, 5, -2, 11; say max <zero one two three four five six seven eight nine>;   # Even when the values and number of values aren't known until runtime my @list = flat(0..9,'A'..'H').roll((^60).pick).rotor(4,:partial)».join.words; say @list, ': ', max @list;  
Give a code snippet in #Raku 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/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Fortran
Fortran
MODULE SAMPLER !To sample a record from a file. SAM00100 CONTAINS SAM00200 CHARACTER*20 FUNCTION GETREC(N,F,IS) !Returns a status. SAM00300 Careful. Some compilers get confused over the function name's usage. SAM00...
Give a code snippet in #Fortran Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it...
christopher/rosetta-code
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#jq
jq
def primes: 2, range(3; infinite; 2) | select(is_prime);   # generate an infinite stream of primorials beginning with primorial(0) def primorials: 0, foreach primes as $p (1; .*$p; .);   "The first ten primorial numbers are:", limit(10; primorials),   "\nThe primorials with the given index have the lengths shown:",...
Give a code snippet in #jq Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primoria...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Janet
Janet
(prin "Goodbye, World!")
Give a code snippet in #Janet Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Stand...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Python
Python
from random import randrange   while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
Give a code snippet in #Python Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#jq
jq
def Smarandache_primes: # Output: a naively constructed stream of candidate strings of length >= 1 def Smarandache_candidates: def unconstrained($length): if $length==1 then "2", "3", "5", "7" else ("2", "3", "5", "7") as $n | $n + unconstrained($length -1 ) end; unconstrained(. - 1)...
Give a code snippet in #jq The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundred...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Perl
Perl
sub factorial { my $n = shift; my $result = 1; for (my $i = 1; $i <= $n; ++$i) { $result *= $i; }; $result; }   # using a .. range sub factorial { my $r = 1; $r *= $_ for 1..shift; $r; }
Give a code snippet in #Perl Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#F.23
F#
  module ``Trabb Pardo - Knuth`` open System let f (x: float) = sqrt(abs x) + (5.0 * (x ** 3.0))   Console.WriteLine "Enter 11 numbers:" [for _ in 1..11 -> Convert.ToDouble(Console.ReadLine())] |> List.rev |> List.map f |> List.iter (function | n when n <= 400.0 -> Console.WriteLine(n) | _ -> Console....
Give a code snippet in #F.23 The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#HicEst
HicEst
OPEN(FIle='test.txt')   1 DLG(NameEdit=x0, DNum=3)   x = x0 chi2 = SOLVE(NUL=x^3 - 3*x^2 + 2*x, Unknown=x, I=iterations, NumDiff=1E-15) EDIT(Text='approximate exact ', Word=(chi2 == 0), Parse=solution)   WRITE(FIle='test.txt', LENgth=6, Name) x0, x, solution, chi2, iterations GOTO 1
Give a code snippet in #HicEst Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Prolog
Prolog
$ swipl -g "writeln('hello world')." -t 'halt.' hello world $
Give a code snippet in #Prolog Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementat...
christopher/rosetta-code
http://rosettacode.org/wiki/Playfair_cipher
Playfair cipher
Playfair cipher You are encouraged to solve this task according to the task description, using any language you may know. Task Implement a Playfair cipher for encryption and decryption. The user must be able to choose   J  =  I     or   no   Q   in the alphabet. The output of the encrypted and decrypted message ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[MakeTranslationTable, PlayfairCipher, PlayfairDecipher] MakeTranslationTable[tt_List] := Module[{poss, in, out}, poss = Tuples[Tuples[Range[5], 2], 2]; Table[ If[p[[1, 1]] == p[[2, 1]], (* same row *) {in, out} = {p, {{p[[1, 1]], Mod[p[[1, 2]] + 1, 5, 1]}, {p[[2, 1]], Mod[p[[2, 2]] + 1, 5, 1]}}}...
Give a code snippet in #Mathematica.2FWolfram_Language Playfair cipher You are encouraged to solve this task according to the task description, using any language you may know. Task Implement a Playfair cipher for encryption and decryption. The user must be able to choose   J  =  I     or   no   Q   in the alpha...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Perl
Perl
use strict; use warnings; no warnings 'recursion'; use experimental 'signatures';   sub continued_fraction ($a, $b, $n = 100) { $a->() + ($n and $b->() / continued_fraction($a, $b, $n-1)); }   printf "√2 ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? 2 : 1 } }, sub { 1 }; prin...
Give a code snippet in #Perl continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to writ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#Ada
Ada
with Ada.Text_IO;   procedure Fractan is   type Fraction is record Nom: Natural; Denom: Positive; end record; type Frac_Arr is array(Positive range <>) of Fraction;   function "/" (N: Natural; D: Positive) return Fraction is Frac: Fraction := (Nom => N, Denom => D); begin return Frac; end "/"...
Give a code snippet in #Ada FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial ...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Ada
Ada
package Generic_Root is type Number is range 0 .. 2**63-1; type Number_Array is array(Positive range <>) of Number; type Base_Type is range 2 .. 16; -- any reasonable base to write down numb   generic with function "&"(X, Y: Number) return Number; -- instantiate with "+" for additive digital ro...
Give a code snippet in #Ada The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , re...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#Kotlin
Kotlin
// version 1.1.2   class Node<T: Number>(var data: T, var prev: Node<T>? = null, var next: Node<T>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append(" -> ", node.data.toString()) ...
Give a code snippet in #Kotlin Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Kotlin
Kotlin
fun main(args: Array<String>) = print("Goodbye, World!")
Give a code snippet in #Kotlin Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Stan...
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#Python
Python
  from logpy import * from logpy.core import lall import time   def lefto(q, p, list): # give me q such that q is left of p in list # zip(list, list[1:]) gives a list of 2-tuples of neighboring combinations # which can then be pattern-matched against the query return membero((q,p), zip(list, list[1:]))   def nexto(...
Give a code snippet in #Python Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five h...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#ATS
ATS
  (* ****** ****** *) // #include "share/atspre_staload.hats" #include "share/HATS/atspre_staload_libats_ML.hats" // (* ****** ****** *) // abst@ype pip_type = int abst@ype suit_type = int // abst@ype card_type = int // (* ****** ****** *)   typedef pip = pip_type typedef suit = suit_type   (* ****** ****** *)   typede...
Give a code snippet in #ATS Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current con...
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Ursala
Ursala
#import std #import nat   ss ::   ordering  %fZ ~ordering||lleq! column  %n ~column||1! reversed  %b   sorter = +^(~reversed?/~&x! ~&!,-<+ +^/~ordering ~~+ ~&h++ //skip+ predecessor+ ~column)
Give a code snippet in #Ursala Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; le...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Visual_Basic_.NET
Visual Basic .NET
Option Strict On Imports System.Text.RegularExpressions   Module Module1 ReadOnly IsinRegex As New Regex("^[A-Z]{2}[A-Z0-9]{9}\d$", RegexOptions.Compiled)   Function DigitValue(c As Char) As Integer Dim temp As Integer If Asc(c) >= Asc("0"c) AndAlso Asc(c) <= Asc("9"c) Then temp = As...
Give a code snippet in #Visual_Basic_.NET An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has...
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 |...
#SNUSP
SNUSP
++++>++++ a b !/?\<?\# a=b > - \# a>b - < a<b #\?/
Give a code snippet in #SNUSP 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/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks 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) In computational number theory, the Tonelli–Shanks algor...
#11l
11l
F legendre(a, p) R pow(a, (p - 1) I/ 2, p)   F tonelli(n, p) assert(legendre(n, p) == 1, ‘not a square (mod p)’) V q = p - 1 V s = 0 L q % 2 == 0 q I/= 2 s++ I s == 1 R pow(n, (p + 1) I/ 4, p) V z = 2 L I p - 1 == legendre(z, p) L.break z++ V c = pow(z, ...
Give a code snippet in #11l This page uses content from Wikipedia. The original article was at Tonelli-Shanks 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) In computational number the...
christopher/rosetta-code
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are n...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[EstheticNumbersRangeHelper, EstheticNumbersRange] EstheticNumbersRangeHelper[power_, mima : {mi_, max_}, b_ : 10] := Module[{steps, cands}, steps = Tuples[{-1, 1}, power - 1]; steps = Accumulate[Prepend[#, 0]] & /@ steps; cands = Table[Select[# + ConstantArray[s, power] & /@ steps, AllTrue[Between[{0, b ...
Give a code snippet in #Mathematica.2FWolfram_Language An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic n...
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#LIL
LIL
set rc [system ls -go]
Give a code snippet in #LIL Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Lua
Lua
function findcps(primelist, fcmp) local currlist = {primelist[1]} local longlist, prevdiff = currlist, 0 for i = 2, #primelist do local diff = primelist[i] - primelist[i-1] if fcmp(diff, prevdiff) then currlist[#currlist+1] = primelist[i] if #currlist > #longlist then longlist = currli...
Give a code snippet in #Lua Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes...
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...
#Ursala
Ursala
#import std   baz =   ~&?( ~&h?(  :/'baz succeeded with this input:', <'baz threw a user-defined empty string exception','U1'>!%), <'baz threw a user-defined empty file exception','U0'>!%)   bar = :/'bar received this result from normal termination of baz:'+ baz   #executable&   foo =   guard(  :/'...
Give a code snippet in #Ursala 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.   Arra...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#C
C
#include <stdlib.h> #include <stdio.h> #include <math.h>   /* declare a typedef for a function pointer */ typedef double (*Class2Func)(double);   /*A couple of functions with the above prototype */ double functionA( double v) { return v*v*v; } double functionB(double v) { return exp(log(v)/3); }   /* A function t...
Give a code snippet in #C A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other funct...
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
#Joy
Joy
DEFINE first == *.
Give a code snippet in #Joy Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Common_Lisp
Common Lisp
(defun take (seq &optional (n 1)) (values-list (loop repeat n collect (funcall seq))))   (defun power-seq (n) (let ((x 0)) (lambda () (expt (incf x) n))))   (defun filter-seq (s1 s2) ;; remove s2 from s1 (let ((x1 (take s1)) (x2 (take s2))) (lambda () (tagbody g (if (= x1 x2) (progn (setf x1 ...
Give a code snippet in #Common_Lisp A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#VBScript
VBScript
  Function count(coins,m,n) ReDim table(n+1) table(0) = 1 i = 0 Do While i < m j = coins(i) Do While j <= n table(j) = table(j) + table(j - coins(i)) j = j + 1 Loop i = i + 1 Loop count = table(n) End Function   'testing arr = Array(1,5,10,25) m = UBound(arr) + 1 n = 100 WScript.StdOut.WriteLine cou...
Give a code snippet in #VBScript There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels an...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#CMake
CMake
file(READ /etc/passwd string)
Give a code snippet in #CMake Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#AutoIt
AutoIt
  #include <Array.au3> Local $Array[1] _ArrayAdd($Array, "[]") _ArrayAdd($Array, "[][]") _ArrayAdd($Array, "[[][]]") _ArrayAdd($Array, "][") _ArrayAdd($Array, "][][") _ArrayAdd($Array, "[]][[]")   For $i = 0 To UBound($Array) -1 Balanced_Brackets($Array[$i]) If @error Then ConsoleWrite($Array[$i] &" = NOT OK"&@CRLF...
Give a code snippet in #AutoIt Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#C.2B.2B
C++
#include <queue> #include <cassert> // for run time assertions   int main() { std::queue<int> q; assert( q.empty() ); // initially the queue is empty   q.push(1); // add an element assert( !q.empty() ); // now the queue isn't empty any more assert( q.front() == 1 ); // the firs...
Give a code snippet in #C.2B.2B Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of q...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Elixir
Elixir
IO.puts :stderr, "Goodbye, World!"
Give a code snippet in #Elixir Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out...
christopher/rosetta-code
http://rosettacode.org/wiki/Intersecting_number_wheels
Intersecting number wheels
A number wheel has: A name which is an uppercase letter. A set of ordered values which are either numbers or names. A number is generated/yielded from a named wheel by: 1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"...
#Ruby
Ruby
groups = [{A: [1, 2, 3]}, {A: [1, :B, 2], B: [3, 4]}, {A: [1, :D, :D], D: [6, 7, 8]}, {A: [1, :B, :C], B: [3, 4], C: [5, :B]} ]   groups.each do |group| p group wheels = group.transform_values(&:cycle) res = 20.times.map do el = wheels[:A].next el = wheels[el].next until el....
Give a code snippet in #Ruby A number wheel has: A name which is an uppercase letter. A set of ordered values which are either numbers or names. A number is generated/yielded from a named wheel by: 1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the...
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.
#CoffeeScript
CoffeeScript
  print_multiplication_tables = (n) -> width = 4   pad = (s, n=width, c=' ') -> s = s.toString() result = '' padding = n - s.length while result.length < padding result += c result + s   s = pad('') + '|' for i in [1..n] s += pad i console.log s   s = pad('', width, '-') + '+' ...
Give a code snippet in #CoffeeScript 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/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#Clojure
Clojure
  (use 'quil.core)   (def w 500) (def h 400)   (defn setup [] (background 0))   (defn draw [] (push-matrix) (translate (/ w 2) (/ h 2) 0) (rotate-x 0.7) (rotate-z 0.5) (box 100 150 200) ; 2x3x4 relative dimensions (pop-matrix))   (defsketch main  :title "cuboid"  :setup setup  :size [w h]  :draw draw...
Give a code snippet in #Clojure Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection ...
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...
#Icon_and_Unicon
Icon and Unicon
  record Node (value, successor)  
Give a code snippet in #Icon_and_Unicon 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: E...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#Action.21
Action!
CHAR ARRAY text(1000) CARD length   PROC AppendText(CHAR ARRAY part) BYTE i   FOR i=1 TO part(0) DO text(length)=part(i) length==+1 OD RETURN   INT FUNC GetPosForWrap(BYTE lineLen INT start) INT pos   pos=start+lineLen IF pos>=length THEN RETURN (length-1) FI   WHILE pos>start AND text(pos...
Give a code snippet in #Action.21 Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#6502_Assembly
6502 Assembly
;;;;;;; zero page RAM memory addresses CursorX equ $00 CursorY equ $01 temp equ $02 ;;;;;;; memory-mapped hardware registers BorderColor equ $D020   Joystick1 equ $DC01 Joystick2 equ $DC00
Give a code snippet in #6502_Assembly 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/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#eC
eC
#include <GL/gl.h> import "ecere"   class GLTriangle : Window { text = "Triangle"; displayDriver = "OpenGL"; background = activeBorder; nativeDecorations = true; borderStyle = sizable; hasMaximize = true, hasMinimize = true, hasClose = true; size = { 640, 480 };   void OnRedraw(Surface surface) ...
Give a code snippet in #eC Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#Bracmat
Bracmat
str="Hello"; str$(!str " World!"):?str; out$!str;
Give a code snippet in #Bracmat 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/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Emacs_Lisp
Emacs Lisp
(secure-hash 'sha256 "Rosetta code") ;; as string of hex digits
Give a code snippet in #Emacs_Lisp SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa5427139...
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...
#Forth
Forth
create buf1 256 allot create buf2 256 allot buf1 value src buf2 value dest   s" 1" src place   : append-run ( digit run -- ) dest count + tuck c! 1+ c! dest c@ 2 + dest c! ;   : next-look-and-say 0 dest c! src 1+ c@ [char] 0 ( digit run ) src count bounds do over i c@ = if 1+ else append-ru...
Give a code snippet in #Forth 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Untouchable_numbers
Untouchable numbers
Definitions   Untouchable numbers   are also known as   nonaliquot numbers.   An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)   The   sum of all the proper divisors   is also known as   the   aliquot sum.   A...
#J
J
  factor=: 3 : 0 NB. explicit 'primes powers'=. __&q: y input_to_cartesian_product=. primes ^&.> i.&.> >: powers cartesian_product=. , { input_to_cartesian_product , */&> cartesian_product )   factor=: [: , [: */&> [: { [: (^&.> i.&.>@>:)/ __&q: NB. tacit     proper_divisors=: [: }: factor ...
Give a code snippet in #J Definitions   Untouchable numbers   are also known as   nonaliquot numbers.   An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)   The   sum of all the proper divisors   is also known a...
christopher/rosetta-code
http://rosettacode.org/wiki/One-time_pad
One-time pad
Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random encryption / decryption ( basic...
#Wren
Wren
import "io" for File, Directory import "/srandom" for SRandom import "/ioutil" for FileUtil, Input import "/dynamic" for Enum import "/str" for Char, Str   var CHARS_PER_LINE = 48 var CHUNK_SIZE = 6 var COLS = 8 var DEMO = true // would normally be set to false   var FileType = Enum.create("FileType", ["OTP", "ENC", "...
Give a code snippet in #Wren Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random e...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Raku
Raku
  my @y = <A B C D>; # Array of strings 'A', 'B', 'C', and 'D' say @y[2]; # the @-sigil requires the container to implement the role Positional @y[1,2] = 'x','y'; # that's where subscripts and many other things come from say @y; # OUTPUT«[A x y D]␤» # we start to count at 0 btw.   my $x = @y; # $x is now a reference fo...
Give a code snippet in #Raku Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
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.
#Rascal
Rascal
  rascal>import List; ok   rascal>max([1,2,3,4]); int: 4  
Give a code snippet in #Rascal 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/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#C
C
#include <stdio.h> #include <stdlib.h> #include <time.h>   int main() { struct tm ts; time_t t; const char *d = "March 7 2009 7:30pm EST";   strptime(d, "%B %d %Y %I:%M%p %Z", &ts); /* ts.tm_hour += 12; instead of t += 12*60*60 works too. */ t = mktime(&ts); t += 12*60*60; printf("%s", ctime(&t)); ...
Give a code snippet in #C Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#Factor
Factor
USING: io.encodings.ascii io.files kernel system ;   "Hello from Rosetta Code!" os windows? "tape.file" "/dev/tape" ? ascii set-file-contents
Give a code snippet in #Factor The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#bc
bc
a[0] = .123 a[1] = 234 a[3] = 95.6 for (i = 0; i < 4; i++) { a[i] }
Give a code snippet in #bc Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do...
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) ...
#DWScript
DWScript
var i : Integer;   for i := 1 to 100 do begin if i mod 15 = 0 then PrintLn('FizzBuzz') else if i mod 3 = 0 then PrintLn('Fizz') else if i mod 5 = 0 then PrintLn('Buzz') else PrintLn(i); end;
Give a code snippet in #DWScript 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   FizzB...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Clio
Clio
fn bottle n: n -> if = 0: 'no more bottles' elif = 1: n + ' bottle' else: n + ' bottles'   [99:0] -> * (@eager) fn i: i -> bottle -> print (transform i: sentence-case) 'of beer on the wall,' @ 'of beer.' if i = 0: 'Go to the store, buy some more, 99 bottles of beer on the wall.' -> print ...
Give a code snippet in #Clio Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#Clojure
Clojure
(ns zebra.core (:refer-clojure :exclude [==]) (:use [clojure.core.logic] [clojure.tools.macro :as macro]))   (defne lefto [x y l] ([_ _ [x y . ?r]]) ([_ _ [_ . ?r]] (lefto x y ?r)))   (defn nexto [x y l] (conde ((lefto x y l)) ((lefto y x l))))   (defn zebrao [hs] (macro/symbol-mac...
Give a code snippet in #Clojure Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five ...
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) ...
#REALbasic
REALbasic
  let fizzbuzz i => switch (i mod 3, i mod 5) { | (0, 0) => "FizzBuzz" | (0, _) => "Fizz" | (_, 0) => "Buzz" | _ => string_of_int i };   for i in 1 to 100 { print_endline (fizzbuzz i) };  
Give a code snippet in #REALbasic 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   Fizz...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
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 ...
#Nim
Nim
import sequtils, algorithm, intsets   # Go through the list, and for each element, check the rest of the list to see # if it appears again, var items = @[1, 2, 3, 2, 3, 4, 5, 6, 7] echo deduplicate(items) # O(n^2)   proc filterDup(xs: openArray[int]): seq[int] = result = @[xs[0]] var last = xs[0] for x in xs[1..x...
Give a code snippet in #Nim 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#AWK
AWK
  # syntax: GAWK -f JENSENS_DEVICE.AWK # converted from FreeBASIC BEGIN { evaluation() exit(0) } function evaluation( hi,i,lo,tmp) { lo = 1 hi = 100 for (i=lo; i<=hi; i++) { tmp += (1/i) } printf("%.15f\n",tmp) }  
Give a code snippet in #AWK Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#OCaml
OCaml
open Unix   let init_socket addr port = let inet_addr = (gethostbyname addr).h_addr_list.(0) in let sockaddr = ADDR_INET (inet_addr, port) in let sock = socket PF_INET SOCK_STREAM 0 in connect sock sockaddr; (* convert the file descriptor into high-level channels: *) let outchan = out_channel_of_descr sock ...
Give a code snippet in #OCaml For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Icon_and_Unicon
Icon and Unicon
procedure main();yes:="Accept";no:="Reject";pat:="procedure main();yes:=$;no:=$;pat:=$;a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end";a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(c...
Give a code snippet in #Icon_and_Unicon Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its inp...
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...
#Common_Lisp
Common Lisp
(format T "~{~a ~}~%" (loop for n = 1 then (1+ n) when (primep (logcount n)) collect n into numbers when (= (length numbers) 25) return numbers))   (format T "~{~a ~}~%" (loop for n from 888888877 to 888888888 when (primep (logcou...
Give a code snippet in #Common_Lisp 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 ...
#GAP
GAP
# According to section 21.18 of the reference manual, Sort is not stable (it's a Shell sort). # However, SortingPerm is stable. We will see it on an example, showing indexes of elements after the sort.   n := 20; L := List([1 .. n], i -> Random("AB")); # "AABABBBABBABAABABBAB"     p := SortingPerm(L); # (3,10,15,17,18,...
Give a code snippet in #GAP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Spin
Spin
con _clkmode = xtal1 + pll16x _clkfreq = 80_000_000   obj ser : "FullDuplexSerial.spin"   pub main ser.start(31, 30, 0, 115200)   repeat ser.str(string("SPAM",13,10))   waitcnt(_clkfreq + cnt) ser.stop cogstop(0)
Give a code snippet in #Spin Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#OOC
OOC
  main: func { "asdf" reverse() println() // prints "fdsa" }  
Give a code snippet in #OOC Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty s...
christopher/rosetta-code
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. 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) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#Kotlin
Kotlin
// version 1.1.3   import java.util.Stack   typealias Nodes = List<Node>   class Node(val n: Int) { var index = -1 // -1 signifies undefined var lowLink = -1 var onStack = false   override fun toString() = n.toString() }   class DirectedGraph(val vs: Nodes, val es: Map<Node, Nodes>)   fun tarjan(g: ...
Give a code snippet in #Kotlin This page uses content from Wikipedia. The original article was at Graph. 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) Tarjan's algorithm is an algorithm in graph...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#ML.2FI
ML/I
MCSKIP "WITH" NL "" Factorial - iterative MCSKIP MT,<> MCINS %. MCDEF FACTORIAL WITHS () AS <MCSET T1=%A1. MCSET T2=1 MCSET T3=1 %L1.MCGO L2 IF T3 GR T1 MCSET T2=T2*T3 MCSET T3=T3+1 MCGO L1 %L2.%T2.> fact(1) is FACTORIAL(1) fact(2) is FACTORIAL(2) fact(3) is FACTORIAL(3) fact(4) is FACTORIAL(4)
Give a code snippet in #ML.2FI Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | ...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) s1 := RealSet("(0,1]").union(RealSet("[0,2)")) s2 := RealSet("[0,2)").intersect(RealSet("(1,2)")) s3 := RealSet("[0,3)").difference(RealSet("(0,1)")) s4 := RealSet("[0,3)").difference(RealSet("[0,1]")) every s := s1|s2|s3|s4 do { every n := 0 to 2 do write(s.toS...
Give a code snippet in #Icon_and_Unicon All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#Ksh
Ksh
  #!/bin/ksh   # Semordnilap   # # Variables: # integer MIN_WORD_LEN=1 TRUE=1 FALSE=0 dict='/home/ostrande/prj/roscode/unixdict.txt'   integer i j=0 k=0 typeset -A word   # # Functions: #   # # Function _flipit(string) - return flipped string # function _flipit { typeset _buf ; _buf="$1" typeset _tmp ; unset _tmp   ...
Give a code snippet in #Ksh A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total ...
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
#Haskell
Haskell
  main = putStrLn "Hello world!"  
Give a code snippet in #Haskell 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/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program colorText.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ BUFFERSIZE, 100   /* Initialized data ...
Give a code snippet in #ARM_Assembly Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour ...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Oforth
Oforth
: move(n, from, to, via) n 0 > ifTrue: [ move(n 1-, from, via, to) System.Out "Move disk from " << from << " to " << to << cr move(n 1-, via, to, from) ] ;   5 $left $middle $right) move
Give a code snippet in #Oforth Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Excel
Excel
FIBONACCI =LAMBDA(n, APPLYN(n - 2)( LAMBDA(xs, APPENDROWS(xs)( SUM( LASTNROWS(2)(xs) ) ) ) )({1;1}) )
Give a code snippet in #Excel The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#ANSI_Standard_BASIC
ANSI Standard BASIC
100 SET WINDOW 0,1279,0,1023 110 REM (0,0) is the bottom left of the display 120 SET AREA COLOR 1 ! Select color one for drawing 130 FOR row=1 TO 4 140 LET n=IP(2^(row+2)) 150 LET w=IP(1280/n) 160 LET py=IP(256*(4-row)) 170 FOR b=0 TO n-1 180 LET g=b/(n-1) 190 IF n=16 OR n=64 THEN LET g=1-g 200 ...
Give a code snippet in #ANSI_Standard_BASIC The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of g...
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#Factor
Factor
USING: io kernel literals math.parser math.ranges sequences sequences.extras sequences.repeating splitting.extras splitting.monotonic strings ; IN: rosetta-code.run-length-encoding   CONSTANT: alpha $[ CHAR: A CHAR: Z [a,b] >string ]   : encode ( str -- str ) [ = ] monotonic-split [ [ length number>string ] [ first...
Give a code snippet in #Factor Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a fun...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#PL.2FI
PL/I
declare s character (100) varying; declare k fixed decimal (15);   put ('please type a string:'); get edit (s) (L); put skip list (s);   put skip list ('please type the integer 75000'); get list (k); put skip list (k); put skip list ('Thanks');
Give a code snippet in #PL.2FI User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Sub Form_Open() Dim sAnswer, sMessage As String   sAnswer = InputBox("Input an integer", "Odd or even")   If IsInteger(sAnswer) Then If Odd(Val(sAnswer)) Then sMessage = "' is an odd number" If Even(Val(sAnswer)) Then sMessage = "' is an even number" Else sMessage = "' does not compute!!" Endif   Print "'"...
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i i...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#FreeBASIC
FreeBASIC
' version 25-06-2015 ' compile with: fbc -s console   Function calc_entropy(source As String, base_ As Integer) As Double   Dim As Integer i, sourcelen = Len(source), totalchar(255) Dim As Double prop, entropy   For i = 0 To sourcelen -1 totalchar(source[i]) += 1 Next   For i = 0 To 255 ...
Give a code snippet in #FreeBASIC The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wor...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Common_Lisp
Common Lisp
;; iterate using dolist, destructure manually (dolist (pair alist) (destructuring-bind (key . value) pair (format t "~&Key: ~a, Value: ~a." key value)))   ;; iterate and destructure with loop (loop for (key . value) in alist do (format t "~&Key: ~a, Value: ~a." key value))
Give a code snippet in #Common_Lisp Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collection...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#D
D
import std.stdio;   T delegate(S) compose(T, U, S)(in T delegate(U) f, in U delegate(S) g) { return s => f(g(s)); }   void main() { writeln(compose((int x) => x + 15, (int x) => x ^^ 2)(10)); writeln(compose((int x) => x ^^ 2, (int x) => x + 15)(10)); }
Give a code snippet in #D Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to...
christopher/rosetta-code
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#Ruby
Ruby
def turn(base, n) sum = 0 while n != 0 do rem = n % base n = n / base sum = sum + rem end return sum % base end   def fairshare(base, count) print "Base %2d: " % [base] for i in 0 .. count - 1 do t = turn(base, i) print " %2d" % [t] end print "\n" ...
Give a code snippet in #Ruby The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs f...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#JavaScript
JavaScript
  var abr=`Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LP...
Give a code snippet in #JavaScript This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#PL.2FI
PL/I
  infinity: procedure options (main); declare k fixed decimal (30); put skip edit ((k do k = 1 to 999999999999999999999999999998))(f(31)); end infinity;  
Give a code snippet in #PL.2FI Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations l...
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#F.23
F#
  // McNuggets. Nigel Galloway: October 28th., 2018 let fN n g = Seq.initInfinite(fun ng->ng*n+g)|>Seq.takeWhile(fun n->n<=100) printfn "%d" (Set.maxElement(Set.difference (set[1..100]) (fN 20 0|>Seq.collect(fun n->fN 9 n)|>Seq.collect(fun n->fN 6 n)|>Set.ofSeq)))  
Give a code snippet in #F.23 Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNug...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AutoHotkey
AutoHotkey
items := [1,5,4,9,3,4] for i, v in SleepSort(items) result .= v ", " MsgBox, 262144, , % result := "[" Trim(result, ", ") "]" return   SleepSort(items){ global Sorted := [] slp := 50 for i, v in items{ fn := Func("PushFn").Bind(v) SetTimer, %fn%, % v * -slp } Sleep % Max(items*) ...
Give a code snippet in #AutoHotkey Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#zkl
zkl
fcn bearingAngleDiff(b1,b2){ // -->Float, b1,b2 can be int or float ( (b:=(0.0 + b2 - b1 + 720)%360) > 180 ) and b - 360 or b; }
Give a code snippet in #zkl Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -1...
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...
#C.23
C#
using System;   class Program { static void Main() { var value = "100"; var fromBases = new[] { 2, 8, 10, 16 }; var toBase = 10; foreach (var fromBase in fromBases) { Console.WriteLine("{0} in base {1} is {2} in base {3}", value, fromBase, Conv...
Give a code snippet in #C.23 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#jq
jq
def triples(n): range(1;n+1) as $x | range($x;n+1) as $y | range($y;n+1) as $z | select($x*$x + $y*$y == $z*$z) | [$x, $y, $z] ;  
Give a code snippet in #jq A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the u...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Speak["This is an example of speech synthesis."]
Give a code snippet in #Mathematica.2FWolfram_Language Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. 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, sexy primes are prime numbers that differ from each ot...
#Factor
Factor
USING: combinators.short-circuit fry interpolate io kernel literals locals make math math.primes math.ranges prettyprint qw sequences tools.memory.private ; IN: rosetta-code.sexy-primes   CONSTANT: limit 1,000,035 CONSTANT: primes $[ limit primes-upto ] CONSTANT: tuplet-names qw{ pair triplet quadruplet quintuplet }   ...
Give a code snippet in #Factor This page uses content from Wikipedia. The original article was at Sexy_prime. 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, sexy primes are prime ...
christopher/rosetta-code
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation ...
#Lua
Lua
-- Circular primes, in Lua, 6/22/2020 db local function isprime(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end for f = 5, math.sqrt(n), 6 do if n % f == 0 or n % (f+2) == 0 then return false end end return true end   local function iscircularprime...
Give a code snippet in #Lua Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number w...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#Wren
Wren
import "/math" for Int   var limit = 24 var res = List.filled(limit, 0) var next = 1 var n = 1 while (next <= limit) { var k = Int.divisors(n).count if (k == next) { res[k-1] = n next = next + 1 if (next > 4 && Int.isPrime(next)) n = 2.pow(next-1) - 1 } n = n + 1 } Syste...
Give a code snippet in #Wren Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exac...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#C.2B.2B_2
C++
g++ --std=c++11 ycomb.cc
Give a code snippet in #C.2B.2B_2 In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of ...
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
#D
D
import std.stdio, std.math, std.algorithm, std.range, std.numeric, std.typecons;   Tuple!(double[],"x", string,"err") gaussPartial(in double[][] a0, in double[] b0) pure /*nothrow*/ in { assert(a0.length == a0[0].length); assert(a0.length == b0.length); assert(a0.all!(row => row.length == a0[0].lengt...
Give a code snippet in #D 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/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Visual_Basic_.NET
Visual Basic .NET
Option Explicit On Option Infer On Option Strict On   Module Program Function FormatEnumerable(source As IEnumerable(Of String)) As String Dim res As New Text.StringBuilder("{")   Using en = source.GetEnumerator() Dim moreThanOne As Boolean = False Dim nxt = If(en.MoveNext(),...
Give a code snippet in #Visual_Basic_.NET Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#MOO
MOO
i = 1024; while (i > 0) player:tell(i); i /= 2; endwhile
Give a code snippet in #MOO 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
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 ...
#D
D
import std.stdio, std.string, std.algorithm, std.array, std.range, std.conv;   T[] orderDisjointArrayItems(T)(in T[] data, in T[] items) pure /*nothrow*/ @safe { int[] itemIndices; foreach (item; items.dup.sort().uniq) { immutable int itemCount = items.count(item); assert(data.count(item)...
Give a code snippet in #D Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Common_Lisp
Common Lisp
(let ((array (make-array 10))) (setf (aref array 0) 1 (aref array 1) 3) (print array))
Give a code snippet in #Common_Lisp This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and...
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...
#Ada
Ada
declare I : Integer := 1024; begin while I > 0 loop Put_Line(Integer'Image(I)); I := I / 2; end loop; end;
Give a code snippet in #Ada 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 ...
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.)
#RLaB
RLaB
  x = "code" # I am a comment x = "code" // Here I comment thee # matlab-like document line // C++ like document line  
Give a code snippet in #RLaB 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/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Collections;   module AssocArray { Main() : void { def hash1 = Hashtable([(1, "one"), (2, "two"), (3, "three")]); def hash2 = Hashtable(3); foreach (e in hash1) hash2[e.Value] = e.Key; WriteLine("Enter 1, 2, or 3:"); ...
Give a code snippet in #Nemerle Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition...
christopher/rosetta-code