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/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#OCaml
OCaml
let is_dir_empty d = Sys.readdir d = [| |]
Give a code snippet in #OCaml Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an em...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Fish
Fish
2[*]
Give a code snippet in #Fish A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract f...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Jsish
Jsish
for (;;) puts('SPAM');
Give a code snippet in #Jsish 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   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#AppleScript
AppleScript
use framework "Foundation"   ------ CASE-INSENSITIVE PALINDROME, IGNORING SPACES ? ----   -- isPalindrome :: String -> Bool on isPalindrome(s) s = intercalate("", reverse of characters of s) end isPalindrome   -- toSpaceFreeLower :: String -> String on spaceFreeToLower(s) script notSpace on |λ|(s) ...
Give a code snippet in #AppleScript A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possi...
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#C.23
C#
  static void Main(string[] args) { //test some numbers for (int i = 0; i < 50; i++) { Console.WriteLine("{0}\t{1} ", i,isSemiPrime(i)); } Console.ReadLine(); }   //returns true or false depending if input was considered semiprime private static bool isSemiPrime(int c) { int a = 2, b = 0...
Give a code snippet in #C.23 Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chos...
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#zkl
zkl
fcn draw_yinyang(trans,scale){ 0'|<use xlink:href="#y" transform="translate(%d,%d) scale(%g)"/>| .fmt(trans,trans,scale).print(); }   print( "<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n" "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\n" " 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n" "<svg ...
Give a code snippet in #zkl One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Simula
Simula
BEGIN  ! Concatenate arrays - of REAL, here;   CLASS REAL_ARRAY(N); INTEGER N; BEGIN REAL ARRAY DATA(1:N);    ! Return a new REAL_ARRAY containing  ! the values from this REAL_ARRAY  ! followed by the values from other; REF(REAL_ARRAY) PROCEDURE CONCAT(other); R...
Give a code snippet in #Simula 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/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#J
J
'Goodbye, World!'
Give a code snippet in #J The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Raku
Raku
use Lingua::EN::Numbers;   sub pell (Int $n) {   my $y = my $x = Int(sqrt $n); my $z = 1; my $r = 2 * $x;   my ($e1, $e2) = (1, 0); my ($f1, $f2) = (0, 1);   loop { $y = $r * $z - $y; $z = Int(($n - $y²) / $z); $r = Int(($x + $y) / $z);   ($e1, $e2) = ($e2, $r * $...
Give a code snippet in #Raku Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive i...
christopher/rosetta-code
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Scala
Scala
import java.io.{File, FileOutputStream, InputStream}   import org.apache.commons.net.ftp.{FTPClient, FTPFile, FTPReply}   import scala.util.{Failure, Try}   object FTPconn extends App { val (server, pass) = ("ftp.ed.ac.uk", "-ftptest@example.com") val (dir, filename, ftpClient) = ("/pub/cartonet/", "readme.txt", ne...
Give a code snippet in #Scala Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
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 ...
#Wart
Wart
h <- (table 'a 1 'b 2) each (key val) table prn key " " val
Give a code snippet in #Wart 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 Comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#Factor
Factor
USING: arrays kernel locals math math.functions rosettacode.raster.storage sequences ; IN: rosettacode.raster.line   ! this gives a function :: (cubic-bezier) ( P0 P1 P2 P3 -- bezier ) [ :> x 1 x - 3 ^ P0 n*v 1 x - sq 3 * x * P1 n*v 1 x - 3 * x sq * P2 n*v x 3 ^ P3 n*v v+ v+...
Give a code snippet in #Factor Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#Lasso
Lasso
local(f = file('unixdict.txt'), words = array, ordered = array, maxleng = 0) #f->dowithclose => { #f->foreachLine => { #words->insert(#1) } } with w in #words do => { local(tosort = #w->asString->values) #tosort->sort if(#w->asString == #tosort->join('')) => { #ordered->insert(#w->asString) #w->asString->siz...
Give a code snippet in #Lasso An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locall...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
wordlist = Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "Words"]; Print["The number of words in unixdict.txt = " <> ToString[Length[wordlist]]] StringMatchQ[#, ___ ~~ "c" ~~ "i" ~~ "e" ~~ ___] & /@ wordlist ; cie = Count[%, True]; StringMatchQ[#, ___ ~~ "c" ~~ "e" ~~ "i" ~~ ___] & /@ wordlist...
Give a code snippet in #Mathematica_.2F_Wolfram_Language The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phras...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Plain_English
Plain English
To run: Start up. Show the Munchausen numbers up to 5000. Wait for the escape key. Shut down.   To show the Munchausen numbers up to a number: If a counter is past the number, exit. If the counter is Munchausen, convert the counter to a string; write the string to the console. Repeat.   To decide if a number is Munchau...
Give a code snippet in #Plain_English A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Al...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#HicEst
HicEst
SYSTEM(DIR="docs") ! create docs in current directory (if not existent), make it current OPEN (FILE="input.txt", "NEW") ! in current directory = docs WRITE(FIle="input.txt", DELETE=1) ! no command to DELETE a DIRECTORY in HicEst   SYSTEM(DIR="C:\docs") ! create C:\docs (if not existent), make it curren...
Give a code snippet in #HicEst Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#FreeBASIC
FreeBASIC
  ' Chowla_numbers   #include "string.bi"   Dim Shared As Long limite limite = 10000000 Dim Shared As Boolean c(limite) Dim As Long count, topenumprimo, a count = 1 topenumprimo = 100 Dim As Longint p, k, kk, limitenumperfect limitenumperfect = 35000000 k = 2: kk = 3   Declare Function chowla(Byval n As Longint) As Lon...
Give a code snippet in #FreeBASIC Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Gnuplot
Gnuplot
multiply(x,y) = x*y   # then for example print multiply(123,456)
Give a code snippet in #Gnuplot A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distrac...
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#zkl
zkl
fcn sed(data,src,dst){ srcSz:=src.len(); dstSz:=dst.len(); md5:=Utils.MD5.calc(data); n:=0; while(Void!=(n:=data.find(src,n))) { data.del(n,srcSz); data.insert(n,dst); n+= dstSz; } return(md5!=Utils.MD5.calc(data)); // changed? } fcn sedFile(fname,src,dst){ f:=File(fname,"r"); data:=f.read(); f.c...
Give a code snippet in #zkl Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Perl
Perl
use strict; my(%f,@m);   /^(.).*(.)$/,$f{$1}{$_}=$2 for qw( audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumin...
Give a code snippet in #Perl A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the cat...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Kotlin
Kotlin
// version 1.1   fun sumProperDivisors(n: Int) = if (n < 2) 0 else (1..n / 2).filter { (n % it) == 0 }.sum()   fun main(args: Array<String>) { var sum: Int var deficient = 0 var perfect = 0 var abundant = 0   for (n in 1..20000) { sum = sumProperDivisors(n) when { sum...
Give a code snippet in #Kotlin These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficien...
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#C
C
  #include <stdio.h> #include <stdlib.h> #include <string.h>   #define err(...) fprintf(stderr, ## __VA_ARGS__), exit(1)   /* We create a dynamic string with a few functions which make modifying * the string and growing a bit easier */ typedef struct { char *data; size_t alloc; size_t length; } dstr;   inl...
Give a code snippet in #C This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where...
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...
#FreeBASIC
FreeBASIC
' version 27-10-2016 ' compile with: fbc -s console   #Define max_doors 100   Dim As ULong c, n, n1, door(1 To max_doors)   ' toggle, at start all doors are closed (0) ' 0 = door closed, 1 = door open For n = 1 To max_doors For n1 = n To max_doors Step n door(n1) = 1 - door(n1) Next Next   ' count the d...
Give a code snippet in #FreeBASIC 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/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#X86_Assembly
X86 Assembly
1 ;Assemble with: tasm, tlink /t 2 0000 .model tiny 3 0000 .code 4 .386 5 org 100h 6 ...
Give a code snippet in #X86_Assembly The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral tria...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Tailspin
Tailspin
  templates bubblesort templates bubble @: 1; 1..$-1 -> # $@ ! when <?($@bubblesort($+1) <..~$@bubblesort($)>)> do @: $; def temp: $@bubblesort($@); @bubblesort($@): $@bubblesort($@+1); @bubblesort($@+1): $temp; end bubble   @: $; $::length -> # $@ !   when <2..> do ...
Give a code snippet in #Tailspin Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#Swift
Swift
import Foundation   class PrimeSieve { var composite: [Bool]   init(size: Int) { composite = Array(repeating: false, count: size/2) var p = 3 while p * p <= size { if !composite[p/2 - 1] { let inc = p * 2 var q = p * p while q <...
Give a code snippet in #Swift Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#Nim
Nim
import strformat, strutils import bignum   let Zero = newInt(0) One = newInt(1)   #---------------------------------------------------------------------------------------------------   proc toEgyptianrecursive(rat: Rat; fracs: seq[Rat]): seq[Rat] =   if rat.isZero: return fracs   let iquo = cdiv(rat.denom, rat....
Give a code snippet in #Nim An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (un...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#8th
8th
#!/usr/local/bin/a68g --script # # -*- coding: utf-8 -*- #   # UNICHAR/UNICODE must be printed using REPR to convert to UTF8 #   MODE UNICHAR = STRUCT(BITS #31# bits); # assuming bits width >=31 # MODE UNICODE = FLEX[0]UNICHAR;   OP INITUNICHAR = (BITS bits)UNICHAR: (UNICHAR out; bits OF out := #ABS# bits; out); OP INI...
Give a code snippet in #8th As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is y...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#JavaScript
JavaScript
  let thePressedKey;   function handleKey(evt) { thePressedKey = evt; console.log(thePressedKey); }   document.addEventListener('keydown', handleKey);  
Give a code snippet in #JavaScript Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Fortran
Fortran
  PROGRAM MAX_LICENSES IMPLICIT NONE   INTEGER :: out=0, maxout=0, maxcount=0, err CHARACTER(50) :: line CHARACTER(19) :: maxtime(100)   OPEN (UNIT=5, FILE="Licenses.txt", STATUS="OLD", IOSTAT=err) IF (err > 0) THEN WRITE(*,*) "Error opening file Licenses.txt" STOP END IF   DO R...
Give a code snippet in #Fortran A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a c...
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...
#LFE
LFE
  (let* ((my-dict (: dict new)) (my-dict (: dict store 'key-1 '"value 1" my-dict)) (my-dict (: dict store 'key-2 '"value 2" my-dict))) (: io format '"size: ~p~n" (list (: dict size my-dict))) (: io format '"some data: ~p~n" (list (: dict fetch 'key-1 my-dict))))    
Give a code snippet in #LFE 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, El...
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Common_Lisp
Common Lisp
(defun gray-encode (n) (logxor n (ash n -1)))   (defun gray-decode (n) (do ((p n (logxor p n))) ((zerop n) p) (setf n (ash n -1))))   (loop for i to 31 do (let* ((g (gray-encode i)) (b (gray-decode g))) (format t "~2d:~6b =>~6b =>~6b :~2d~%" i i g b b)))
Give a code snippet in #Common_Lisp Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Processing
Processing
void setup() { println("Survivor: " + execute(41, 3)); println("Survivors: " + executeAllButM(41, 3, 3)); }   int execute(int n, int k) { int killIdx = 0; IntList prisoners = new IntList(n); for (int i = 0; i < n; i++) { prisoners.append(i); } println("Prisoners executed in order:"); while (prisoner...
Give a code snippet in #Processing Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Action.21
Action!
BYTE FUNC SumOfSquares(BYTE x) BYTE sum,d   sum=0 WHILE x#0 DO d=x MOD 10 d==*d sum==+d x==/10 OD RETURN (sum)   BYTE FUNC Contains(BYTE ARRAY a BYTE count,x) BYTE i   FOR i=0 TO count-1 DO IF a(i)=x THEN RETURN (1) FI OD RETURN (0)   BYTE FUNC IsHappyNumber(BYTE x) BYTE ARRAY ca...
Give a code snippet in #Action.21 From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endles...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Euphoria
Euphoria
include file.e   function file_size(sequence file_name) object x x = dir(file_name) if sequence(x) and length(x) = 1 then return x[1][D_SIZE] else return -1 -- the file does not exist end if end function   procedure test(sequence file_name) integer size size = file_size(file_...
Give a code snippet in #Euphoria Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#JavaScript
JavaScript
function doStuff() { throw new Error('Not implemented!'); }
Give a code snippet in #JavaScript Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Excep...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#XPL0
XPL0
inc c:\cxpl\codes; def Pi = 3.14159265358979323846, Deg2Rad = Pi/180.0, Rad2Deg = 180.0/Pi, Tab = $09; real Lat, SinLat, Long, Mer; real HA, HLA; \hour angle and hour line angle int H, T; \hour, time [Text(0, "Latitude: "); Lat:= RlIn(0); Text(0, "Longit...
Give a code snippet in #XPL0 Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island,...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#UNIX_Shell
UNIX Shell
list=(these are some words) printf '%s\n' "${list[RANDOM%${#list[@]}]}"
Give a code snippet in #UNIX_Shell Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Tcl
Tcl
package require Tcl 8.6   proc hammingWeight {n} { tcl::mathop::+ {*}[split [format %llb $n] ""] } for {set n 0;set l {}} {$n<30} {incr n} { lappend l [hammingWeight [expr {3**$n}]] } puts "p3: $l" for {set n 0;set e [set o {}]} {[llength $e]<30||[llength $o]<30} {incr n} { lappend [expr {[hammingWeight $n]...
Give a code snippet in #Tcl Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count ...
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...
#Euphoria
Euphoria
  function load_file(sequence filename) integer fn,c sequence data fn = open(filename,"r") -- "r" for text files, "rb" for binary files if (fn = -1) then return {} end if -- failed to open the file   data = {} -- init to empty sequence c = getc(fn) -- prime the char buffer while (c != -1) do -- ...
Give a code snippet in #Euphoria 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 in...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#PureBasic
PureBasic
Structure wins stay.i redecide.i EndStructure   #goat = 0 #car = 1 Procedure MontyHall(*results.wins) Dim Doors(2) Doors(Random(2)) = #car   player = Random(2) Select Doors(player) Case #car *results\redecide + #goat *results\stay + #car Case #goat *results\redecide + #car *r...
Give a code snippet in #PureBasic Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Agda
Agda
module Matrix where   open import Data.Nat open import Data.Vec   Matrix : (A : Set) → ℕ → ℕ → Set Matrix A m n = Vec (Vec A m) n   transpose : ∀ {A m n} → Matrix A m n → Matrix A n m transpose [] = replicate [] transpose (xs ∷ xss) = zipWith _∷_ xs (transpose xss)   a = (1 ∷ 2 ∷ 3 ∷ []) ∷ (4 ∷ 5 ∷ 6 ∷ []) ∷ [] b = tra...
Give a code snippet in #Agda Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Scheme
Scheme
  (import (scheme base) (scheme char) (scheme cxr) (scheme write) (srfi 1 lists))   ;; convert a string into a list of tokens (define (string->tokens str) (define (next-token chars) (cond ((member (car chars) (list #\+ #\- #\* #\/) char=?) (values (cdr chars) ...
Give a code snippet in #Scheme Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a s...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#ALGOL_68
ALGOL 68
PROC set = (REF FILE file, INT page, line, character)VOID: ~
Give a code snippet in #ALGOL_68 Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Visual_Basic_.NET
Visual Basic .NET
'Current Directory IO.Directory.CreateDirectory("docs") IO.File.Create("output.txt").Close()   'Root IO.Directory.CreateDirectory("\docs") IO.File.Create("\output.txt").Close()   'Root, platform independent IO.Directory.CreateDirectory(IO.Path.DirectorySeparatorChar & "docs") IO.File.Create(IO.Path.DirectorySeparato...
Give a code snippet in #Visual_Basic_.NET In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#F.23
F#
let dot_product (a:array<'a>) (b:array<'a>) = if Array.length a <> Array.length b then failwith "invalid argument: vectors must have the same lengths" Array.fold2 (fun acc i j -> acc + (i * j)) 0 a b
Give a code snippet in #F.23 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]...
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) ...
#Casio_BASIC
Casio BASIC
(* FizzBuzz in CDuce *)   let format (n : Int) : Latin1 = if (n mod 3 = 0) || (n mod 5 = 0) then "FizzBuzz" else if (n mod 5 = 0) then "Buzz" else if (n mod 3 = 0) then "Fizz" else string_of (n);;   let fizz (n : Int, size : Int) : _ = print (format (n) @ "\n"); if (n = size) then n = 0...
Give a code snippet in #Casio_BASIC 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   Fi...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#HicEst
HicEst
s = 0 DO exponent = 2, 31 IF(exponent > 2) s = 4 n = 2^exponent - 1 DO i = 1, exponent-2 s = MOD(s*s - 2, n) ENDDO IF(s == 0) WRITE(Messagebox) 'M', exponent, ' is prime;', n ENDDO   END
Give a code snippet in #HicEst Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#Nim
Nim
import iterutils, bigints   proc lfact: iterator: BigInt = result = iterator: BigInt = yield 0.initBigInt var fact = 1.initBigInt sum = 0.initBigInt n = 1.initBigInt while true: sum += fact fact *= n n += 1 yield sum   echo "first 11:\n " for i in lfact().slice(l...
Give a code snippet in #Nim Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Ursa
Ursa
decl double<> notes append 261.63 293.66 329.63 349.23 392.00 440.00 493.88 523.25 notes   for (decl int i) (< i (size notes)) (inc i) ursa.util.sound.beep notes<i> 0.5 end for
Give a code snippet in #Ursa 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,...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#Clojure
Clojure
(let [Δ 1] (inc Δ))
Give a code snippet in #Clojure Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#Modula-3
Modula-3
INTERFACE Frac;   EXCEPTION ZeroDenominator;   TYPE   T <: Public; Public = OBJECT METHODS (* initialization and conversion *) init(a, b: INTEGER): T RAISES { ZeroDenominator }; fromInt(a: INTEGER): T; (* unary operators *) abs(): T; opposite(): T; (* binary operators *) plus(other...
Give a code snippet in #Modula-3 Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominato...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#VBScript
VBScript
Function sum_and_product(arr) sum = 0 product = 1 For i = 0 To UBound(arr) sum = sum + arr(i) product = product * arr(i) Next WScript.StdOut.Write "Sum: " & sum WScript.StdOut.WriteLine WScript.StdOut.Write "Product: " & product WScript.StdOut.WriteLine End Function   myarray = Array(1,2,3,4,5,6) sum_and_pr...
Give a code snippet in #VBScript Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Objective-C
Objective-C
// here "object" is an object pointer if (object == nil) { NSLog("object is nil"); }
Give a code snippet in #Objective-C Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Lambdatalk
Lambdatalk
  {def allsame {def allsame.r {lambda {:s :n :i} {if {= :i :n} then true else {if {not {W.equal? {A.get :i :s} {A.get 0 :s}}} then false else {allsame.r :s :n {+ :i 1}} }}}} {lambda {:s} {allsame.r :s {- {A.length :s} 1} 0} }} -> allsame   {def strict_order {def strict_order.r {lambda {:s :n...
Give a code snippet in #Lambdatalk Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or f...
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...
#CoffeeScript
CoffeeScript
# You could have symmetric algorithms for max right and left # truncatable numbers, but they lend themselves to slightly # different optimizations.   max_right_truncatable_number = (n, f) -> # This algorithm only evaluates 37 numbers for primeness to # get the max right truncatable prime < 1000000. Its # optimiz...
Give a code snippet in #CoffeeScript 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-tr...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Web_68
Web 68
@1Introduction. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Licence as published by the Free Software Foundation, either version 3 of the Licence, or (at your option) any later version.   Copyright (c) 2012 Sian Mountbatten.   @m cvs simpleapp = "$Id...
Give a code snippet in #Web_68 Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#UNIX_Shell
UNIX Shell
$ a=42 $ b=a $ eval "echo \$$b" 42
Give a code snippet in #UNIX_Shell Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if ap...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Lasso
Lasso
// String with leading whitespace removed '>' + (' \t Hello')->trim& + '<'   // String with trailing whitespace removed '>' + ('Hello \t ')->trim& + '<'   // String with both leading and trailing whitespace removed '>' + (' \t Hello \t ')->trim& + '<'
Give a code snippet in #Lasso Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace re...
christopher/rosetta-code
http://rosettacode.org/wiki/Padovan_n-step_number_sequences
Padovan n-step number sequences
As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n ==...
#ALGOL_W
ALGOL W
begin % show some valuies of the Padovan n-step number sequences  %  % sets R(i,j) to the jth element of the ith padovan sequence  %  % maxS is the number of sequences to generate and maxE is the %  % maximum number of elements for each sequence  %  % maxS must be >= 2 ...
Give a code snippet in #ALGOL_W As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Scala
Scala
def repeat[A](n:Int)(f: => A)= ( 0 until n).foreach(_ => f)   repeat(3) { println("Example") }
Give a code snippet in #Scala Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are...
#Haskell
Haskell
import Control.Monad.State (State, evalState, replicateM, runState, state) import System.Random (StdGen, newStdGen, randomR) import Data.List (find, nub, sort)   combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (y:ys) = map (y :) (combinations (k - 1) ys) ++ combi...
Give a code snippet in #Haskell Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol...
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...
#J
J
las=: ,@((# , {.);.1~ 1 , 2 ~:/\ ])&.(10x&#.inv)@]^:(1+i.@[)
Give a code snippet in #J 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, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Run_BASIC
Run BASIC
open DefaultDir$ + "\public\filetest.txt" for input as #f while not(eof(#f)) line input #f, a$ print a$ wend close #f  
Give a code snippet in #Run_BASIC Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
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.)
#Emacs_Lisp
Emacs Lisp
; This is a comment
Give a code snippet in #Emacs_Lisp 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/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Potion
Potion
"møøse" length print "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" length print "J̲o̲s̲é̲" length print
Give a code snippet in #Potion Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme con...
christopher/rosetta-code
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Kotlin
Kotlin
// Version 1.2.71   val months = listOf( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" )   class Birthday(val month: Int, val day: Int) { public override fun toString() = "${months[month - 1]} $day"   public fun monthUniqueIn(bds...
Give a code snippet in #Kotlin Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells...
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
#Visual_Basic_.NET
Visual Basic .NET
f=Add, f(6, 2) = 8 f=Mul, f(6, 2) = 12 f=Div, f(6, 2) = 3
Give a code snippet in #Visual_Basic_.NET Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#CLU
CLU
digits = iter (n: int) yields (int) while n>0 do yield(n//10) n := n/10 end end digits   mdr = proc (n: int) returns (int,int) i: int := 0 while n>=10 do m: int := 1 for d: int in digits(n) do m := m * d end n := m i := i+1 end ...
Give a code snippet in #CLU The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#IS-BASIC
IS-BASIC
100 PROGRAM "Fibonacc.bas" 110 FOR I=0 TO 10 120 PRINT FIB(I); 130 NEXT 140 DEF FIB(K) 150 SELECT CASE K 160 CASE IS<0 170 PRINT "Negative parameter to Fibonacci.":STOP 180 CASE 0 190 LET FIB=0 200 CASE 1 210 LET FIB=1 220 CASE ELSE 230 LET FIB=FIB(K-1)+FIB(K-2) 240 END SELECT 250 END DE...
Give a code snippet in #IS-BASIC While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unw...
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function nonSquare (n As UInteger) As UInteger Return CUInt(n + Int(0.5 + Sqr(n))) End Function   Function isSquare (n As UInteger) As Boolean Dim As UInteger r = CUInt(Sqr(n)) Return n = r * r End Function   Print "The first 22 numbers generated by the sequence are :" For i As Integer = 1 To ...
Give a code snippet in #FreeBASIC 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   A0...
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
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 |...
#E
E
var x := 0 def slot := &x # define "slot" to be x's slot x := 1 # direct assignment; value is now 1 slot.put(2) # via slot object; value is now 2
Give a code snippet in #E 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 Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Racket
Racket
(define (leap-year? y) (and (zero? (modulo y 4)) (or (positive? (modulo y 100)) (zero? (modulo y 400)))))
Give a code snippet in #Racket Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Oforth
Oforth
import: date   : testVariable | a b c | Date now ->a a println ;
Give a code snippet in #Oforth 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/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.
#NewLISP
NewLISP
(define (nth-root n a) (let ((x1 a) (x2 (div a n))) (until (= x1 x2) (setq x1 x2 x2 (div (add (mul x1 (- n 1)) (div a (pow x1 (- n 1)))) n))) x2))
Give a code snippet in #NewLISP 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/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Processing
Processing
size(320, 240); set(100, 100, color(255,0,0));
Give a code snippet in #Processing Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
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...
#Lasso
Lasso
#!/usr/bin/lasso9   local( lower = integer_random(10, 1), higher = integer_random(100, 20), number = integer_random(#higher, #lower), status = false, guess )   // prompt for a number stdout('Guess a number: ')   while(not #status) => { #guess = null   // the following bits wait until the terminal gives you back ...
Give a code snippet in #Lasso 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: hi...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#REXX
REXX
/*REXX pgm displays an integer (expressed in the pgm as a literal) in different bases*/ /*────────── expressing decimal numbers ──────────*/ ddd = 123 /*a decimal number (expressed as a literal). */ ddd = '123' /*this is...
Give a code snippet in #REXX Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#D
D
// // The Rosetta Code Virtual Machine in D. // // This code was migrated from an implementation in ATS. I have tried // to keep it possible to compare the two languages easily, although // in some cases the demonstration of "low level" techniques in ATS // (such as avoiding memory leaks that might require garbage // c...
Give a code snippet in #D A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input f...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Faulhaber] bernoulliB[1] := 1/2 bernoulliB[n_] := BernoulliB[n] Faulhaber[n_, p_] := 1/(p + 1) Sum[Binomial[p + 1, j] bernoulliB[j] n^(p + 1 - j), {j, 0, p}] Table[Rest@CoefficientList[Faulhaber[n, t], n], {t, 0, 9}] // Grid Faulhaber[1000, 17]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Brat
Brat
#Convert to integer, increment, then back to string p ("100".to_i + 1).to_s #Prints 101
Give a code snippet in #Brat Task Increment a numerical string.
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...
#Lasso
Lasso
push: queue->insert pop: queue->get empty: queue->size == 0
Give a code snippet in #Lasso 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 que...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#TSE_SAL
TSE SAL
  STRING PROC FNStringGetExpressionRegularCharacterMetaEscapeS( STRING inS ) STRING s[255] = inS s = StrReplace( "\", s, "\\", "gn" ) s = StrReplace( "{", s, "\{", "gn" ) s = StrReplace( "[", s, "\[", "gn" ) s = StrReplace( "}", s, "\}", "gn" ) s = StrReplace( "]", s, "\]", "gn" ) s = StrReplace( "*", s, "\*", "...
Give a code snippet in #TSE_SAL The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or d...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#F.23
F#
type LazyList<'a> = Cons of 'a * Lazy<LazyList<'a>> // ': fix colouring   let rec hammings() = let rec (-|-) (Cons(x, nxf) as xs) (Cons(y, nyf) as ys) = if x < y then Cons(x, lazy(nxf.Value -|- ys)) elif x > y then Cons(y, lazy(xs -|- nyf.Value)) else Cons(x, lazy(nxf.Value -|- nyf.Value)) let rec inf_m...
Give a code snippet in #F.23 Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#C
C
  #include <stdio.h> #include <string.h>   /* The functions used are destructive, so after each call the string needs * to be copied over again. One could easily allocate new strings as * required, but this way allows the caller to manage memory themselves */   char* reverse_section(char *s, size_t length) { if (...
Give a code snippet in #C Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each wo...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Ring
Ring
  # Project : FAST format   a = ">Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED"   i = 1 while i <= len(a) if substr(a,i,17) = ">Rosetta_Example_" see nl see substr(a,i,18) + ": " + nl i = i + 17 else if asc...
Give a code snippet in #Ring In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosett...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Forth
Forth
388c388 < CREATE big_string 256 CHARS ALLOT --- > CREATE big_string 500000 CHARS ALLOT 394c394 < big_string 256 CHARS + bighld ! ; \ Haydon p 67 --- > big_string 500000 CHARS + bighld ! ; \ Haydon p 67 403c403 < big_string 256 CHARS + \ One past end of string --- > big_string 500000 CHARS + \ One past en...
Give a code snippet in #Forth Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
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...
#TI-89_BASIC
TI-89 BASIC
Prgm Local k, s ClrIO Loop Disp "Press a key, or ON to exit." getKey() © clear buffer 0 → k : While k = 0 : getKey() → k : EndWhile ClrIO If k ≥ 256 Then Disp "Not a character." Disp "Code: " & string(k) Else   char(k) → s © © char() and or...
Give a code snippet in #TI-89_BASIC 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)....
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...
#SenseTalk
SenseTalk
// ExponentialGenerator.script   to initialize set my base to 0 if my exponent is empty then set my exponent to 1 -- default if not given end initialize   to handle nextValue add 1 to my base return my base to the power of my exponent end nextValue
Give a code snippet in #SenseTalk 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#K
K
w@&d=|/d:#:'w:d@&&/'{~x<y}':'d:0:"unixdict.txt" ("abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow" "biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty")
Give a code snippet in #K An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally as...
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#Kotlin
Kotlin
// version 1.1   interface Announcer { fun announceType()   // interface can contain non-abstract members but cannot store state fun announceName() { println("I don't have a name") } }   abstract class Animal: Announcer { abstract fun makeNoise()   // abstract class can contain non-abstr...
Give a code snippet in #Kotlin Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Modula-3
Modula-3
MODULE Stars EXPORTS Main;   IMPORT IO;   BEGIN FOR i := 1 TO 5 DO FOR j := 1 TO i DO IO.Put("*"); END; IO.Put("\n"); END; END Stars.
Give a code snippet in #Modula-3 “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract stru...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Scala
Scala
import scala.math.sqrt   object StddevCalc extends App {   def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = { def avg(ts: Iterable[T])(implicit num: Fractional[T]): T = num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T   val mean: T = avg(ts) //...
Give a code snippet in #Scala Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the funct...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Erlang
Erlang
  -module( configuration_file ).   -export( [read/1, task/0] ).   read( File ) -> {ok, Binary} = file:read_file( File ), Lines = [X || <<First:8, _T/binary>> = X <- binary:split(Binary, <<"\n">>, [global]), First =/= $#, First =/= $;], [option_from_binaries(binary:split(X, <<" ">>)) || X <- Lines].   task()...
Give a code snippet in #Erlang The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are...
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
#Retro
Retro
:example ("-) 'Enter_a_string:_ s:put s:get s:keep [ 'Enter_75000:_ s:put s:get-word s:to-number nl #75000 eq? ] until 'Your_string_was:_'%s'\n s:format s:put ;
Give a code snippet in #Retro 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/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Objective-C
Objective-C
NSArray *args = [[NSProcessInfo processInfo] arguments]; NSLog(@"This program is named %@.", [args objectAtIndex:0]); NSLog(@"There are %d arguments.", [args count] - 1); for (i = 1; i < [args count]; ++i){ NSLog(@"the argument #%d is %@", i, [args objectAtIndex:i]); }
Give a code snippet in #Objective-C Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#BaCon
BaCon
' Pick random element OPTION BASE 1 DECLARE words$[6] FOR i = 1 TO 6 : READ words$[i] : NEXT DATA "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"   element = RANDOM(6) + 1 PRINT "Chose ", element, ": ", words$[element]
Give a code snippet in #BaCon Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Graph_colouring
Graph colouring
A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge separated by a dash. Edges define the nodes being connected...
#Go
Go
package main   import ( "fmt" "sort" )   type graph struct { nn int // number of nodes st int // node numbering starts from nbr [][]int // neighbor list for each node }   type nodeval struct { n int // number of node v int // valence of node i.e. number of neighbors }   func contai...
Give a code snippet in #Go A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge separated by a dash. Edges defi...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Racket
Racket
  #lang racket (define functions (for/list ([i 10]) (λ() (* i i)))) (map (λ(f) (f)) functions)  
Give a code snippet in #Racket Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i ...
christopher/rosetta-code
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Go
Go
// prints the first few members of the Thue-Morse sequence   package main   import ( "fmt" "bytes" )   // sets tmBuffer to the next member of the Thue-Morse sequence // tmBuffer must contain a valid Thue-Morse sequence member before the call func nextTMSequenceMember( tmBuffer * bytes.Buffer ) { // "flip" t...
Give a code snippet in #Go Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
christopher/rosetta-code