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/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...
#Emacs_Lisp
Emacs Lisp
(dolist (x '(1 2 3 4)) (message "x=%d" x))
Give a code snippet in #Emacs_Lisp 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   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Modula-2
Modula-2
  MODULE RomanNumeralsEncode;   FROM Strings IMPORT Append; FROM STextIO IMPORT WriteString, WriteLn;   CONST MaxChars = 15; (* 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded with these symbols. *)   TYPE TRomanNumeral = ARRAY [0 .. MaxChars - 1] OF CHAR;   PROCEDURE ToRoman(AV...
Give a code snippet in #Modula-2 Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Perl
Perl
#! /usr/bin/perl   use strict; use Image::Imlib2;   sub tograyscale { my $img = shift; my $gimg = Image::Imlib2->new($img->width, $img->height); for ( my $x = 0; $x < $gimg->width; $x++ ) { for ( my $y = 0; $y < $gimg->height; $y++ ) { my ( $r, $g, $b, $a ) = $img->query_pixel($x, $y); my $gray =...
Give a code snippet in #Perl Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. ...
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-...
#CLU
CLU
% NOTE: when compiling with Portable CLU, % this program needs to be merged with 'useful.lib' to get log() % % pclu -merge $CLUHOME/lib/useful.lib -compile fib_words.clu   % Yield pairs of (zeroes, ones) for each Fibonacci word % We don't generate the whole words, as that would take too much % memory. fib_words = iter...
Give a code snippet in #CLU 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  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Python
Python
'''Koch curve'''   from math import cos, pi, sin from operator import add, sub from itertools import chain     # kochSnowflake :: Int -> (Float, Float) -> (Float, Float) -> [(Float, Float)] def kochSnowflake(n, a, b): '''List of points on a Koch snowflake of order n, derived from an equilateral triangle with...
Give a code snippet in #Python Draw a Koch curve. See details: Koch curve
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Swift
Swift
func swap<T>(inout a: T, inout b: T) { (a, b) = (b, a) }
Give a code snippet in #Swift Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericit...
christopher/rosetta-code
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the...
#Bracmat
Bracmat
( Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan ...
Give a code snippet in #Bracmat Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then ...
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 ...
#Swift
Swift
import Foundation   // Allow for easy character checking extension String { subscript (i: Int) -> String { return String(Array(self)[i]) } }   func isPalindrome(str:String) -> Bool { if (count(str) == 0 || count(str) == 1) { return true } let removeRange = Range<String.Index>(start: ...
Give a code snippet in #Swift 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#Plain_English
Plain English
To run: Start up. Clear the screen. Imagine a box with the screen's left and the screen's top and the screen's right and the screen's bottom divided by 4. Make a color pinstripe given 1 pixel and the box. Draw the color pinstripe. Draw the next color pinstripe given the color pinstripe. Draw the next color pinstripe gi...
Give a code snippet in #Plain_English The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detec...
#Wren
Wren
import "/sort" for Sort import "/fmt" for Fmt   var sortedOutline = Fn.new { |originalOutline, ascending| var outline = originalOutline.toList // make copy in case we mutate it var indent = "" var del = "\x7f" var sep = "\0" var messages = [] if (outline[0].trimStart(" \t") != outline[0]) { ...
Give a code snippet in #Wren Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure c...
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 ...
#TI-89_BASIC
TI-89 BASIC
dotP([1, 3, –5], [4, –2, –1])
Give a code snippet in #TI-89_BASIC 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, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Phix
Phix
function toRoman(integer v) constant roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}, decml = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 } string res = "" integer val = v for i=1 to length(roman) do while val>=decml[i] do res &=...
Give a code snippet in #Phix Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a valu...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Maxima
Maxima
a: matrix([1, 2], [3, 4], [5, 6], [7, 8])$   b: matrix([1, 2, 3], [4, 5, 6])$   a . b; /* matrix([ 9, 12, 15], [19, 26, 33], [29, 40, 51], [39, 54, 69]) */
Give a code snippet in #Maxima Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th...
#Objeck
Objeck
  class Program { function : Total(n : Int, nuts : Int) ~ Int { k := 0; for(nuts *= n; k < n; k++;) { if(nuts % (n-1) <> 0) { return 0; }; nuts += nuts / (n-1) + 1; };   return nuts; }   function : Main(args : String[]) ~ Nil { for(n := 2; n < 10; n++;) { x := 0; t := 0; ...
Give a code snippet in #Objeck Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so...
christopher/rosetta-code
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Par...
#Haskell
Haskell
co9 n | n <= 8 = n | otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n   task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100]   task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100]
Give a code snippet in #Haskell Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#SenseTalk
SenseTalk
  put textDifference("kitten", "sitting") // --> 3 put textDifference("rosettacode", "raisethysword") // --> 8    
Give a code snippet in #SenseTalk This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Modula-2
Modula-2
MODULE addstr;   IMPORT InOut, NumConv, Strings;   VAR str1, str2 : Strings.String; num : CARDINAL; ok : BOOLEAN;   BEGIN str1 := "12345"; InOut.Write ('"'); InOut.WriteString (str1); InOut.WriteString ('" + 1 = '); NumConv.Str2Num (num, 10, str1, ok); ...
Give a code snippet in #Modula-2 Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#Pascal
Pascal
Program SelfDescribingNumber;   uses SysUtils;   function check(number: longint): boolean; var i, d: integer; a: string; count, w : array [0..9] of integer;   begin a := intToStr(number); for i := 0 to 9 do begin count[i] := 0; w[i] := 0; end; for i := 1 to length(a) do...
Give a code snippet in #Pascal Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when d...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int X, Y; [SetVid($101); \set 640x480 graphics with 8-bit color port($3C8):= 0; \set color registers with beautiful shades for X:= 0 to 256-1 do [port($3C9):= X>>1; \red port($3C9):= X>>3; \green ...
Give a code snippet in #XPL0 Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Latitude
Latitude
foo := Nil. if { foo nil?. } then { putln: "Foo is nil". } else { putln: "Foo is not nil". }.
Give a code snippet in #Latitude 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 la...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#PowerShell
PowerShell
  1..1000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 20 1001..2000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 1  
Give a code snippet in #PowerShell The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Sidef
Sidef
func roots_of_unity(n) { n.of { |j| exp(2i * Num.pi / n * j) } }   roots_of_unity(5).each { |c| printf("%+.5f%+.5fi\n", c.reals) }
Give a code snippet in #Sidef The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Objeck
Objeck
  class LCM { function : Main(args : String[]) ~ Nil { IO.Console->Print("lcm(35, 21) = ")->PrintLine(lcm(21,35)); }   function : lcm(m : Int, n : Int) ~ Int { return m / gcd(m, n) * n; }   function : gcd(m : Int, n : Int) ~ Int { tmp : Int; while(m <> 0) { tmp := m; m := n % m; n := tmp; }; ...
Give a code snippet in #Objeck Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that ha...
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...
#AutoHotkey
AutoHotkey
If (object == null) MsgBox, object is null
Give a code snippet in #AutoHotkey 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/Undefined_values
Undefined values
#PowerShell
PowerShell
  if (Get-Variable -Name noSuchVariable -ErrorAction SilentlyContinue) { $true } else { $false }  
Give a code snippet in #PowerShell
christopher/rosetta-code
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifi...
#AutoHotkey
AutoHotkey
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nMD4:`n" MD4(str)       ; MD4 =============================================================================== MD4(string, encoding = "utf-8") { return CalcStringHash(string, 0x8002, encoding) }   ; CalcAddrHash ===================================================...
Give a code snippet in #AutoHotkey Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in o...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#APL
APL
  ⍝ recursive dfn: dfnHailstone←{ c←⊃⌽⍵ ⍝ last element 1=c:1 ⍝ if it is 1, stop. ⍵,∇(1+2|c)⊃(c÷2)(1+3×c) ⍝ otherwise pick the next step, and append the result of the recursive call }   ⍝ tradfn version: ∇seq←hailstone n;next ⍝ Returns the hailstone sequence for a given number   seq←n ⍝ Ini...
Give a code snippet in #APL The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#X86_Assembly
X86 Assembly
    .NOLIST   ; The task can be completed in 48 and "half" steps: ; On the first pass ALL doors are opened. ; On the second pass every EVEN door is closed. ; So, instead of all closed, the doors can initially be: ; Every odd door open, every even door closed and start at pass 3. ; On 51st and all the next passes, onl...
Give a code snippet in #X86_Assembly 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,...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#Retro
Retro
needs casket::html' with casket::html'   : rnd ( -$ ) random 1000 mod toString ;   [ [ [ ] td [ "x" ] td [ "y" ] td [ "z" ] td ] tr [ [ "1" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr [ [ "2" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr [ [ "3" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr [ [ "4" ] td [ rnd ] td...
Give a code snippet in #Retro Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled wit...
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
#Lambdatalk
Lambdatalk
  1) working in a global scope   {def A 3} -> A // A is in the global scope {def B 4} -> B // B is in the global scopel {def MUL {lambda {:x :y} {* :x :y}}} -> MUL // MUL is a global function {MUL {A} {B}} ...
Give a code snippet in #Lambdatalk 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/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Oz
Oz
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
Give a code snippet in #Oz Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Haskell
Haskell
import Data.Complex   main = do let a = 1.0 :+ 2.0 -- complex number 1+2i let b = 4 -- complex number 4+0i -- 'b' is inferred to be complex because it's used in -- arithmetic with 'a' below. putStrLn $ "Add: " ++ show (a + b) putStrLn $ "Subtract: " ++ show (a - b) putStrLn $ "Multipl...
Give a code snippet in #Haskell A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\display...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Ada
Ada
integer f; text s, t;   f = 36; s = "integer f; text s, t;   f = 36; s = \"\";   o_text(cut(s, 0, f)); o_text(cut(s, 0, f - 1)); o_etext(cut(s, f - 1, 2)); o_text(cut(s, f + 1, 8888 - f)); o_text(cut(s, f, 8888 - f)); ";   o_text(cut(s, 0, f)); o_text(cut(s, 0, f - 1)); o_etext(cut(s, f - 1, 2)); o_text(cut(s, f + 1, 8...
Give a code snippet in #Ada A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   s...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#8086_Assembly
8086 Assembly
bits 16 cpu 8086 org 100h section .text jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Store the lowercase alphabet starting at [ES:DI] ;;; Destroys AX, CX, DI alph: mov cx,13 ; 2*13 words = 26 bytes mov ax,'ab' ; Do two bytes at once .loop: stosw ; Store AX at ES:DI and add 2 t...
Give a code snippet in #8086_Assembly Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#Perl
Perl
@dx = qw< -0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001 -0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014 0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051 0.047 -0.095 0.695 0.340 -0.182 0.287 0.213 -0.423 -0.021 -0.134...
Give a code snippet in #Perl W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a ...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Perl
Perl
use ntheory qw/forperm/; use Set::CrossProduct;   sub four_sq_permute { my($list) = @_; my @solutions; forperm { @c = @$list[@_]; push @solutions, [@c] if check(@c); } @$list; print +@solutions . " unique solutions found using: " . join(', ', @$list) . "\n"; return @solutions; }   ...
Give a code snippet in #Perl 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Kotlin
Kotlin
// version 1.0.5-2   fun main(args: Array<String>) { val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9) println(array.joinToString(" "))   val filteredArray = array.filter{ it % 2 == 0 } println(filteredArray.joinToString(" "))   val mutableList = array.toMutableList() mutableList.retainAll { it % 2...
Give a code snippet in #Kotlin Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/P-Adic_square_roots
P-Adic square roots
Task. Convert rational a/b to its approximate p-adic square root. To check the result, square the root and construct rational m/n to compare with radicand a/b. For rational reconstruction Lagrange's lattice basis reduction algorithm is used. Recipe: find root x1 modulo p and build a sequence of solutions f(xk) ≡ 0 ...
#Haskell
Haskell
{-# LANGUAGE KindSignatures, DataKinds #-}   import Data.Ratio import Data.List (find) import GHC.TypeLits import Padic   pSqrt :: KnownNat p => Rational -> Padic p pSqrt r = res where res = maybe Null mkUnit series (a, b) = (numerator r, denominator r) series = case modulo res of   2 | eqMod 4 a...
Give a code snippet in #Haskell Task. Convert rational a/b to its approximate p-adic square root. To check the result, square the root and construct rational m/n to compare with radicand a/b. For rational reconstruction Lagrange's lattice basis reduction algorithm is used. Recipe: find root x1 modulo p and build 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 ...
#PureBasic
PureBasic
If OpenConsole("")=0 : End 1 : EndIf If ReadFile(0,"./Data/unixdict.txt")=0 : End 2 : EndIf NewList dict$()   While Eof(0)=0 : AddElement(dict$()) : dict$()=Trim(ReadString(0)) : Wend : CloseFile(0)   While FirstElement(dict$()) buf$=dict$() : DeleteElement(dict$()) If buf$="" : Continue : EndIf xbuf$=ReverseSt...
Give a code snippet in #PureBasic 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 ...
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.
#Sidef
Sidef
var dt = frequire('DateTime::Format::Strptime')   var input = 'March 7 2009 7:30pm EST' input.sub!('EST', 'America/New_York')   say dt.strptime('%b %d %Y %I:%M%p %O', input) \ .add(hours => 12) \ .set_time_zone('America/Edmonton') \ .format_cldr('MMMM d yyyy h:mma zzz...
Give a code snippet in #Sidef 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/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.
#NewLISP
NewLISP
(delete-file "input.txt") (delete-file "/input.txt") (remove-dir "docs") (remove-dir "/docs")
Give a code snippet in #NewLISP 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/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.
#Maple
Maple
FileTools:-Remove("input.txt"); FileTools:-RemoveDirectory("docs"); FileTools:-Remove("/input.txt"); FileTools:-RemoveDirectory("/docs");  
Give a code snippet in #Maple 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/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 ...
#11l
11l
F mdroot(n) V count = 0 V mdr = n L mdr > 9 V m = mdr V digits_mul = 1 L m != 0 digits_mul *= m % 10 m = m I/ 10 mdr = digits_mul count++ R (count, mdr)   print(‘Number: (MP, MDR)’) print(‘====== =========’) L(n) (123321, 7739, 893, 899998) print(‘#6: ’.fo...
Give a code snippet in #11l 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/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#Scala
Scala
import java.awt.Color import scala.collection.mutable   object Flood { def floodFillStack(bm:RgbBitmap, x: Int, y: Int, targetColor: Color): Unit = { // validate if (bm.getPixel(x,y) == targetColor) return   // vars val oldColor = bm.getPixel(x,y) val pixels = new mutable.Stack[(Int,Int)]   //...
Give a code snippet in #Scala Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Rust
Rust
#![feature(conservative_impl_trait)] fn main() { let cube = |x: f64| x.powi(3); let cube_root = |x: f64| x.powf(1.0 / 3.0);   let flist  : [&Fn(f64) -> f64; 3] = [&cube , &f64::sin , &f64::cos ]; let invlist: [&Fn(f64) -> f64; 3] = [&cube_root, &f64::asin, &f64::acos];   let result = flist....
Give a code snippet in #Rust 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 fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
SumOfSquares[x_]:=Total[x^2] SumOfSquares[{1,2,3,4,5}]
Give a code snippet in #Mathematica.2FWolfram_Language Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#360_Assembly
360 Assembly
* Chinese zodiac 10/03/2019 CHINEZOD CSECT USING CHINEZOD,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST...
Give a code snippet in #360_Assembly Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#EchoLisp
EchoLisp
  ;; value for 'even' numbers (define (even-val n) (if (> n 4) (+ n n -9) (+ n n)))   ;;Luhn test ;; input : a string of decimal digits ;; output #t or #f (define (valid nums (odd #f )) (let ((nums (map string->number (reverse (string->list nums))))) (= 0 (modulo (for/sum ((n nums)) (set! odd (not odd)...
Give a code snippet in #EchoLisp The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order...
christopher/rosetta-code
http://rosettacode.org/wiki/ASCII_art_diagram_converter
ASCII art diagram converter
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RC...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program asciiDiagram64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include ...
Give a code snippet in #AArch64_Assembly Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#C.2B.2B
C++
Trigraph Replacement letter  ??( [  ??) ]  ??< {  ??> }  ??/ \  ??= #  ??' ^  ??! |  ??- ~
Give a code snippet in #C.2B.2B Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling ...
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#D
D
import std.stdio, std.traits, std.conv;   string middleThreeDigits(T)(in T n) pure nothrow if (isIntegral!T) { auto s = n < 0 ? n.text[1 .. $] : n.text; auto len = s.length; if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; auto mid = len / 2; return s[mid - 1 .. mid + 2]; }   ...
Give a code snippet in #D Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#AppleScript
AppleScript
------------------ TOKENIZE WITH ESCAPING ----------------   -- tokenize :: String -> Character -> Character -> [String] on tokenize(str, delimChar, chrEsc)   script charParse -- Record: {esc:Bool, token:String, tokens:[String]} -- charParse :: Record -> Character -> Record on |λ|(a, x) ...
Give a code snippet in #AppleScript Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#PureBasic
PureBasic
Procedure SetFileSize(File$, length.q) Protected fh, pos, i If FileSize(File$) < length Debug "File to small, is a directory or does not exist." ProcedureReturn #False Else fh = OpenFile(#PB_Any, File$) FileSeek(fh, length) TruncateFile(fh) CloseFile(fh) EndIf ProcedureReturn #True En...
Give a code snippet in #PureBasic Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Retro
Retro
: pow ( bp-n ) 1 swap [ over * ] times nip ;
Give a code snippet in #Retro Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or pro...
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...
#6502_Assembly
6502 Assembly
  \ 99 bottles of beer on the wall: : allout "no more bottles" ; : just-one "1 bottle"  ; : yeah! dup . " bottles" ;   [ ' allout , ' just-one , ' yeah! , ] var, bottles   : .bottles dup 2 n:min bottles @ swap caseof ; : .beer .bottles . " of beer" . ; : .wall .beer " on the wall" . ; : .take " Take o...
Give a code snippet in #6502_Assembly 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 w...
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...
#Prolog
Prolog
% the test run_length :- L = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", writef('encode %s\n', [L]), encode(L, R), writeln(R), nl, writef('decode %w\n', [R]), decode(R, L1), writeln(L1).   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % encode % % trans...
Give a code snippet in #Prolog 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/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#Objective-C
Objective-C
NSString *dir = @"/foo/bar";   // Pre-OS X 10.5 NSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir]; // OS X 10.5+ NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL];   for (NSString *file in contents) if ([[file pathExtension] isEqualToString:@"...
Give a code snippet in #Objective-C Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single direc...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Nim
Nim
import imageman   const Black = ColorRGBU [byte 0, 0, 0] # For background. Red = ColorRGBU [byte 255, 0, 0] # For triangle.   proc drawSierpinski(img: var Image; txy: array[1..6, float]; levelsYet: Natural) = var nxy: array[1..6, float] if levelsYet > 0: for i in 1..6: let pos = if i < 5: i + 2 else...
Give a code snippet in #Nim Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#C.2B.2B
C++
#include <iostream> #include <vector>   int main(int argc, char* argv[]) { std::vector<char> ls(3); ls[0] = 'a'; ls[1] = 'b'; ls[2] = 'c'; std::vector<char> us(3); us[0] = 'A'; us[1] = 'B'; us[2] = 'C'; std::vector<int> ns(3); ns[0] = 1; ns[1] = 2; ns[2] = 3;   std::vector<char>::const_iterator lIt = l...
Give a code snippet in #C.2B.2B Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this ex...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#Io
Io
  write("Goodbye, World!")  
Give a code snippet in #Io 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#AutoHotkey
AutoHotkey
MsgBox % stor(444)   stor(value) { romans = M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I M := 1000 CM := 900 D := 500 CD := 400 C := 100 XC := 90 L := 50 XL := 40 X := 10 IX := 9 V := 5 IV := 4 I := 1 Loop, Parse, romans, `, { While, value >= %A_LoopField% { result .= A_LoopField ...
Give a code snippet in #AutoHotkey Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#FOCAL
FOCAL
01.10 D 3;S T=0 01.20 F X=1,9;T %1,D(X) 01.30 T !;A "HOW MANY",R 01.40 I (R-1)1.3;I (9-R)1.3 01.50 D 5;S T=T+1 01.60 D 4;I (A-9)1.2 01.70 D 1.2;T !"CORRECT! ATTEMPTS",%4,T,! 01.80 Q   02.10 S A=10*FRAN();S A=A-FITR(A)   03.10 F X=1,9;S D(X)=X 03.20 F X=1,8;D 2;S Y=X+FITR((10-X)*A);S A=D(X);S D(X)=D(Y);S D(Y)=A 03.30 D ...
Give a code snippet in #FOCAL Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The sc...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Go
Go
package main   import ( "fmt" "math/rand" "strings" "time" )   func main() { rand.Seed(time.Now().UnixNano()) p := newPuzzle() p.play() }   type board [16]cell type cell uint8 type move uint8   const ( up move = iota down right left )   func randMove() move { return move(rand.Intn(4)) }   var solvedBoard = b...
Give a code snippet in #Go Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#GUISS
GUISS
Start,Programs,Accessories,Sound Recorder,Button:Record
Give a code snippet in #GUISS Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate....
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#FileMaker
FileMaker
    #May 10th., 2018.   Set Error Capture [On] Allow User Abort [Off] # Set default number of minutes Set Variable [$maxduration; Value:1] # Ask user for a desired duration of the test Show Custom Dialog [ "Setup"; "Enter the number of minutes (0,1-15, 6s increments) you would like this test to run.¶" & "Hit an...
Give a code snippet in #FileMaker Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for bein...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#QB64
QB64
  DefStr S DefInt I string1 = "abcdefghijklmnopqrstuvwxyz" substring = "klm" Dim Achar As String * 1 Istart = 6 Ilength = 10 Achar = "c"   ' starting from n characters in and of m length; Print Mid$(string1, Istart, Ilength) ' starting from n characters in, up to the end of the string; Print Mid$(string...
Give a code snippet in #QB64 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_sf_gamma.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif   /* very simple approximation */ double st_gamma(double x) { return sqrt(2.0*M_PI/x)*pow(x/M_E, x); }   #define A 12 double sp_gamma(double z) { const int a = A; static d...
Give a code snippet in #C Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#ColdFusion
ColdFusion
  <cfset zeroPowerTag = 0^0> <cfoutput>"#zeroPowerTag#"</cfoutput>  
Give a code snippet in #ColdFusion Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#MUMPS
MUMPS
DTZ WRITE !,"Date format 3: ",$ZDATE($H,3) WRITE !,"Or ",$ZDATE($H,12),", ",$ZDATE($H,9) QUIT
Give a code snippet in #MUMPS This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#Factor
Factor
USING: arrays assocs concurrency.combinators concurrency.semaphores formatting hashtables http.client io json.reader kernel math math.parser sequences splitting urls.encoding ; IN: rosetta-code.count-examples   CONSTANT: list-url "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Prog...
Give a code snippet in #Factor task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'...
christopher/rosetta-code
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function shou...
#BBC_BASIC
BBC BASIC
file% = FNopentempfile IF file% = 0 ERROR 100, "Failed to open temp file" PRINT #file%, "Hello world!" PTR#file% = 0 INPUT #file%, message$ CLOSE #file% PRINT message$ END   DEF FNopentempfile LOCAL pname%, hfile%, chan% OPEN_EXISTING = 3 FILE_FLAG...
Give a code snippet in #BBC_BASIC Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race condit...
christopher/rosetta-code
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion
Angles (geometric), normalization and conversion
This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 360 degrees, also shown as 360º ...
#Racket
Racket
#lang racket   (define (rem n m) (let* ((m (abs m)) (-m (- m))) (let recur ((n n)) (cond [(< n -m) (recur (+ n m))] [(>= n m) (recur (- n m))] [else n]))))   (define 2.pi (* 2 pi))   (define (deg->deg a) (rem a 360)) (define (grad->grad a) (rem a 400)) (define (mil->mil a) (rem a 640...
Give a code snippet in #Racket This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#J
J
  NB. legit { , and } do not follow a legit backslash: legit=: 1,_1}.4>(3;(_2[\"1".;._2]0 :0);('\';a.);0 _1 0 1)&;:&.(' '&,) 2 1 1 1 NB. result 0 or 1: initial state 2 2 1 2 NB. result 2 or 3: after receiving a non backslash 1 2 1 2 NB. result 4 or 5: after receiving a backslash )   expand=:3 :0 Ch=. u:inv y...
Give a code snippet in #J Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been...
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) ...
#Pascal
Pascal
sub generate { my $n = shift; my $str = '[' x $n; substr($str, rand($n + $_), 0) = ']' for 1..$n; return $str; }   sub balanced { shift =~ /^ (\[ (?1)* \])* $/x; }   for (0..8) { my $input = generate($_); print balanced($input) ? " ok:" : "bad:", " '$input'\n"; }
Give a code snippet in #Pascal 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/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#COBOL
COBOL
  *> *> Kernighan large earthquake problem *> Tectonics: cobc -xj kernighan-earth-quakes.cob *> quakes.txt with the 3 sample lines *> ./kernighan-earth-quakes *> >>SOURCE FORMAT IS FREE identification division. program-id. quakes.   e...
Give a code snippet in #COBOL Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines ...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#J
J
((i.32) e. 32 26 23 22 16 12 11 10 8 7 5 4 2 1 0) 128!:3 'The quick brown fox jumps over the lazy dog' _3199229127
Give a code snippet in #J Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the ini...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Nim
Nim
# Knapsack. Recursive solution.   import strformat import tables   # Description of an item. type Item = tuple[name: string; weight, value, pieces: int]   # List of available items. const Items: seq[Item] = @[("map", 9, 150, 1), ("compass", 13, 35, 1), ("water", 153...
Give a code snippet in #Nim A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weigh...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Applesoft_BASIC
Applesoft BASIC
100 INPUT "HQ9+ : "; I$ 110 LET J$ = I$ + CHR$(13) 120 LET H$ = "HELLO, WORLD!" 130 LET B$ = "BOTTLES OF BEER" 140 LET W$ = " ON THE WALL" 150 LET W$ = W$ + CHR$(13) 160 FOR I = 1 TO LEN(I$) 170 LET C$ = MID$(J$, I, 1) 180 IF C$ = "H" THEN PRINT H$ 190 IF C$ = "Q" THEN PRINT I$ 200 LET A = A + (C$ = "+"...
Give a code snippet in #Applesoft_BASIC Task Implement a   HQ9+   interpreter or compiler.
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Open "input.txt" For Input Encoding "ascii" As #1 Dim fileLen As LongInt = Lof(1) '' get file length in bytes Dim buffer As String = Space(fileLen) '' allocate a string of size 'fileLen' bytes Get #1, 1, buffer '' read all data from start of file into the buffer Print buffer '' print to console buf...
Give a code snippet in #FreeBASIC 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 i...
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...
#FutureBasic
FutureBasic
include "NSLog.incl"   long num do num = rnd(20) - 1 NSLog(@"%ld",num) until ( num == 10 )   HandleEvents
Give a code snippet in #FutureBasic 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 l...
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 ...
#Oz
Oz
declare fun {MaxLicenses Filename ?Times} InUse = {NewCell 0} MaxInUse = {NewCell 0} MaxTimes = {NewCell nil} in for Job in {ReadLines Filename} do case {List.take Job 11} of "License OUT" then InUse := @InUse + 1 if @InUse > @MaxInUse then MaxInUse := @InUse Ma...
Give a code snippet in #Oz 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 checko...
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 ...
#PowerShell
PowerShell
$h = @{ 'a' = 1; 'b' = 2; 'c' = 3 }
Give a code snippet in #PowerShell 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Ruby
Ruby
ruby -le'16.times{|y|print" "*(15-y),*(0..y).map{|x|~y&x>0?" ":" *"}}'
Give a code snippet in #Ruby Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
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 |...
#Raku
Raku
# explicit concatentation $_ = 'byte'; $_ = 'kilo' ~ $_; .say;   # interpolation as concatenation $_ = 'buck'; $_ = "mega$_"; .say;   # lvalue substr $_ = 'bit'; substr-rw($_,0,0) = 'nano'; .say;   # regex substitution $_ = 'fortnight'; s[^] = 'micro'; .say;   # reversed append assignment $_ = 'cooper'; $_ [R~]= 'mini...
Give a code snippet in #Raku 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Logo
Logo
to hail.next :n output ifelse equal? 0 modulo :n 2 [:n/2] [3*:n + 1] end   to hail.seq :n if :n = 1 [output [1]] output fput :n hail.seq hail.next :n end   show hail.seq 27 show count hail.seq 27   to max.hail :n localmake "max.n 0 localmake "max.length 0 repeat :n [if greater? count hail.seq repcount  :max...
Give a code snippet in #Logo The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Dimensions
Terminal control/Dimensions
Determine the height and width of the terminal, and store this information into variables for subsequent use.
#Forth
Forth
variable term-width variable term-height   s" gforth" environment? [if] 2drop form ( height width ) [else] \ SwiftForth get-size ( width height ) swap [then] term-width ! term-height !
Give a code snippet in #Forth Determine the height and width of the terminal, and store this information into variables for subsequent use.
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#E
E
def sleep(milliseconds :int, nextThing) { stdout.println("Sleeping...") timer.whenPast(timer.now() + milliseconds, fn { stdout.println("Awake!") nextThing() }) }
Give a code snippet in #E Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for...
christopher/rosetta-code
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only...
#Perl
Perl
use strict; use warnings;   my $file = 'nonogram_problems.txt'; open my $fd, '<', $file or die "$! opening $file";   while(my $row = <$fd> ) { $row =~ /\S/ or next; my $column = <$fd>; my @rpats = makepatterns($row); my @cpats = makepatterns($column); my @rows = ( '.' x @cpats ) x @rpats; for( my $prev = ...
Give a code snippet in #Perl A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs...
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#ALGOL_68
ALGOL 68
BEGIN INT examples=10, classes=5; MODE SEMIPRIME = STRUCT ([examples]INT data, INT count); [classes]SEMIPRIME semi primes; PROC num facs = (INT n) INT : COMMENT Return number of not necessarily distinct prime factors of n. Not very efficient for large n ... COMMENT BEGIN INT tf := 2, residue ...
Give a code snippet in #ALGOL_68 A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,  ...
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 ...
#Sidef
Sidef
func playfair(key, from = 'J', to = (from == 'J' ? 'I' : '')) {   func canon(str) { str.gsub(/[^[:alpha:]]/, '').uc.gsub(from, to) }   var m = canon(key + ('A'..'Z' -> join)).chars.uniq.slices(5)   var :ENC = gather { m.each { |r| for i,j in (^r ~X ^r) { i == ...
Give a code snippet in #Sidef 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 e...
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 ...
#8080_Assembly
8080 Assembly
org 100h jmp test ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Given an array of bytes starting at HL with length BC, ;; remove all duplicates in the array. The new end of the array ;; is returned in HL. A page of memory (256 bytes) is required ;; to mark which bytes have been seen. ...
Give a code snippet in #8080_Assembly 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 | ...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#C
C
#include <iostream>   struct SpecialVariables { int i = 0;   SpecialVariables& operator++() { // 'this' is a special variable that is a pointer to the current // class instance. It can optionally be used to refer to elements // of the class. this->i++; // has the same meani...
Give a code snippet in #C Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
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
#Icon_and_Unicon
Icon and Unicon
procedure main() write( "Hello world!" ) end
Give a code snippet in #Icon_and_Unicon 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/Standa...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Clojure
Clojure
(defn quadratic "Compute the roots of a quadratic in the form ax^2 + bx + c = 1. Returns any of nil, a float, or a vector." [a b c] (let [sq-d (Math/sqrt (- (* b b) (* 4 a c))) f #(/ (% b sq-d) (* 2 a))] (cond (neg? sq-d) nil (zero? sq-d) (f +) (pos? sq-d) [(f +) (f -)] ...
Give a code snippet in #Clojure This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . You...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#ERRE
ERRE
  PROGRAM MEANS   DIM A[9]   PROCEDURE ARITHMETIC_MEAN(A[]->M) LOCAL S,I% NEL%=UBOUND(A,1) S=0 FOR I%=0 TO NEL% DO S+=A[I%] END FOR M=S/(NEL%+1) END PROCEDURE   PROCEDURE GEOMETRIC_MEAN(A[]->M) LOCAL S,I% NEL%=UBOUND(A,1) S=1 FOR I%=0 TO NEL% DO ...
Give a code snippet in #ERRE Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldot...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Dyalect
Dyalect
let a = 6 let b = 4   print("sum = \(a+b)") print("difference = \(a-b)") print("product = \(a*b)") print("Integer quotient = \(a/b)") print("Remainder = \(a%b)")
Give a code snippet in #Dyalect 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/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Scheme
Scheme
(define (next-generation left petri-dish right) (if (null? petri-dish) (list) (cons (if (= (+ left (car petri-dish) (if (null? (cdr petri-dish)) right (cadr petri-dish))) 2) 1...
Give a code snippet in #Scheme Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the curren...
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#Groovy
Groovy
BigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3 String nn boolean first = true   while (true) { (nn, first, q, r, t, k, n, l) = (4*q + r - t < n*t) \ ? ["${n}${first?'.':''}", false, 10*q, 10*(r - n*t), t , k , 10*(3*q + r)/t - 10*n , l ] \  : ['' , first, q*k , (2*q +...
Give a code snippet in #Groovy Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal seq...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Ruby
Ruby
class String   SoundexChars = 'BFPVCGJKQSXZDTLMNR' SoundexNums = '111122222222334556' SoundexCharsEx = '^' + SoundexChars SoundexCharsDel = '^A-Z'   # desc: http://en.wikipedia.org/wiki/Soundex def soundex(census = true) str = self.upcase.delete(SoundexCharsDel) str[0,1] + str[1..-1].delete(Soundex...
Give a code snippet in #Ruby Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to rais...
#Io
Io
U0 := Exception clone U1 := Exception clone   foo := method( for(i,1,2, try( bar(i) )catch( U0, "foo caught U0" print )pass ) ) bar := method(n, baz(n) ) baz := method(n, if(n == 1,U0,U1) raise("baz with n = #{n}" interpolate) )   foo
Give a code snippet in #Io 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 ...
christopher/rosetta-code