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/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurren...
#AutoHotkey
AutoHotkey
answers := [ (join "It is certain", "It is decidedly so", "Without a doubt","Yes, definitely", "You may rely on it", "As I see it, yes","Most likely", "Outlook good", "Signs point to yes", "Yes","Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now","Concentrate and ask again", "Don...
Give a code snippet in #AutoHotkey Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#CoffeeScript
CoffeeScript
#translated from JavaScript example class Card constructor: (@pip, @suit) ->   toString: => "#{@pip}#{@suit}"   class Deck pips = '2 3 4 5 6 7 8 9 10 J Q K A'.split ' ' suits = '♣ ♥ ♠ ♦'.split ' '   constructor: (@cards) -> if not @cards? @cards = [] for suit in suits for pip in pips ...
Give a code snippet in #CoffeeScript Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the cu...
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 |...
#ColdFusion
ColdFusion
  <cfoutput> <cfset who = "World!"> #"Hello " & who# </cfoutput>  
Give a code snippet in #ColdFusion 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 Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Julia
Julia
url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" wordlist = open(readlines, download(url))   wsort(word::AbstractString) = join(sort(collect(word)))   function anagram(wordlist::Vector{<:AbstractString}) dict = Dict{String, Set{String}}() for word in wordlist sorted = wsort(word) push...
Give a code snippet in #Julia When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in t...
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#PicoLisp
PicoLisp
(de shuffle (Lst) (by '(NIL (rand)) sort Lst) )   # Extend this class with a `next-guess>` method and a `str>` method. (class +Strategy +Entity) (dm prev-drawer> (Num) (=: prev Num) )   (class +Random +Strategy) (dm T (Prisoner) (=: guesses (nth (shuffle (range 1 100)) 51)) ) (dm next-guess> () (pop (:: gue...
Give a code snippet in #PicoLisp The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners star...
christopher/rosetta-code
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed)....
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[NextInSequence, EKGSequence] NextInSequence[seq_List] := Module[{last, new = 1, holes, max, sel, found, i}, last = Last[seq]; max = Max[seq]; holes = Complement[Range[max], seq]; sel = SelectFirst[holes, Not[CoprimeQ[last, #]] &]; If[MissingQ[sel], i = max; found = False; While[! found, ...
Give a code snippet in #Mathematica.2FWolfram_Language The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its ...
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...
#Java
Java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;   class Hailstone {   public static List<Long> getHailstoneSequence(long n) { if (n <= 0) throw new IllegalArgumentException("Invalid starting sequence number"); List<Long> list = new ArrayList<Long>(); ...
Give a code snippet in #Java 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/Erd%C3%B6s-Selfridge_categorization_of_primes
Erdös-Selfridge categorization of primes
A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1. The task is first to display the first 200 primes allocated to their category, then assign the firs...
#Wren
Wren
import "./math" for Int import "./fmt" for Fmt   var limit = (1e6.log * 1e6 * 1.2).floor // should be more than enough var primes = Int.primeSieve(limit)   var prevCats = {}   var cat // recursive cat = Fn.new { |p| if (prevCats.containsKey(p)) return prevCats[p] var pf = Int.primeFactors(p+1) if (pf.all {...
Give a code snippet in #Wren A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1. The task is first to display the first 200 primes allocated to their ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Red
Red
>> view [ text "Hello World !"]
Give a code snippet in #Red Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#AutoHotkey
AutoHotkey
AutoTrim, Off draw = ( ______ __ __ __ __ /\ __ \/\ \_\ \/\ \/ / \ \ __ \ \ __ \ \ _"-. \ \_\ \_\ \_\ \_\ \_\ \_\ \/_/\/_/\/_/\/_/\/_/\/_/ ) Gui, +ToolWindow Gui, Color, 1A1A1A, 1A1A1A Gui, Font, s8 cLime w800, Courier New Gui, Add, text, x4 y0 , % " " draw Gui, Show, w192 h82, AHK in 3D return ...
Give a code snippet in #AutoHotkey Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Clojure
Clojure
(ns sleepsort.core (require [clojure.core.async :as async :refer [chan go <! <!! >! timeout]]))   (defn sleep-sort [l] (let [c (chan (count l))] (doseq [i l] (go (<! (timeout (* 1000 i))) (>! c i))) (<!! (async/into [] (async/take (count l) c)))))
Give a code snippet in #Clojure 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/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-strea...
#Java
Java
import java.util.Iterator; import java.util.List; import java.util.Objects;   public class StreamMerge { private static <T extends Comparable<T>> void merge2(Iterator<T> i1, Iterator<T> i2) { T a = null, b = null;   while (i1.hasNext() || i2.hasNext()) { if (null == a && i1.hasNext()) { ...
Give a code snippet in #Java 2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#X86_Assembly
X86 Assembly
  ; x86_64 linux nasm   struc Stack maxSize: resb 8 currentSize: resb 8 contents: endStruc   section .data   soError: db "Stack Overflow Exception", 10 seError: db "Stack Empty Error", 10     section .text   createStack: ; IN: max number of elements (rdi) ; OUT: pointer to new stack (rax) push rdi xor rdx, rd...
Give a code snippet in #X86_Assembly 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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stac...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Ruby
Ruby
require 'tk'   window = TkRoot::new() window::mainloop()
Give a code snippet in #Ruby Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Frege
Frege
module gcd.GCD where   pure native parseInt java.lang.Integer.parseInt :: String -> Int   gcd' a 0 = a gcd' a b = gcd' b (a `mod` b)   main args = do (a:b:_) = args println $ gcd' (parseInt a) (parseInt b)  
Give a code snippet in #Frege Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Common_Lisp
Common Lisp
float = [ sign ], { decimal-digit }, decimal-point, decimal-digit, { decimal-digit }, [exponent] | [ sign ], decimal-digit, { decimal-digit }, [ decimal-point, { decimal-digit } ], exponent ; exponent = exponent-marker, [ sign ], decimal-digit, { decimal-digit } ; sign = "+" | "-" ; decimal-point = "." ; dec...
Give a code snippet in #Common_Lisp Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression o...
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#Elena
Elena
  singleton Singleton { // ... }  
Give a code snippet in #Elena A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 ...
#C.23
C#
using System; using System.Linq;   namespace CountingSort { class Program { static void Main(string[] args) { Random rand = new Random(); // Just for creating a test array int[] arr = new int[100]; // o...
Give a code snippet in #C.23 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#VBScript
VBScript
  Function dns_query(url,ver) Set r = New RegExp r.Pattern = "Pinging.+?\[(.+?)\].+" Set objshell = CreateObject("WScript.Shell") Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) WScript.StdOut.WriteLine "URL: " & url Do Until objexec.StdOut.AtEndOfStream line = objexec.StdOut.ReadLine ...
Give a code snippet in #VBScript DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
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
#JavaScript
JavaScript
(function(steps) { 'use strict'; var i, tmp, s1 = '0', s2 = '1'; for (i = 0; i < steps; i++) { tmp = s1; s1 += s2; s2 += tmp; } console.log(s1); })(6);
Give a code snippet in #JavaScript 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
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 ...
#Erlang
Erlang
% Implemented by Arjun Sunel -module(func_definition). -export([main/0]).   main() -> K=multiply(3,4), io :format("~p~n",[K]).   multiply(A,B) -> case {A,B} of {A, B} -> A * B end.
Give a code snippet in #Erlang 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_constant
Magic constant
A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant. EG A 3 x 3 magic square always sums to ...
#jq
jq
# To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   # nth-root def iroot($n): . as $in | if $n == 1 then . else (. < 0) as $neg | if $neg and (n % 2) == 0 then "Cannot take the \($n)th root of a negative number." | er...
Give a code snippet in #jq A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant. EG A 3 x 3 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;; Count jewels. ;;; Input: BC = jewels, DE = stones. ;;; Output: BC = count ;;; Destroyed: A, DE, HL jewel: lxi h,jarr ; Zero out the page of memory xra a jzero: mov m,a inr l jnz jzero jrjwl: ldax b ; Get jewel inx b mov l,a ; Mark the corresponding byte in the array inr m ana a ; If '...
Give a code snippet in #8080_Assembly Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lo...
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
#Delphi
Delphi
  program ProjectGoodbye; {$APPTYPE CONSOLE} begin WriteLn('Hello world!'); end.  
Give a code snippet in #Delphi Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Kotlin
Kotlin
data class Square(val x : Int, val y : Int)   val board = Array(8 * 8, { Square(it / 8 + 1, it % 8 + 1) }) val axisMoves = arrayOf(1, 2, -1, -2)   fun <T> allPairs(a: Array<T>) = a.flatMap { i -> a.map { j -> Pair(i, j) } }   fun knightMoves(s : Square) : List<Square> { val moves = allPairs(axisMoves).filter{ Math....
Give a code snippet in #Kotlin Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Go
Go
package main   import "fmt"   func ord(n int) string { s := "th" switch c := n % 10; c { case 1, 2, 3: if n%100/10 == 1 { break } switch c { case 1: s = "st" case 2: s = "nd" case 3: s = "rd" } } ...
Give a code snippet in #Go Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show he...
christopher/rosetta-code
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If t...
#Nim
Nim
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle );   my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9;   my $mebooks = my $youbooks = 0;   my $me = substr $deck,...
Give a code snippet in #Nim Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a give...
christopher/rosetta-code
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are n...
#Swift
Swift
extension Sequence { func take(_ n: Int) -> [Element] { var res = [Element]()   for el in self { guard res.count != n else { return res }   res.append(el) }   return res } }   extension String { func isEsthetic(base: Int = 10) -> Bool { zip(dropFirst(0), dropFirst()) ...
Give a code snippet in #Swift An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero diff...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Yabasic
Yabasic
  dim fruta$(3) read fruta$(1), fruta$(2), fruta$(3) data "apple", "orange", "pear"   print arraysize(fruta$(),1) print fruta$(2) end  
Give a code snippet in #Yabasic Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter fre...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#11l
11l
F cline(n, x, y, cde) print(String(cde[0]).rjust(n + 1)‘’ (cde[1] * (9 * x - 1))‘’ cde[0]‘’ (I cde.len > 2 {String(cde[2]).rjust(y + 1)} E ‘’))   F cuboid(x, y, z) cline(y + 1, x, 0, ‘+-’) L(i) 1 .. y cline(y - i + 1, x, i - 1, ‘/ |’) cline(0, x, y, ‘+-|’) ...
Give a code snippet in #11l Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Common_Lisp
Common Lisp
((defun select-nth (n list predicate) "Select nth element in list, ordered by predicate, modifying list." (do ((pivot (pop list)) (ln 0) (left '()) (rn 0) (right '())) ((endp list) (cond ((< n ln) (select-nth n left predicate)) ((eql n ln) pivot) ((< n (+ ln rn 1))...
Give a code snippet in #Common_Lisp Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle v...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#OCaml
OCaml
# let find_index pred lst = let rec loop n = function [] -> raise Not_found | x::xs -> if pred x then n else loop (n+1) xs in loop 0 lst;; val find_index : ('a -> bool) -> 'a list -> int = <fun>   # let haystack = ["Zig";"Zag";"Wally";"Ronald";"Bush";"Krusty";"Ch...
Give a code snippet in #OCaml Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle th...
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
#ChucK
ChucK
int a;
Give a code snippet in #ChucK 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/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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringLength["Hello world"]
Give a code snippet in #Mathematica.2FWolfram_Language 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 u...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 ...
#ActionScript
ActionScript
//Comparison function must returns Numbers even though it deals with integers. function compare(x:int, y:int):Number { return Number(x-y); } var nums:Vector.<int> = Vector.<int>([5,12,3,612,31,523,1,234,2]); nums.sort(compare);
Give a code snippet in #ActionScript 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 | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Harbour
Harbour
PROCEDURE Main()   LOCAL cStr   FOR EACH cStr IN { "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" } ? PadL( cStr, 10 ), iif( Blockable( cStr ), "can", "cannot" ), "be spelled with blocks." NEXT   RETURN   STATIC FUNCTION Blockable( cStr )   LOCAL blocks := { ; "BO", "XK", "DQ", "C...
Give a code snippet in #Harbour ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alpha...
christopher/rosetta-code
http://rosettacode.org/wiki/Minimal_steps_down_to_1
Minimal steps down to 1
Given: A starting, positive integer (greater than one), N. A selection of possible integer perfect divisors, D. And a selection of possible subtractors, S. The goal is find the minimum number of steps necessary to reduce N down to one. At any step, the number may be: Divided by any member of D if it is perfect...
#Raku
Raku
use Lingua::EN::Numbers;   for [2,3], 1, 2000, [2,3], 1, 50000, [2,3], 2, 2000, [2,3], 2, 50000 -> @div, $sub, $limit { my %min = 1 => {:op(''), :v(1), :s(0)}; (2..$limit).map( -> $n { my @ops; @ops.push: ($n / $_, "/$_") if $n %% $_ for @div; @ops.push: ($n - $sub, "-$sub") i...
Give a code snippet in #Raku Given: A starting, positive integer (greater than one), N. A selection of possible integer perfect divisors, D. And a selection of possible subtractors, S. The goal is find the minimum number of steps necessary to reduce N down to one. At any step, the number may be: Divided by an...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#REXX
REXX
/*REXX program calculates and displays K-fact (multifactorial) of non-negative integers.*/ numeric digits 1000 /*get ka-razy with the decimal digits. */ parse arg num deg . /*get optional arguments from the C.L. */ if num=='' | num=="," then num=15 ...
Give a code snippet in #REXX The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#MAXScript
MAXScript
e -- Euler's number pi -- pi log x -- natural logarithm log10 x -- log base 10 exp x -- exponantial abs x -- absolute value floor x -- floor ceil x -- ceiling pow x y -- power
Give a code snippet in #MAXScript Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Ol
Ol
  (define base64-codes "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") (define kernel (alist->ff (map cons (string->bytes base64-codes) (iota (string-length base64-codes)))))   ; returns n bits from input binary stream (define (bits n hold) (let loop ((hold hold)) (vector-apply hold (lambda...
Give a code snippet in #Ol See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with ...
christopher/rosetta-code
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Julia
Julia
function compressLZW(decompressed::String) dictsize = 256 dict = Dict{String,Int}(string(Char(i)) => i for i in 0:dictsize) result = Vector{Int}(undef, 0) w = "" for c in decompressed wc = string(w, c) if haskey(dict, wc) w = wc else push!...
Give a code snippet in #Julia The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Scala
Scala
val collection = Array(1, 2, 3, 4) collection.foreach(println)
Give a code snippet in #Scala 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...
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. ...
#LiveCode
LiveCode
put 0 into n repeat for 5 times add 1 to n repeat for n times put "*" end repeat put return end repeat
Give a code snippet in #LiveCode “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/Jaro-Winkler_distance
Jaro-Winkler distance
The Jaro-Winkler distance is a metric for measuring the edit distance between words. It is similar to the more basic Levenstein distance but the Jaro distance also accounts for transpositions between letters in the words. With the Winkler modification to the Jaro metric, the Jaro-Winkler distance also adds an increase ...
#Swift
Swift
import Foundation   func loadDictionary(_ path: String) throws -> [String] { let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii) return contents.components(separatedBy: "\n") }   func jaroWinklerDistance(string1: String, string2: String) -> Double { var st1 = Array(string1) ...
Give a code snippet in #Swift The Jaro-Winkler distance is a metric for measuring the edit distance between words. It is similar to the more basic Levenstein distance but the Jaro distance also accounts for transpositions between letters in the words. With the Winkler modification to the Jaro metric, the Jaro-Winkler ...
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
#Wortel
Wortel
@sum !*^@sq [3 1 4 1 5 9] ; returns 133
Give a code snippet in #Wortel 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/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
#QB64
QB64
  _TITLE "GUI Sliding Blocks Game " RANDOMIZE TIMER   ' get from user the desired board size = s DO LOCATE CSRLIN, 3: INPUT "(0 quits) Enter your number of blocks per side 3 - 9 you want > ", s IF s = 0 THEN END LOOP UNTIL s > 2 AND s < 10   ' screen setup: based on the square blocks q pixels a sides q = 540 / ...
Give a code snippet in #QB64 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/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 |...
#REBOL
REBOL
rebol [ Title: "Retrieve Substring" URL: http://rosettacode.org/wiki/Substring#REBOL ]   s: "abcdefgh" n: 2 m: 3 char: #"d" chars: "cd"   ; Note that REBOL uses base-1 indexing. Strings are series values, ; just like blocks or lists so I can use the same words to manipulate ; them. All these examples use the 'cop...
Give a code snippet in #REBOL Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Ring
Ring
  aString = "1Welcome to the Ring Programming Language2" see substr(aString,2,len(aString)-1) + nl + substr(aString,1,len(aString)-1) + nl + substr(aString,2,len(aString)-2) + nl  
Give a code snippet in #Ring The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Stata
Stata
. mat a=1,2,3\4,5,6 . mat b=a' . mat list a   a[2,3] c1 c2 c3 r1 1 2 3 r2 4 5 6   . mat list b   b[3,2] r1 r2 c1 1 4 c2 2 5 c3 3 6
Give a code snippet in #Stata Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task ...
#Raku
Raku
sub comma { $^i.flip.comb(3).join(',').flip }   use Math::Primesieve;   my $sieve = Math::Primesieve.new;   my @primes = $sieve.primes(10_000_000);   my %filter = @primes.Set;   my $primes = @primes.classify: { %filter{($_ - 1)/2} ?? 'safe' !! 'unsafe' };   for 'safe', 35, 'unsafe', 40 -> $type, $quantity { say "Th...
Give a code snippet in #Raku Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't...
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...
#EchoLisp
EchoLisp
  (lib 'math) (define (semi-prime? n) (= (length (prime-factors n)) 2))   (for ((i 100)) (when (semi-prime? i) (write i)))   4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95   (lib 'bigint) (define N (* (random-prime 10000000) (random-prime 10000000))) → 676...
Give a code snippet in #EchoLisp 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#C.23
C#
using System;   static class YCombinator<T, TResult> { // RecursiveFunc is not needed to call Fix() and so can be private. private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);   public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } = f => ((Recursiv...
Give a code snippet in #C.23 In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a var...
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...
#JavaScript
JavaScript
^[a-zA-Z_][a-zA-Z_0-9]*$
Give a code snippet in #JavaScript 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, enabli...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#PHP
PHP
<?php   function is_prime($n) { if ($n <= 3) { return $n > 1; } elseif (($n % 2 == 0) or ($n % 3 == 0)) { return false; } $i = 5; while ($i * $i <= $n) { if ($n % $i == 0) { return false; } $i += 2; if ($n % $i == 0) { return fa...
Give a code snippet in #PHP An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   em...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#Haskell
Haskell
module Pernicious where   isPernicious :: Integer -> Bool isPernicious num = isPrime $ toInteger $ length $ filter ( == 1 ) $ toBinary num   isPrime :: Integer -> Bool isPrime number = divisors number == [1, number] where divisors :: Integer -> [Integer] divisors number = [ m | m <- [1 .. number] , nu...
Give a code snippet in #Haskell A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is pri...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#C.2B.2B
C++
  #include <windows.h> #include <iostream> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int BMP_SIZE = 512, CELL_S...
Give a code snippet in #C.2B.2B This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#GAP
GAP
Hanoi := function(n) local move; move := function(n, a, b, c) # from, through, to if n = 1 then Print(a, " -> ", c, "\n"); else move(n - 1, a, c, b); move(1, a, b, c); move(n - 1, b, a, c); fi; end; move(n, "A", "B", "C"); end;   Hanoi(1); # A -> C   Hanoi(2); # A -> B # A -> C # B -> C   Hanoi(3)...
Give a code snippet in #GAP Task Solve the   Towers of Hanoi   problem with recursion.
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 ...
#Common_Lisp
Common Lisp
(defgeneric kar (kons) (:documentation "Return the kar of a kons."))   (defgeneric kdr (kons) (:documentation "Return the kdr of a kons."))   (defun konsp (object &aux (args (list object))) "True if there are applicable methods for kar and kdr on object." (not (or (endp (compute-applicable-methods #'kar args)) ...
Give a code snippet in #Common_Lisp 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 op...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DIM a(5) 20 LET a(2)=128 30 PRINT a(2)
Give a code snippet in #ZX_Spectrum_Basic This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to i...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.2B.2B
C++
#include <iostream>   void bitwise(int a, int b) { std::cout << "a and b: " << (a & b) << '\n'; // Note: parentheses are needed because & has lower precedence than << std::cout << "a or b: " << (a | b) << '\n'; std::cout << "a xor b: " << (a ^ b) << '\n'; std::cout << "not a: " << ~a << '\n';   //...
Give a code snippet in #C.2B.2B 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/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...
#AWK
AWK
BEGIN { print "\nWelcome to the number reversal game!\n"   print "You must put the numbers in order from 1 to 9." print "Your only moves are to reverse groups of numbers" print "on the left side of the list."   newgame() prompt() }   # start a new game function newgame( i, j, t) { # score = number of moves sco...
Give a code snippet in #AWK 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 scor...
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Go
Go
type cell string   type spec struct { less func(cell, cell) bool column int reverse bool }   func newSpec() (s spec) { // initialize any defaults return }   // sort with all defaults t.sort(newSpec())   // reverse sort s := newSpec s.reverse = true t.sort(s)
Give a code snippet in #Go Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexico...
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:
#Asymptote
Asymptote
path subtriangle(path p, real node) { return point(p, node) -- point(p, node + 1/2) -- point(p, node - 1/2) -- cycle; }   void sierpinski(path p, int order) { if (order == 0) fill(p); else { sierpinski(subtriangle(p, 0), order - 1); sierpinski(subtrian...
Give a code snippet in #Asymptote 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/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...
#Modula-3
Modula-3
MODULE Literals EXPORTS Main;   IMPORT IO;   BEGIN IO.PutInt(16_2D7); IO.Put(" "); IO.PutInt(10_727); IO.Put(" "); IO.PutInt(8_1327); IO.Put(" "); IO.PutInt(2_1011010111); IO.Put("\n"); END Literals.
Give a code snippet in #Modula-3 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...
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 ...
#Racket
Racket
  #lang racket   (define (bubble-sort <? v) (define len (vector-length v)) (define ref vector-ref) (let loop ([max len] [again? #f]) (for ([i (in-range 0 (- max 1))] [j (in-range 1 max)]) (define vi (ref v i)) (when (<? (ref v j) vi) (vector-set! v i (ref v j)) ...
Give a code snippet in #Racket Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#D
D
void main() @safe { import std.stdio, std.traits;   enum width = 75, height = 52; enum maxSteps = 12_000; enum Direction { up, right, down, left } enum Color : char { white = '.', black = '#' } uint x = width / 2, y = height / 2; Color[width][height] M; auto dir = Direction.up;   wit...
Give a code snippet in #D Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the fol...
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.
#Astro
Astro
for line in lines open('input.txt'): print line  
Give a code snippet in #Astro 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/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#IS-BASIC
IS-BASIC
100 PROGRAM "e.bas" 110 LET E1=0:LET E,N,N1=1 120 DO WHILE E<>E1 130 LET E1=E:LET E=E+1/N 140 LET N1=N1+1:LET N=N*N1 150 LOOP 160 PRINT "The value of e =";E
Give a code snippet in #IS-BASIC Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#GW-BASIC
GW-BASIC
10 ' Modular inverse 20 LET E% = 42 30 LET T% = 2017 40 GOSUB 1000 50 PRINT MODINV% 60 END 990 ' increments e stp (step) times until bal is greater than t 992 ' repeats until bal = 1 (mod = 1) and returns count 994 ' bal will not be greater than t + e 1000 LET D% = 0 1010 IF E% >= T% THEN GOTO 1140 1020 LET BAL%...
Give a code snippet in #GW-BASIC From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m ...
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) ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Sub Main() Dim siCount As Short Dim sText As String   For siCount = 1 To 100 sText = "" If siCount Mod 3 = 0 Then sText = "Fizz" If siCount Mod 5 = 0 Then sText = "Buzz" If siCount Mod 15 = 0 Then sText = "FizzBuzz" If sText Then Print sText Else Print siCount Next   End
Give a code snippet in #F.C5.8Drmul.C3.A6 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,   prin...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an 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 |...
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. FACTORS. DATA DIVISION. WORKING-STORAGE SECTION. 01 CALCULATING. 03 NUM USAGE BINARY-LONG VALUE ZERO. 03 LIM USAGE BINARY-LONG VALUE ZERO. 03 CNT USAGE BINARY-LONG VALUE ZERO. 03 DIV USAGE BINA...
Give a code snippet in #COBOL Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Symsyn
Symsyn
    | Pop Count 3^i   i if i < 30 (3^i) x popcount x 63 x ~ x $r + $r $s + ' ' $s + i goif endif "' Pop Count 3^i : ' $s " []   | Evil Numbers   i cnt if cnt < 30 popcount i 7 x x:0:1 y if y <> 1 + cnt ~ i $r + $r $e + ' ' $e endif + i ...
Give a code snippet in #Symsyn 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 coun...
christopher/rosetta-code
http://rosettacode.org/wiki/Hunt_the_Wumpus
Hunt the Wumpus
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#AutoHotkey
AutoHotkey
  // constant value 2d array to represent the dodecahedron // room structure const static int adjacentRooms[20][3] = { {1, 4, 7}, {0, 2, 9}, {1, 3, 11}, {2, 4, 13}, {0, 3, 5}, {4, 6, 14}, {5, 7, 16}, {0, 6, 8}, {7, 9, 17}, {1, 8, 10}, {9, 11, 18}, {2, 10, 12}, {11, 13, 19}, {3, 12, 14}, {5, 13,...
Give a code snippet in #AutoHotkey This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#ALGOL_68
ALGOL 68
BEGIN MODE ELEMENT = STRING;   # Iterative: # PROC iterative binary search = ([]ELEMENT hay stack, ELEMENT needle)INT: ( INT out, low := LWB hay stack, high := UPB hay stack; WHILE low < high DO INT mid := (low+high) OVER 2; IF hay stack[mid] > needle THEN high := mid-1 E...
Give a code snippet in #ALGOL_68 A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secre...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#MATLAB_.2F_Octave
MATLAB / Octave
  function r = base_count(f) fid = fopen(f,'r'); nn=[0,0,0,0]; while ~feof(fid) s = fgetl(fid); fprintf(1,'%5d :%s\n', sum(nn), s(s=='A'|s=='C'|s=='G'|s=='T')); nn = nn+[sum(s=='A'),sum(s=='C'),sum(s=='G'),sum(s=='T')]; end fclose(fid);   fprintf(1, '\nBases:\n\n A  : %d\n C  : %d\n G...
Give a code snippet in #MATLAB_.2F_Octave Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATG...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
Find if a point is within a triangle
Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the algorithm you chose works. Re...
#Java
Java
import java.util.Objects;   public class FindTriangle { private static final double EPS = 0.001; private static final double EPS_SQUARE = EPS * EPS;   public static class Point { private final double x, y;   public Point(double x, double y) { this.x = x; this.y = y; ...
Give a code snippet in #Java Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the a...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Nim
Nim
import os echo getAppFilename() # Prints the full path of the executed file echo paramStr(0) # Prints argv[0]
Give a code snippet in #Nim The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script na...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related ...
#Objeck
Objeck
#~ Rotating Cube ~#   use Collection.Generic; use Game.SDL2; use Game.Framework;   class RotatingCube { # game framework @framework : GameFramework; @initialized : Bool;   @nodes : Float[,]; @edges : Int[,];   New() { @initialized := true; @framework := GameFramework->New(GameConsts->SCREEN_WIDTH, G...
Give a code snippet in #Objeck Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Persp...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Fortran
Fortran
SUBROUTINE SPLATTER(TEXT) !Print a comma-separated list. Repeated characters constitute one item. Can't display the inserted commas in a different colour so as not to look like any commas in TEXT. CHARACTER*(*) TEXT !The text. INTEGER L !A finger. CHARACTER*1 C !A state follower. IF (...
Give a code snippet in #Fortran Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#C
C
#include <stdio.h> #include <stdlib.h>   typedef struct { double v; int c; } vcount;   int cmp_dbl(const void *a, const void *b) { double x = *(const double*)a - *(const double*)b; return x < 0 ? -1 : x > 0; }   int vc_cmp(const void *a, const void *b) { return ((const vcount*)b)->c - ((const vcount*)a)->c; }   int ...
Give a code snippet in #C Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possib...
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...
#Go
Go
package main   import ( "fmt" "math/cmplx" )   func main() { a := 1 + 1i b := 3.14159 + 1.25i fmt.Println("a: ", a) fmt.Println("b: ", b) fmt.Println("a + b: ", a+b) fmt.Println("a * b: ", a*b) fmt.Println("-a: ", -a) fmt.Println("1 / a: ", 1/a) fmt.Println("...
Give a code snippet in #Go 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...
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...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make local test: LINKED_LIST [INTEGER] count, number, te: INTEGER do create test.make test := hailstone_sequence (27) io.put_string ("There are " + test.count.out + " elements in the sequence for the number 27.") io.put_string ("%NThe first 4 elemen...
Give a code snippet in #Eiffel 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/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 ...
#Jsish
Jsish
/* Levenshtein Distance, in Jsish */   function levenshtein(a, b) { var t = [], u, i, j, m = a.length, n = b.length; if (!m) { return n; } if (!n) { return m; } for (j = 0; j <= n; j++) { t[j] = j; } for (i = 1; i <= m; i++) { for (u = [i], j = 1; j <= n; j++) { u[j] = a[i - 1] === b[j - 1] ? t[j - ...
Give a code snippet in #Jsish 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 com...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Wren
Wren
import "/date" for Date   var centuries = ["20th", "21st", "22nd"] var starts = [1900, 2000, 2100] for (i in 0...centuries.count) { var longYears = [] System.print("\nLong years in the %(centuries[i]) century:") for (j in starts[i]...starts[i]+100) { var t = Date.new(j, 12, 28) if (t.weekOfY...
Give a code snippet in #Wren Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 ...
#BBC_BASIC
BBC BASIC
DIM test%(9) test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 PROCradixsort(test%(), 10, 10) FOR i% = 0 TO 9 PRINT test%(i%) ; NEXT PRINT END   DEF PROCradixsort(a%(), n%, r%) LOCAL d%, e%, i%, l%, m%, b%(), bucket%() DIM b%(n%-1), bucket%(r%-1) FOR...
Give a code snippet in #BBC_BASIC Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#D
D
import std.stdio, std.algorithm, std.range, std.typecons;   auto hailstone(uint n) pure nothrow { auto result = [n]; while (n != 1) { n = (n & 1) ? (n * 3 + 1) : (n / 2); result ~= n; } return result; }   void main() { enum M = 27; immutable h = M.hailstone; writeln("hailstone(", M, ")= ", h[0 .. ...
Give a code snippet in #D 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 T...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Java
Java
public class TwelveDaysOfChristmas {   final static String[] gifts = { "A partridge in a pear tree.", "Two turtle doves and", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies ...
Give a code snippet in #Java Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#F.23
F#
  // Carmichael Number . Nigel Galloway: November 19th., 2017 let fN n = Seq.collect ((fun g->(Seq.map(fun e->(n,1+(n-1)*(n+g)/e,g,e))){1..(n+g-1)})){2..(n-1)} let fG (P1,P2,h3,d) = let mod' n g = (n%g+g)%g let fN P3 = if isPrime P3 && (P2*P3)%(P1-1)=1 then Some (P1,P2,P3) else None if isPrime P2 && ((h3+P1)*(P1-...
Give a code snippet in #F.23 A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to invest...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#AWK
AWK
  BEGIN { print("Hello World!") >"/dev/lp0" }  
Give a code snippet in #AWK Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some s...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Raku
Raku
for 1 .. 5 -> $degree { sub mfact($n) { [*] $n, *-$degree ...^ * <= 0 }; say "$degree: ", map &mfact, 1..10 }
Give a code snippet in #Raku The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
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 ...
#Wren
Wren
import "/pattern" for Pattern import "/str" for Str import "/fmt" for Fmt import "/sort" for Cmp, Sort   var p2 = Pattern.new("+2 ") var p3 = Pattern.new("/s") // any whitespace character var p5 = Pattern.new("+1/d")   /** Only covers ISO-8859-1 accented characters plus (for consistency) Ÿ */ var ucAccented = ["ÀÁÂÃÄÅ"...
Give a code snippet in #Wren Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Oforth
Oforth
: testInteger(n, m) assert: [ n isInteger ] assert: [ n 42 == ]   System.Out "Assertions are ok, parameters are : " << n << ", " << m << cr ;
Give a code snippet in #Oforth Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor
Terminal control/Hiding the cursor
The task is to hide the cursor and show it again.
#Quackery
Quackery
[ $ &print("\x1b[?25l",end='')& python ] is hide ( --> )   [ $ &print("\x1b[?25h",end='')& python ] is show ( --> )
Give a code snippet in #Quackery The task is to hide the cursor and show it again.
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.
#VBScript
VBScript
  Dim matrix1(2,2) matrix1(0,0) = 3 : matrix1(0,1) = 7 : matrix1(0,2) = 4 matrix1(1,0) = 5 : matrix1(1,1) = -2 : matrix1(1,2) = 9 matrix1(2,0) = 8 : matrix1(2,1) = -6 : matrix1(2,2) = -5 Dim matrix2(2,2) matrix2(0,0) = 9 : matrix2(0,1) = 2 : matrix2(0,2) = 1 matrix2(1,0) = -7 : matrix2(1,1) = 3 : matrix2(1,2) = -10 mat...
Give a code snippet in #VBScript 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/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import javax.swing.Timer   -- .+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8 class RClockSwing public extends JFrame -- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . properties c...
Give a code snippet in #NetRexx Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change eve...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Python
Python
import bpy   # select default cube bpy.data.objects['Cube'].select_set(True)   # delete default cube bpy.ops.object.delete(True)   # add text to Blender scene bpy.data.curves.new(type="FONT", name="Font Curve").body = "Hello World" font_obj = bpy.data.objects.new(name="Font Object", object_data=bpy.data.curves["Font ...
Give a code snippet in #Python Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#Raku
Raku
say lcs("thisisatest", "testing123testing");sub lcs(Str $xstr, Str $ystr) { return "" unless $xstr && $ystr;   my ($x, $xs, $y, $ys) = $xstr.substr(0, 1), $xstr.substr(1), $ystr.substr(0, 1), $ystr.substr(1); return $x eq $y ?? $x ~ lcs($xs, $ys) !! max(:by{ $^a.chars }, lcs($xstr, $ys), lcs...
Give a code snippet in #Raku Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be string...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Oz
Oz
functor import Application QTk at 'x-oz://system/wp/QTk.ozf' define proc {OnClose} {Application.exit 0} end   %% Descripe the GUI in a declarative style. GUIDescription = td(label(text:"Hello World!") action:OnClose %% Exit app when window closes. )   %% Create a window objec...
Give a code snippet in #Oz Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#J
J
5^3^2 1.95312e6 (5^3)^2 15625 5^(3^2) 1.95312e6
Give a code snippet in #J This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the ...
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/...
#Cowgol
Cowgol
include "cowgol.coh";   sub digitsum(n: uint16): (sum: uint8) is sum := 0; while n != 0 loop sum := sum + (n % 10) as uint8; n := n / 10; end loop; end sub;   sub nextHarshad(m: uint16): (n: uint16) is n := m; loop n := n + 1; if n % digitsum(n) as uint16 == 0 the...
Give a code snippet in #Cowgol 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...
christopher/rosetta-code