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/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#Kotlin
Kotlin
// version 1.2.21   import java.util.Random import kotlin.math.*   data class Point(var x: Double, var y: Double, var group: Int)   typealias LPoint = List<Point> typealias MLPoint = MutableList<Point>   val origin get() = Point(0.0, 0.0, 0) val r = Random() val hugeVal = Double.POSITIVE_INFINITY   const val RAND_MAX =...
Give a code snippet in #Kotlin K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the data...
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...
#COBOL
COBOL
>>SOURCE FREE PROGRAM-ID. twelve-days-of-christmas.   DATA DIVISION. WORKING-STORAGE SECTION. 01 gifts-area VALUE "partridge in a pear tree " & "Two turtle doves " & "Three french hens " & "Four calling birds " & "FIVE GOLDEN RINGS " & "Six ...
Give a code snippet in #COBOL 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 operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item...
#Tcl
Tcl
package require struct::set   proc consolidate {sets} { if {[llength $sets] < 2} { return $sets }   set r [list {}] set r0 [lindex $sets 0] foreach x [consolidate [lrange $sets 1 end]] { if {[struct::set size [struct::set intersect $x $r0]]} { struct::set add r0 $x } else { lappend r $x...
Give a code snippet in #Tcl Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input set...
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
C
#include <stdio.h>   char a1[] = {'a','b','c'}; char a2[] = {'A','B','C'}; int a3[] = {1,2,3};   int main(void) { for (int i = 0; i < 3; i++) { printf("%c%c%i\n", a1[i], a2[i], a3[i]); } }
Give a code snippet in #C 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,...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Perl
Perl
print $ENV{HOME}, "\n";
Give a code snippet in #Perl Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#11l
11l
F k(n) V n2 = String(Int64(n) ^ 2) L(i) 0 .< n2.len V a = I i > 0 {Int(n2[0 .< i])} E 0 V b = Int(n2[i ..]) I b != 0 & a + b == n R 1B R 0B   print((1..9999).filter(x -> k(x))) print((1..999999).filter(x -> k(x)).len)
Give a code snippet in #11l A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#AutoIt
AutoIt
#include <AD.au3> _AD_Open()
Give a code snippet in #AutoIt The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Befunge
Befunge
0>51p0>52p51g52g*:51g52g`!*\!51g52g+*+0\3>01p::55+%68*+\!28v w^p2<y|!`+66:+1,+*84*"\"!:g25$_,#!>#:<$$_^#!:-1g10/+55\-**<< "$9"^x>$55+,51g1+:66+`#@_055+68*\>\#<1#*-#9:#5_$"+---">:#,_$
Give a code snippet in #Befunge Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#CoffeeScript
CoffeeScript
  loop print a = Math.random() * 20 // 1 break if a == 10 print Math.random() * 20 // 1  
Give a code snippet in #CoffeeScript 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 ...
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 ...
#V
V
[multiply *].
Give a code snippet in #V 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#PHP
PHP
$i; function sum (&$i, $lo, $hi, $term) { $temp = 0; for ($i = $lo; $i <= $hi; $i++) { $temp += $term(); } return $temp; }   echo sum($i, 1, 100, create_function('', 'global $i; return 1 / $i;')), "\n"; //Output: 5.18737751764 (5.1873775176396)   function sum ($lo,$hi) { $temp = 0; for ($i = $...
Give a code snippet in #PHP Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL...
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#J
J
i. 5 5 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Give a code snippet in #J For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the p...
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. ...
#Kotlin
Kotlin
// version 1.1.2   import java.io.File   fun walkDirectory(dirPath: String, pattern: Regex): List<String> { val d = File(dirPath) require(d.exists() && d.isDirectory()) return d.list().filter { it.matches(pattern) } }   fun main(args: Array<String>) { val r = Regex("""^a.*\.h$""") // get all C header f...
Give a code snippet in #Kotlin 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,...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Go
Go
package main   import "fmt"   type ( seq []int sofs []seq )   func newSeq(start, end int) seq { if end < start { end = start } s := make(seq, end-start+1) for i := 0; i < len(s); i++ { s[i] = start + i } return s }   func newSofs() sofs { return sofs{seq{}} }   func ...
Give a code snippet in #Go A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the u...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h> #define MAX_LINE_SIZE 1000 main: v=0, fd=0 fsearch("-r $'\n'","archivo.txt")(v) fopen(OPEN_READ,"archivo.txt")(fd) {"Line #7 = "}, fgetsline(fd,MAX_LINE_SIZE,7,v), println try fgetsline(fd,MAX_LINE_SIZE,10,v), catch(e) {"Error search line (code=",e,"): "},get str err...
Give a code snippet in #Amazing_Hopper Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and s...
christopher/rosetta-code
http://rosettacode.org/wiki/Topological_sort
Topological 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 ...
#Kotlin
Kotlin
// version 1.1.51   val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " + "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"   val deps = mutableListOf( 2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1, 3 to 1, 3 to 10, 3 to 11, 4 to 1, 4 to 10, 5 to 0, 5 to ...
Give a code snippet in #Kotlin 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/Kronecker_product_based_fractals
Kronecker product based fractals
This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the matrix   (filled with 0/1)   we ...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-} import Reflex import Reflex.Dom import Data.Map as DM (Map, fromList) import Data.Text (Text, pack) import Data.List (transpose)   -- Show Vicsek and Sierpinski Carpet fractals main :: IO () main = mainWidget $ do elAttr "h1" ("style" =: "color:black") $ text "Kroneker Product Base...
Give a code snippet in #Haskell This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the...
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 ...
#Dyalect
Dyalect
func countJewels(stones, jewels) { stones.Iterate().Map(x => jewels.Contains(x) ? 1 : 0).Reduce((x,y) => x + y, 0) }   print(countJewels("aAAbbbb", "aA")) print(countJewels("ZZ", "z"))
Give a code snippet in #Dyalect 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 ca...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#MiniZinc
MiniZinc
  %Spiral Matrix. Nigel Galloway, February 3rd., 2020 int: Size; array [1..Size,1..Size] of var 1..Size*Size: spiral; constraint spiral[1,1..]=1..Size; constraint forall(n in 2..(Size+1) div 2)(forall(g in n..Size+1-n)(spiral[n,g]=spiral[n,g-1]+1)); constraint forall(n in 1..(Size+1) div 2)(forall(g in n+1..Size+1-n)(s...
Give a code snippet in #MiniZinc Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#PHP
PHP
<?php //Josephus.php function Jotapata($n=41,$k=3,$m=1){$m--; $prisoners=array_fill(0,$n,false);//make a circle of n prisoners, store false ie: dead=false $deadpool=1;//count to next execution $order=0;//death order and *dead* flag, ie. deadpool while((array_sum(array_count_values($prisoners))<$n)){//while sum of c...
Give a code snippet in #PHP Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp...
#Nim
Nim
const Size = 15   type Canvas = array[Size, array[Size, char]]     func horizontal(canvas: var Canvas; col1, col2, row: Natural) = for col in col1..col2: canvas[row][col] = 'x'     func vertical(canvas: var Canvas; row1, row2, col: Natural) = for row in row1..row2: canvas[row][col] = 'x'     func diagd(canv...
Give a code snippet in #Nim Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself repres...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#JavaScript
JavaScript
  const e = '3 4 2 * 1 5 - 2 3 ^ ^ / +'; const s = [], tokens = e.split(' '); for (const t of tokens) { const n = Number(t); if (!isNaN(n)) { s.push(n); } else { if (s.length < 2) { throw new Error(`${t}: ${s}: insufficient operands.`); } const o2 = s.pop(), o1 = s.pop(); switch (t) { ...
Give a code snippet in #JavaScript Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with t...
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
#PHP
PHP
go ?=> member(N,1..5), println(N), fail, % or false/0 to get other solutions nl. go => true.
Give a code snippet in #PHP 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/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...
#Rust
Rust
extern crate rand;   use std::fmt; use rand::Rng; use Pip::*; use Suit::*;   #[derive(Copy, Clone, Debug)] enum Pip { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }   #[derive(Copy, Clone, Debug)] enum Suit { Spades, Hearts, Diamonds, Clubs }   struct Card { pip: Pip, suit: Suit }   im...
Give a code snippet in #Rust 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 co...
christopher/rosetta-code
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Cod...
#Python
Python
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import hashlib >>> h = hashlib.new('ripemd160') >>> h.update(b"Rosetta Code") >>> h.hexdigest() 'b3be159860842cebaa7174c8fff0aa9e50a5199f' >>>
Give a code snippet in #Python RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the A...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Oz
Oz
declare Xs = {MakeList 5} %% a list of 5 unbound variables in {ForAll Xs OS.rand} %% fill it with random numbers (CORRECT) {Show Xs}
Give a code snippet in #Oz Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Apex
Apex
EncodingUtil.urlEncode('http://foo bar/', 'UTF-8')
Give a code snippet in #Apex Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes i...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( ( 0.00 0.06 0.10 ) ( 0.06 0.11 0.18 ) ( 0.11 0.16 0.26 ) ( 0.16 0.21 0.32 ) ( 0.21 0.26 0.38 ) ( 0.26 0.31 0.44 ) ( 0.31 0.36 0.50 ) ( 0.36 0.41 0.54 ) ( 0.41 0.46 0.58 ) ( 0.46 0.51 0.62 ) ( 0.51 0.56 0.66 ) ( 0.56 0.61 0.70 ) ( 0.61 0.66 0.74 ) ( 0.66 0.71 0.78 ) ( 0.71 0.76 0.82 ) ( 0.76 ...
Give a code snippet in #Phixmonti A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   ...
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 ...
#VBScript
VBScript
  'instantiate the dictionary object Set dict = CreateObject("Scripting.Dictionary")   'populate the dictionary or hash table dict.Add 1,"larry" dict.Add 2,"curly" dict.Add 3,"moe"   'iterate key and value pairs For Each key In dict.Keys WScript.StdOut.WriteLine key & " - " & dict.Item(key) Next  
Give a code snippet in #VBScript 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/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#Common_Lisp
Common Lisp
(let ((Δ 1)) (incf Δ))
Give a code snippet in #Common_Lisp Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Relate...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Multiple
Inheritance/Multiple
Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePhone,   then write a class Camer...
#Oforth
Oforth
Property new: Camera Property new: MobilePhone   Object Class new: CameraPhone CameraPhone is: Camera CameraPhone is: MobilePhone
Give a code snippet in #Oforth Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobileP...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#C
C
typedef struct Point { int x; int y; } Point;
Give a code snippet in #C 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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Relat...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#ALGOL_68
ALGOL 68
BEGIN # returns the longest common substring of s and t # PROC longest common substring = ( STRING s, t )STRING: BEGIN STRING s1 = s[ @ 1 ]; # normalise bounds to 1 : ... # STRING s2 = t[ @ 1 ]; STRING result := ""; INT result len := 0; ...
Give a code snippet in #ALGOL_68 Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are conse...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#Icon_and_Unicon
Icon and Unicon
# # 4bitadder.icn, emulate a 4 bit adder. Using only and, or, not # record carry(c)   # # excercise the adder, either "test" or 2 numbers # procedure main(argv) c := carry(0)   # cli test if map(\argv[1]) == "test" then { # Unicon allows explicit radix literals every i := (2r0000 | 2r1001 |...
Give a code snippet in #Icon_and_Unicon Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate ca...
christopher/rosetta-code
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
Selectively replace multiple instances of a character within a string
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fifth 'a' with 'D' the first 'b...
#FreeBASIC
FreeBASIC
Function replaceChar(Byref S As String) As String Dim As String A = "ABaCD", B = "Eb", R = "rF" Dim As Byte pA = 1, pB = 1, pR = 1 For i As Byte = 0 To Len(S) Select Case Mid(S,i,1) Case "a" Mid(S,i,1) = Mid(A,pA,1) pA += 1 Case "b" Mid(S,i,1) = Mi...
Give a code snippet in #FreeBASIC Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
Sorting algorithms/Strand 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 ...
#J
J
strandSort=: (#~ merge $:^:(0<#)@(#~ -.)) (= >./\)
Give a code snippet in #J Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Fantom
Fantom
  using fwt using gfx   class SimpleApplication { public static Void main () { Window { title = "Simple Window Application" size = Size(350, 50) clicked := 0 label := Label { text = "There have been no clicks yet" } Button { text = "Click me" ...
Give a code snippet in #Fantom Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Ring
Ring
  see "Enter a string : " give s see "Enter an integer : " give i see "String = " + s + nl see "Integer = " + i + nl  
Give a code snippet in #Ring User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#HicEst
HicEst
CHARACTER string = "123 -4567.89"   READ( Text=string) a, b WRITE(Text=string) a+1, b+1 ! 124 -4566.89
Give a code snippet in #HicEst Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#CoffeeScript
CoffeeScript
  # Let's say you want to arrange the first N-squared natural numbers # in a spiral, where you fill in the numbers clockwise, starting from # the upper left corner. This code computes the values for each x/y # coordinate of the square. (Of course, you could precompute the values # iteratively, but what fun is that?) ...
Give a code snippet in #CoffeeScript Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Python
Python
from sympy import isprime   def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10))   for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n')   print()
Give a code snippet in #Python Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Modula-3
Modula-3
MODULE FileTest EXPORTS Main;   IMPORT IO, Fmt, FS, File, OSError, Pathname;   PROCEDURE FileExists(file: Pathname.T): BOOLEAN = VAR status: File.Status; BEGIN TRY status := FS.Status(file); RETURN TRUE; EXCEPT | OSError.E => RETURN FALSE; END; END FileExists;   BEGIN IO.Put(Fmt.Bool...
Give a code snippet in #Modula-3 Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works ...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Groovy
Groovy
import groovy.swing.SwingBuilder   count = 0 new SwingBuilder().edt { frame(title:'Click frame', pack: true, show: true) { vbox { countLabel = label("There have been no clicks yet.") button('Click Me', actionPerformed: {count++; countLabel.text = "Clicked ${count} time(s)."}) } } }
Give a code snippet in #Groovy Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#M2000_Interpreter
M2000 Interpreter
  print str$(now,"long time"), time$(now)  
Give a code snippet in #M2000_Interpreter Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Relat...
christopher/rosetta-code
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#C
C
#include <stdio.h> #include <math.h>   #define C 7 typedef struct { double x, y; } pt;   pt zero(void) { return (pt){ INFINITY, INFINITY }; }   // should be INFINITY, but numeric precision is very much in the way int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }   pt neg(pt p) { return (pt){ p.x, -p.y }; }   pt d...
Give a code snippet in #C Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutsh...
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) ...
#Z80_Assembly
Z80 Assembly
foreach n in ([1..100]) { if(n % 3 == 0) print("Fizz"); if(not (n%5)) "Buzz".print(); if(n%3 and n%5) print(n); println(); }
Give a code snippet in #Z80_Assembly 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   F...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Phix
Phix
constant data = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", "are$delineated$by$a$single$'dollar'$character,$write$a$program", "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", "column$are$separated$by$at$least$one$space.", "Further,$allow$for$each$word$in$a$c...
Give a code snippet in #Phix Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left...
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#K4
K4
fd:1_-':
Give a code snippet in #K4 Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B ...
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 |...
#R
R
factors <- function(n) { if(length(n) > 1) { lapply(as.list(n), factors) } else { one.to.n <- seq_len(n) one.to.n[(n %% one.to.n) == 0] } }
Give a code snippet in #R Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#RapidQ
RapidQ
create form as qform center width=500 height=400 end create form.showModal
Give a code snippet in #RapidQ 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/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Forth
Forth
: main ( n -- ) 0 swap 3 do i 3 mod 0= if i + else i 5 mod 0= if i + then then loop . ;   1000 main \ 233168 ok
Give a code snippet in #Forth Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
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...
#Perl
Perl
my @heading = qw(X Y Z); my $rows = 5; print '<table><thead><td>', (map { "<th>$_</th>" } @heading), "</thead><tbody>";   for (1 .. $rows) { print "<tr><th>$_</th>", (map { "<td>".int(rand(10000))."</td>" } @heading), "</tr>"; }   print "</tbody></table>";
Give a code snippet in #Perl 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...
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...
#Alore
Alore
def gcd(a as Int, b as Int) as Int while b != 0 a,b = b, a mod b end return Abs(a) end
Give a code snippet in #Alore 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/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Ursa
Ursa
decl int input set input (in int console) if (= (mod input 2) 1) out "odd" endl console else out "even" endl console end if
Give a code snippet in #Ursa Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divid...
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...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int X, Y, Dir; [SetVid($13); \set 320x200 graphic video mode X:= 50; Y:= 50; Dir:= 0; \start in middle facing east repeat if ReadPix(X,Y) then \(black and white are reversed) [Dir:= Dir-1;\left\ Point(X,Y, 0\bl...
Give a code snippet in #XPL0 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Befunge
Befunge
"J2["39*,,,,@
Give a code snippet in #Befunge Task Clear the terminal window.
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...
#Delphi
Delphi
proc nonrec gcd(word m, n) word: word t; while n ~= 0 do t := m; m := n; n := t % n od; m corp   proc nonrec show(word m, n) void: writeln("gcd(", m, ", ", n, ") = ", gcd(m, n)) corp   proc nonrec main() void: show(18, 12); show(1071, 1029); show(3528, 3780) corp
Give a code snippet in #Delphi 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   greates...
christopher/rosetta-code
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Haskell
Haskell
{-# LANGUAGE LambdaCase #-} import Data.List (find, mapAccumL) import Control.Arrow (first, second)   -- Generalized Fibonacci series defined for any Num instance, and for Zeckendorf numbers as well. -- Used to build Zeckendorf tables. fibs :: Num a => a -> a -> [a] fibs a b = res where res = a : b : zipWith (+)...
Give a code snippet in #Haskell This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m
Minimum multiple of m where digital sum equals m
Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n. Task Find the first 40 elements of the sequence. Stretch Find the next 30 elements of the sequence. See also OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
#Draco
Draco
/* this is very slow even in emulation - if you're going to try it * on a real 8-bit micro I'd recommend setting this back to 40; * it does, however, eventually get there */ byte MAX = 70;   /* note on types: 2^32 is a 10-digit number, * so the digit sum of an ulong is guaranteed * to be <= 90 */ proc nonrec digits...
Give a code snippet in #Draco Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n. Task Find the first 40 elements of the sequence. Stretch Find the next 30 elements of the sequence. See also OEIS:A131382 - Minimal number m such th...
christopher/rosetta-code
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid...
#Rust
Rust
extern crate rand;   use std::io; use std::io::Write;   fn main() {   use minesweeper::{MineSweeper, GameStatus};   let mut width = 6; let mut height = 4; let mut mine_perctg = 10; let mut game = MineSweeper::new(width, height, mine_perctg);   loop { let mut command = String::new();   ...
Give a code snippet in #Rust There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordi...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Raku
Raku
my $buffer = Buf.new(0 xx 1024);
Give a code snippet in #Raku Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Ring
Ring
  recurse(0)   func recurse x see ""+ x + nl recurse(x+1)  
Give a code snippet in #Ring Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#C
C
#include <stdlib.h> #include <stdio.h>   int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
Give a code snippet in #C Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/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
#APL
APL
display dialog "Goodbye, World!" buttons {"Bye"}
Give a code snippet in #APL 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/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Quackery
Quackery
[ [] swap witheach [ upper dup char A char Z 1+ within iff join else drop ] ] is onlycaps ( $ --> $ )   [ onlycaps [] swap witheach [ char A - join ] ] is cipherdisk ( $ --> [ )   [ [] swap witheach [ 26 swap - join ] ] is decipheri...
Give a code snippet in #Quackery Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#PowerShell
PowerShell
function Get-DigitalRoot ($n) { function Get-Digitalsum ($n) { if ($n -lt 10) {$n} else { ($n % 10) + (Get-DigitalSum ([math]::Floor($n / 10))) } }   $ap = 0 do {$n = Get-DigitalSum $n; $ap++} until ($n -lt 10) $DigitalRoot = [pscustomobject]@{ 'Su...
Give a code snippet in #PowerShell The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Liberty_BASIC
Liberty BASIC
  guesses =0   do while len( secret$) <4 ' zero not allowed <<<<<<<<< n$ =chr$( int( rnd( 1) *9) +49) if not( instr( secret$, n$)) then secret$ =secret$ +n$ loop   print " Secretly, my opponent just chose a number. But she didn't tell anyone! "; secret$; "." print...
Give a code snippet in #Liberty_BASIC Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping on...
christopher/rosetta-code
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st...
#Phix
Phix
-- demo\rosetta\checkpoint_synchronisation.exw without js -- task_xxx(), get_key() constant NPARTS = 3 integer workers = 0 sequence waiters = {} bool terminate = false procedure checkpoint(integer task_id) if length(waiters)+1=NPARTS or terminate then printf(1,"checkpoint\n") for i=1 to length(wait...
Give a code snippet in #Phix The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#Factor
Factor
USING: accessors deques dlists fry kernel make math math.order ; IN: rosetta.hamming   TUPLE: hamming-iterator 2s 3s 5s ;   : <hamming-iterator> ( -- hamming-iterator ) hamming-iterator new 1 1dlist >>2s 1 1dlist >>3s 1 1dlist >>5s ;   : enqueue ( n hamming-iterator -- ) [ [ 2 * ] [ 2s>>...
Give a code snippet in #Factor Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming num...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. The original article was at P...
#Go
Go
  package main   import ( "fmt" "math/big" )   func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10...
Give a code snippet in #Go This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. T...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#GAP
GAP
while true do Print("SPAM\n"); od;
Give a code snippet in #GAP Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#NetRexx
NetRexx
  import java.text.SimpleDateFormat say SimpleDateFormat("yyyy-MM-dd").format(Date()) say SimpleDateFormat("EEEE, MMMM dd, yyyy").format(Date())  
Give a code snippet in #NetRexx 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/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#11l
11l
F add_with_carry(&result, =addend, =addendpos) L L result.len < addendpos + 1 result.append(‘0’) V addend_result = String(Int(addend) + Int(result[addendpos])) V addend_digits = Array(addend_result) result[addendpos] = addend_digits.pop()   I addend_digits.empty L.brea...
Give a code snippet in #11l Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   i...
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#PureBasic
PureBasic
Enumeration #LittleEndian #BigEndian EndEnumeration   ProcedureDLL EndianTest() Protected Endian = #LittleEndian Protected dummy.l= 'ABCD' If "A"=Chr(PeekA(@dummy)) Endian=#BigEndian EndIf ProcedureReturn Endian EndProcedure   ;- *** Start of test code If OpenConsole() PrintN("Your word size is...
Give a code snippet in #PureBasic Print the word size and endianness of the host machine. See also: Variable size/Get
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...
#6502_Assembly
6502 Assembly
PHA
Give a code snippet in #6502_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 sta...
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 ...
#PHP
PHP
<?php function dot_product($v1, $v2) { if (count($v1) != count($v2)) throw new Exception('Arrays have different lengths'); return array_sum(array_map('bcmul', $v1, $v2)); }   echo dot_product(array(1, 3, -5), array(4, -2, -1)), "\n"; ?>
Give a code snippet in #PHP Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#Racket
Racket
  (define (subsets l) (if (null? l) '(()) (append (for/list ([l2 (subsets (cdr l))]) (cons (car l) l2)) (subsets (cdr l)))))  
Give a code snippet in #Racket Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first a...
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...
#Swift
Swift
let fruits = ["apple", "orange"] // Declare constant array literal let fruitsCount = fruits.count // Declare constant array length (count)   print(fruitsCount) // Print array length to output window
Give a code snippet in #Swift 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 frequ...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#zkl
zkl
(123).len() //-->1 (byte) (0).MAX.len() //-->8 (bytes), ie the max number of bytes in an int (1.0).MAX.len() //-->8 (bytes), ie the max number of bytes in an float "this is a test".len() //-->14 L(1,2,3,4).len() //-->4 Dictionary("1",1, "2",2).len() //-->2 (keys) Data(0,Int,1,2,3,4).len() //-->4 (bytes) Data(0,Stri...
Give a code snippet in #zkl Demonstrate how to get the size of a variable. See also: Host introspection
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#C.23
C#
using System; using System.ComponentModel; using System.Windows.Forms;   class RosettaInteractionForm : Form {   // Model used for DataBinding. // Notifies bound controls about Value changes. class NumberModel: INotifyPropertyChanged { // initialize event with empty delegate to avoid chec...
Give a code snippet in #C.23 In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI compon...
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...
#VBScript
VBScript
Function binary_search(arr,value,lo,hi) If hi < lo Then binary_search = 0 Else middle=Int((hi+lo)/2) If value < arr(middle) Then binary_search = binary_search(arr,value,lo,middle-1) ElseIf value > arr(middle) Then binary_search = binary_search(arr,value,middle+1,hi) Else binary_search = m...
Give a code snippet in #VBScript 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/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
#Axe
Axe
Disp "Hello world!",i
Give a code snippet in #Axe 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/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...
#jq
jq
# Generate the hailstone sequence as a stream to save space (and time) when counting def hailstone: recurse( if . > 1 then if . % 2 == 0 then ./2|floor else 3*. + 1 end else empty end );   def count(g): reduce g as $i (0; .+1);   # return [i, length] for the first maximal-length ha...
Give a code snippet in #jq 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/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0,0)   Width% = 200 Height% = 200   VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lenagrey   DIM hist%(255), idx%(255) FOR i% = 0 TO 255 : idx%(i%) = i% : NEXT   REM Build histogram: FOR y% = 0 TO Height%-1 ...
Give a code snippet in #BBC_BASIC Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It mus...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Phix
Phix
with javascript_semantics constant input = """ Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his moth...
Give a code snippet in #Phix Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Cre...
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 |...
#newLISP
newLISP
> (set 'str "alphabet" 'n 2 'm 4) 4 > ; starting from n characters in and of m length > (slice str n m) "phab" > ; starting from n characters in, up to the end of the string > (slice str n) "phabet" > ; whole string minus last character > (chop str) "alphabe" > ; starting from a known character within the string and of...
Give a code snippet in #newLISP 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/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Elena
Elena
import extensions; import extensions'dynamic;   public program() { var json := "{ ""foo"": 1, ""bar"": [10, ""apples""] }";   var o := json.fromJson();   console.printLine("json.foo=",o.foo); console.printLine("json.bar=",o.bar) }
Give a code snippet in #Elena Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Scheme
Scheme
(define (day-of-week year month day) (if (< month 3) (begin (set! month (+ month 12)) (set! year (- year 1)))) (+ 1 (remainder (+ 5 day (quotient (* (+ 1 month) 13) 5) year (quotient year 4) (* (quotient year 100) 6) (quotient year 400)) 7)))   (define (task) (let loop ((y 2121) (v...
Give a code snippet in #Scheme A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#REXX
REXX
/* Rexx */ do call testcase say say RFC3986 call testcase RFC3986 say say HTML5 call testcase HTML5 say return end exit   /* -------------------------------------------------------------------------- */ encode: procedure do parse arg url, varn . parse upper var varn variation drop RFC3986 HTML5...
Give a code snippet in #REXX Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes i...
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#CoffeeScript
CoffeeScript
  # Calculate a zig-zag pattern of numbers like so: # 0 1 5 # 2 4 6 # 3 7 8 # # There are many interesting ways to solve this; we # try for an algebraic approach, calculating triangle # areas, so that me minimize space requirements.   zig_zag_value = (x, y, n) ->   upper_triangle_zig_zag = (x, y) -> # calcu...
Give a code snippet in #CoffeeScript Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#zkl
zkl
class Life{ fcn init(n, r1,c1, r2,c2, etc){ var N=n, cells=Data(n*n), tmp=Data(n*n), ds=T(T(-1,-1),T(-1,0),T(-1,1), T(0,-1),T(0,1), T(1,-1),T(1,0),T(1,1)); icells:=vm.arglist[1,*]; (N*N).pump(Void,cells.append.fpM("1-",0)); // clear board icells.pump(Void,Void.Read,fcn(row,col){ cells...
Give a code snippet in #zkl The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   i...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#JavaScript
JavaScript
var dog = "Benjamin"; var Dog = "Samba"; var DOG = "Bernie"; document.write("The three dogs are named " + dog + ", " + Dog + ", and " + DOG + ".");
Give a code snippet in #JavaScript Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjami...
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...
#Racket
Racket
  #lang racket (require net/url html xml xml/path)   (struct item (name mass value count) #:transparent)   ;this section is to convert the web page on the problem into the data for the problem ;i don't got time to manually type tables, nevermind that this took longer (define (group-n n l) (let group-n ([l l] [acc '()...
Give a code snippet in #Racket 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 we...
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.
#Maxima
Maxima
/* Read a file and return a list of all lines */   readfile(name) := block( [v: [ ], f: openr(name), line], while stringp(line: readline(f)) do v: endcons(line, v), close(f), v )$
Give a code snippet in #Maxima 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/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) ...
#Elena
Elena
import system'routines; import extensions; import extensions'text;   randomBrackets(len) { if (0 == len) { ^emptyString } else { var brackets := Array.allocate(len).populate:(i => $91) + Array.allocate(len).populate:(i => $93);   brack...
Give a code snippet in #Elena 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-n...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Oberon-2
Oberon-2
  MODULE Haversines; IMPORT LRealMath, Out;   PROCEDURE Distance(lat1,lon1,lat2,lon2: LONGREAL): LONGREAL; CONST r = 6372.8D0; (* Earth radius as LONGREAL *) to_radians = LRealMath.pi / 180.0D0; VAR d,ph1,th1,th2: LONGREAL; dz,dx,dy: LONGREAL; BEGIN d := lon1 - lon2; ph1 := d * to_r...
Give a code snippet in #Oberon-2 This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an e...
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...
#PicoLisp
PicoLisp
  1.2345e-4 decimal floating-point 7e5 decimal floating-point 1.234_567_89e0 decimal floating-point. 1.0s0 decimal floating-point (single precision) 1.0d0 decimal floating-point (double precision) 1.34q0 decimal floating-point (quadruple/extended precision)   111.0101e7b bin...
Give a code snippet in #PicoLisp 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 B...
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.
#Cowgol
Cowgol
include "cowgol.coh";   # Cowgol has strict typing and there are no templates either. # Defining the type this way makes it easy to change. typedef FilterT is uint32;   # In order to pass functions around, we need to define an # interface. The 'FilterPredicate' interface will take an argument # and return zero if it s...
Give a code snippet in #Cowgol 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/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Grid@Prepend[ Table[{n, #[[1]], #[[2]], Row[{Round[10000 Abs[#[[1]] - #[[2]]]/#[[2]]]/100., "%"}]} &@ N[{Mean[Array[ Length@NestWhileList[#, 1, UnsameQ[##] &, All] - 1 &[# /. MapIndexed[#2[[1]] -> #1 &, RandomInteger[{1, n}, n]] &] &, 10000]], Sum[n! n^(n - k - 1)/...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will cont...
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...
#J
J
dirs=: 0 1,1 0,0 _1,:_1 0 langton=:3 :0 loc=. <.-:$cells=. (_2{.y,y)$dir=. 0 while. *./(0<:loc), loc<$cells do. color=. (<loc) { cells cells=. (-.color) (<loc)} cells dir=. 4 | dir + _1 ^ color loc=. loc + dir { dirs end. ' #' {~ cells )
Give a code snippet in #J 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