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/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#C.2B.2B
C++
#include <algorithm> #include <array> #include <iterator> #include <limits> #include <tuple>   namespace detail_ {   // For constexpr digit<->number conversions. constexpr auto digits = std::array{'0','1','2','3','4','5','6','7','8','9'};   // Helper function to encode a run-length. template <typename OutputIterator> c...
Give a code snippet in #C.2B.2B Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#360_Assembly
360 Assembly
* Merge sort 19/06/2016 MAIN CSECT STM R14,R12,12(R13) save caller's registers LR R12,R15 set R12 as base register USING MAIN,R12 notify assembler LA R11,SAVEXA get the address of my savearea ST R13,4(R11...
Give a code snippet in #360_Assembly Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Q...
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 ...
#Lua
Lua
function multiply( a, b ) return a * b end
Give a code snippet in #Lua 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 fr...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#UNIX_Shell
UNIX Shell
printf "Goodbye, World!" # This works. There is no newline. printf %s "-hyphens and % signs" # Use %s with arbitrary strings.
Give a code snippet in #UNIX_Shell Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/...
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...
#XLISP
XLISP
(defun greatest-common-divisor (x y) (if (= y 0) x (greatest-common-divisor y (mod x y)) ) )
Give a code snippet in #XLISP 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/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...
#Haskell
Haskell
{-# LANGUAGE Strict,FlexibleInstances #-} module KMeans where   import Control.Applicative import Control.Monad.Random import Data.List (minimumBy, genericLength, transpose) import Data.Ord (comparing) import qualified Data.Map.Strict as M     type Vec = [Float] type Cluster = [Vec]   kMeansIteration :: [Vec] -> [Vec] ...
Give a code snippet in #Haskell 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 dat...
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#Fortran
Fortran
! output: ! d-> 00000, t-> 00001, h-> 0001, s-> 0010, ! c-> 00110, x-> 00111, m-> 0100, o-> 0101, ! n-> 011, u-> 10000, l-> 10001, a-> 1001, ! r-> 10100, g-> 101010, p-> 101011, ! e-> 1011, i-> 1100, f-> 1101, -> 111 ! ! 00001|0001|1100|0010|111|1100|0010|111|1001|011| ! 111|1011|00111|1001|0100|101011|10001|1011|...
Give a code snippet in #Fortran Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you...
christopher/rosetta-code
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Go
Go
package main   import ( "fmt" )   type params struct {x, y, z int}   func myFunc(p params) int { return p.x + p.y + p.z }   func main() { r := myFunc(params{x: 1, y: 2, z: 3}) // all fields, same order fmt.Println("r =", r) s := myFunc(params{z: 3, y: 2, x: 1}) // all fields, different order fmt....
Give a code snippet in #Go Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on bein...
christopher/rosetta-code
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#Go
Go
package main   import "fmt"   type person struct{ name string age int }   func copy(p person) person { return person{p.name, p.age} }   func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) /* is := []int{1, 2, 3} it := make([]int, 3) copy(it, is) ...
Give a code snippet in #Go Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means...
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. ...
#AutoHotkey
AutoHotkey
Gui, Add, Edit, vOutput r5 w100 -VScroll ; Create an Edit-Control Gui, Show ; Show the window Loop, 5 ; loop 5 times { Loop, %A_Index% ; A_Index contains the Index of the current loop { output .= "*" ; append an "*" to the output var GuiControl, , Output, %Output% ; update the Edit-Control with the new cont...
Give a code snippet in #AutoHotkey “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 st...
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
#PARI.2FGP
PARI/GP
s=input(); n=eval(input());
Give a code snippet in #PARI.2FGP 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/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...
#Rust
Rust
  fn is_prime(n: i64) -> bool { if n > 1 { (2..((n / 2) + 1)).all(|x| n % x != 0) } else { false } }   // The modulo operator actually calculates the remainder. fn modulo(n: i64, m: i64) -> i64 { ((n % m) + m) % m }   fn carmichael(p1: i64) -> Vec<(i64, i64, i64)> { let mut results =...
Give a code snippet in #Rust 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/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#F.23
F#
  let x = 2.0 let xi = 0.5 let y = 4.0 let yi = 0.25 let z = x + y let zi = 1.0 / ( x + y ) let multiplier (n1,n2) = fun (m:float) -> n1 * n2 * m   [x; y; z] |> List.zip [xi; yi; zi] |> List.map multiplier |> List.map ((|>) 0.5) |> printfn "%A"  
Give a code snippet in #F.23 In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to creat...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 PRINT CHR$(8);:REM cursor one position left 20 PRINT CHR$(9);:REM cursor one position right 30 GO SUB 500: REM get cursor position 40 IF cr>0 THEN LET cr=cr-1: GO SUB 550: REM cursor up one line 50 IF cr<22 THEN LET cr=cr+1: GO SUB 550: REM cursor down one line 60 POKE 23688,33: REM cursor to beginning of the line 7...
Give a code snippet in #ZX_Spectrum_Basic Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down on...
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).
#Java_2
Java
import com.google.gson.Gson;   public class JsonExample {   public static void main(String[] args) { Gson gson = new Gson(); String json = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }";   MyJsonObject obj = gson.fromJson(json, MyJsonObject.class);   System.out.println(obj.getFoo());   for(String bar : obj...
Give a code snippet in #Java_2 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/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...
#JudoScript
JudoScript
//Store length of hello world in length and print it . length = "Hello World".length();
Give a code snippet in #JudoScript 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...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Go
Go
package main   import ( "fmt" "io/ioutil" )   func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
Give a code snippet in #Go File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Scala
Scala
def catalan(n: Int): Int = if (n <= 1) 1 else (0 until n).map(i => catalan(i) * catalan(n - i - 1)).sum   (1 to 15).map(catalan(_))
Give a code snippet in #Scala Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that gene...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#ARM_Assembly
ARM Assembly
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@ ARM SUBLEQ for Linux @@@ @@@ Word size is 32 bits. The program is @@@ @@@ given 8 MB (2 Mwords) to run in. @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .text .global _start @@@ Linux syscalls .equ exit, 1 .equ read, 3 .equ write, 4 .equ open, 5 ...
Give a code snippet in #ARM_Assembly Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an arra...
christopher/rosetta-code
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#Icon_and_Unicon
Icon and Unicon
procedure main() every n := 1 to 10 do { ts := 0 every (ts := 0) <:= swop(permute([: 1 to n :])) write(right(n, 3),": ",right(ts,4)) } end   procedure swop(A) count := 0 while A[1] ~= 1 do { A := reverse(A[1+:A[1]]) ||| A[(A[1]+1):0] count +:= 1 } ...
Give a code snippet in #Icon_and_Unicon Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A r...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#Bracmat
Bracmat
(isPangram= k . low$!arg:?arg & a:?k & whl ' ( @(!arg:? !k ?) & chr$(1+asc$!k):?k:~>z ) & !k:>z & );
Give a code snippet in #Bracmat Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task W...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical 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 |...
#Nemerle
Nemerle
using System; using System.Console;   module Logical { WriteLogical(a : bool, b : bool) : void { WriteLine("{0} and {1} is {2}", a, b, a && b); WriteLine("{0} or {1} is {2}", a, b, a || b); WriteLine("not {0} is {1}", a, !a); }   Main() : void {WriteLogical(true, false)} }
Give a code snippet in #Nemerle 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/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Java
Java
import java.util.ArrayList;   public class FirstClass{   public interface Function<A,B>{ B apply(A x); }   public static <A,B,C> Function<A, C> compose( final Function<B, C> f, final Function<A, B> g) { return new Function<A, C>() { @Override public C apply(A x) { return f.apply(g.apply(x)); } }; ...
Give a code snippet in #Java A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#BBC_BASIC
BBC BASIC
VDU 23,22,512;512;8,16,16,0 VDU 5   GCOL 4,15 REPEAT B% = ADVAL(0) X% = ADVAL(1) / 64 Y% = 1023 - ADVAL(2) / 64 PROCjoy(B%,X%,Y%) WAIT 4 PROCjoy(B%,X%,Y%) UNTIL FALSE END   DEF PROCjoy(B%,X%,Y%) LOCAL I% LINE X%-32,Y%,...
Give a code snippet in #BBC_BASIC The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the ex...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#PARI.2FGP
PARI/GP
isPerfect(n)=sigma(n,-1)==2
Give a code snippet in #PARI.2FGP Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including it...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Run_BASIC
Run BASIC
print isNumeric("123") print isNumeric("1ab")   ' ------------------------ ' Numeric Check ' 0 = bad ' 1 = good ' ------------------------ FUNCTION isNumeric(f$) isNumeric = 1 f$ = trim$(f$) if left$(f$,1) = "-" or left$(f$,1) = "+" then f$ = mid$(f$,2) for i = 1 to len(f$) d$ = mid$(f$,i,1) if d$ = "," then ...
Give a code snippet in #Run_BASIC Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metric...
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...
#Objeck
Objeck
class Program { function : Main(args : String[]) ~ Nil { dog := "Benjamin"; Dog := "Samba"; DOG := "Bernie"; "The three dogs are named {$dog}, {$Dog}, and {$DOG}."->PrintLine(); } }
Give a code snippet in #Objeck 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, S...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#Phix
Phix
with javascript_semantics enum NEXT,DATA constant empty_sll = {{1}} sequence sll = deep_copy(empty_sll) procedure insert_after(object data, integer pos=length(sll)) sll = append(sll,{sll[pos][NEXT],data}) sll[pos][NEXT] = length(sll) end procedure insert_after("ONE") insert_after("TWO") insert_after("THREE"...
Give a code snippet in #Phix Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Oz
Oz
%% Returns a list of lines. %% Text: an instance of Open.text (a mixin class) fun {ReadAll Text} case {Text getS($)} of false then nil [] Line then Line|{ReadAll Text} end end
Give a code snippet in #Oz Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
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 ...
#Ring
Ring
# Project : Population count   odds = [] evens = [] pows = []   for n = 0 to 59 if n < 30 add(pows, onesCount(pow(3, n))) ok num = onesCount(n) if num & 1 = 0 add(evens, n) else add(odds, n) ok next   showOne("3^x:", pows) showOne("Evil numbers:", evens) showOne("Odious numbers:", odds)   func onesCou...
Give a code snippet in #Ring Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count ...
christopher/rosetta-code
http://rosettacode.org/wiki/Leonardo_numbers
Leonardo numbers
Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L(n) = L(n-1) + L(n-2) + 1 ...
#JavaScript
JavaScript
const leoNum = (c, l0 = 1, l1 = 1, add = 1) => new Array(c).fill(add).reduce( (p, c, i) => i > 1 ? ( p.push(p[i - 1] + p[i - 2] + c) && p ) : p, [l0, l1] );   console.log(leoNum(25)); console.log(leoNum(25, 0, 1, 0));
Give a code snippet in #JavaScript Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#FreeBASIC
FreeBASIC
#define twopi 6.2831853071795864769252867665590057684 dim shared as double S = 0 'set up the state as a global variable dim shared as double t0, t1, ta   function sine( x as double, f as double ) as double return sin(twopi*f*x) end function   function zero( x as double, f as double ) as double return 0 end ...
Give a code snippet in #FreeBASIC In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of su...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Onyx
Onyx
# Most of this long script is mere presentation. # All you really need to do is push two integers onto the stack # and then execute add, sub, mul, idiv, or pow.   $ClearScreen { # Using ANSI terminal control `\e[2J\e[1;1H' print flush } bind def   $Say { # string Say - `\n' cat print flush } bind def   $ShowPreambl...
Give a code snippet in #Onyx Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#Coq
Coq
  Require Import Coq.Strings.String.   Eval compute in ("Hello world!"%string).  
Give a code snippet in #Coq 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/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Scala
Scala
object Roots extends App { val poly = (x: Double) => x * x * x - 3 * x * x + 2 * x   private def printRoots(f: Double => Double, lowerBound: Double, upperBound: Double, step: Double): Unit = { val y = f(lowerBound) var (ox, oy, os) =...
Give a code snippet in #Scala Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort; with Ada.Containers.Indefinite_Vectors; procedure Danagrams is package StringVector is new Ada.Containers.Indefinite_Vectors (Positive, String); procedure StrSort is new Ada.Containers.Generic_Array_Sort (Index_Type => Positive...
Give a code snippet in #Ada Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[e...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Rust
Rust
fn egcd(a: i64, b: i64) -> (i64, i64, i64) { if a == 0 { (b, 0, 1) } else { let (g, x, y) = egcd(b % a, a); (g, y - (b / a) * x, x) } }   fn mod_inv(x: i64, n: i64) -> Option<i64> { let (g, x, _) = egcd(x, n); if g == 1 { Some((x % n + n) % n) } else { Non...
Give a code snippet in #Rust Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displayst...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#11l
11l
V playercount = 2 V maxscore = 100 V safescore = [0] * playercount V player = 0 V score = 0   L max(safescore) < maxscore V rolling = input(‘Player #.: (#., #.) Rolling? (Y) ’.format( player, safescore[player], score)).trim(‘ ’).lowercase() C Set([‘yes’, ‘y’, ‘’]) I rolling V rolled = ...
Give a code snippet in #11l The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to the...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Java
Java
import java.util.ArrayList; ...//class definition, etc. public static void genPyrN(int rows){ if(rows < 0) return; //save the last row here ArrayList<Integer> last = new ArrayList<Integer>(); last.add(1); System.out.println(last); for(int i= 1;i <= rows;++i){ //work on the next row ArrayList<Integer> thisRow=...
Give a code snippet in #Java Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either ...
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...
#Elixir
Elixir
defmodule Hailstone do require Integer   def step(1) , do: 0 def step(n) when Integer.is_even(n), do: div(n,2) def step(n) , do: n*3 + 1   def sequence(n) do Stream.iterate(n, &step/1) |> Stream.take_while(&(&1 > 0)) |> Enum.to_list end   def run do se...
Give a code snippet in #Elixir 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/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Maxima
Maxima
/* No need to declare anything, undeclared arrays are hashed */   h[1]: 6; h[9]: 2;   arrayinfo(h); [hashed, 1, [1], [9]]
Give a code snippet in #Maxima Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition,...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to rais...
#OCaml
OCaml
exception U0 exception U1   let baz i = raise (if i = 0 then U0 else U1)   let bar i = baz i (* Nest those calls *)   let foo () = for i = 0 to 1 do try bar i with U0 -> print_endline "Function foo caught exception U0" done   let () = foo ()
Give a code snippet in #OCaml Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arran...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#XPL0
XPL0
code Reserve=3, ChOut=8, IntOut=11;   proc MergeSort(A, Low, High); \Sort array A from Low to High int A, Low, High; int B, Mid, H, I, J, K; [if Low >= High then return; Mid:= (Low+High) >> 1; \split array in half (roughly) MergeSort(A, Low, Mid); \sort left half MergeSort(A, Mid+1, High); \so...
Give a code snippet in #XPL0 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/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#C
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h>     #define MAXLEN 100 typedef char TWord[MAXLEN];     typedef struct Node { TWord word; struct Node *next; } Node;     int is_ordered_word(const TWord word) { assert(word != NULL); int i;   for (i = 0; word[i] != '\0'; i...
Give a code snippet in #C An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally as...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#Wren
Wren
var divByAll = Fn.new { |n, digits| digits.all { |d| n%(d-48) == 0 } }   var magic = 9 * 8 * 7 var high = (9876432/magic).floor * magic var i = high while (i >= magic) { if (i%10 != 0) { // can't end in '0' var s = "%(i)" if (!s.contains("0") && !s.contains("5")) { // can't contain '0' or '5' ...
Give a code snippet in #Wren Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   ...
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.
#Groovy
Groovy
def recurse; recurse = { try { recurse (it + 1) } catch (StackOverflowError e) { return it } }   recurse(0)
Give a code snippet in #Groovy 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/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Lasso
Lasso
define br => '\r' //decode roman define decodeRoman(roman::string)::integer => { local(ref = array('M'=1000, 'CM'=900, 'D'=500, 'CD'=400, 'C'=100, 'XC'=90, 'L'=50, 'XL'=40, 'X'=10, 'IX'=9, 'V'=5, 'IV'=4, 'I'=1)) local(out = integer) while(#roman->size) => { // need to use neset while instead of query expr to utili...
Give a code snippet in #Lasso Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, st...
christopher/rosetta-code
http://rosettacode.org/wiki/Hough_transform
Hough transform
Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\displaystyle (\rho ,\theta )} , ...
#Phix
Phix
-- demo\rosetta\Hough_transform.exw without js -- IupImage, imImage, im_width/height/pixel, allocate, -- imFileImageLoadBitmap, IupImageFromImImage include pGUI.e function hypot(atom a,b) return sqrt(a*a+b*b) end function function hough_transform(imImage im, integer width=460, height=360) height = 2*...
Give a code snippet in #Phix Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#ARM_Assembly
ARM Assembly
.text .global main   @ An ARM program that keeps incrementing R0 forever @ @ If desired, a call to some 'PRINT' routine -- @ which would depend on the OS -- could be included   main: mov r0, #0 @ start with R0 = 0   repeat: @ call to 'PRINT' routine add r0, r0, #1 @ increme...
Give a code snippet in #ARM_Assembly Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementat...
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...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { print "<table>\n <thead align = \"right\">" printf " <tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>\n </thead>\n <tbody align = \"right\">\n" for (i=1; i<=10; i++) { printf " <tr><td>%2i</td><td>%5i</td><td>%5i</td><td>%5i</td></tr>\n",i, 10*i, 100*i, 1000*i-1 } ...
Give a code snippet in #AWK 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/Bitmap/Read_an_image_through_a_pipe
Bitmap/Read an image through a pipe
This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PP...
#Julia
Julia
using Images, FileIO   img = load("data/bitmapOutputTest.jpg") save("data/bitmapOutputTest.ppm", img)
Give a code snippet in #Julia This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ...
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) ...
#VAX_Assembly
VAX Assembly
00000008 0000 1 len =8 00000008 0000 2 msg: .blkb len ;output buffer 0000000C 0008 3 desc: .blkl 1 ;descriptor lenght field 00000000' 000C 4 .address msg ;pointer to buffer ...
Give a code snippet in #VAX_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/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Elena
Elena
import extensions; import system'routines;   horner(coefficients,variable) { ^ coefficients.clone().sequenceReverse().accumulate(new Real(),(accumulator,coefficient => accumulator * variable + coefficient)) }   public program() { console.printLine(horner(new real[]{-19.0r, 7.0r, -4.0r, 6.0r}, 3.0r)) }
Give a code snippet in #Elena A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\...
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...
#R
R
  x = (0:10) > x^2 [1] 0 1 4 9 16 25 36 49 64 81 100 > Reduce(function(y,z){return (y+z)},x) [1] 55 > x[x[(0:length(x))] %% 2==0] [1] 0 2 4 6 8 10  
Give a code snippet in #R 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 us...
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
#Ursala
Ursala
#import std   #cast %nL   examples = <weight 'hello',mpfr..prec 1.0E+0>
Give a code snippet in #Ursala Demonstrate how to get the size of a variable. See also: Host introspection
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Oforth
Oforth
"dup 34 emit print 34 emit BL emit print" dup 34 emit print 34 emit BL emit print
Give a code snippet in #Oforth A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Quackery
Quackery
[ dup 0 < iff $ "negative argument passed to fibonacci" fail [ dup 2 < if done dup 1 - recurse swap 2 - recurse + ] ] is fibonacci ( n --> n )
Give a code snippet in #Quackery While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unw...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#CLU
CLU
% Count the divisors of [1..N] count_divisors = proc (n: int) returns (sequence[int]) divs: array[int] := array[int]$fill(1, n, 1) for i: int in int$from_to(2, n) do for j: int in int$from_to_by(i, n, i) do divs[j] := divs[j] + 1 end end return(sequence[int]$a2s(divs)) end co...
Give a code snippet in #CLU A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
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
#Lambdatalk
Lambdatalk
  Hello world! {h1 Hello world!} _h1 Hello world!\n  
Give a code snippet in #Lambdatalk 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 er...
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: ...
#PowerShell
PowerShell
  function zip3 ($a1, $a2, $a3) { while ($a1) { $x, $a1 = $a1 $y, $a2 = $a2 $z, $a3 = $a3 [Tuple]::Create($x, $y, $z) } }  
Give a code snippet in #PowerShell 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#FALSE
FALSE
1_ [^$1_=~][]#% [$1_=~][,]#
Give a code snippet in #FALSE Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
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 ...
#R
R
words <- readLines("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") word_group <- sapply( strsplit(words, split=""), # this will split all words to single letters... function(x) paste(sort(x), collapse="") # ...which we sort and paste again )   counts <- tapply(words, word_group, length) # group words by ...
Give a code snippet in #R 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....
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#Python
Python
from proper_divisors import proper_divs from functools import lru_cache     @lru_cache() def pdsum(n): return sum(proper_divs(n))     def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pds...
Give a code snippet in #Python An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classification...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Visual_Basic
Visual Basic
Sub fibonacci() Const n = 139 Dim i As Integer Dim f1 As Variant, f2 As Variant, f3 As Variant 'for Decimal f1 = CDec(0): f2 = CDec(1) 'for Decimal setting Debug.Print "fibo("; 0; ")="; f1 Debug.Print "fibo("; 1; ")="; f2 For i = 2 To n f3 = f1 + f2 Debug.Print "fibo("; i; "...
Give a code snippet in #Visual_Basic The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive soluti...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#C.23
C#
  using System; using System.Collections.Generic; using System.Drawing;   namespace FloodFill { class Program { private static bool ColorMatch(Color a, Color b) { return (a.ToArgb() & 0xffffff) == (b.ToArgb() & 0xffffff); }   static void FloodFill(Bitmap bmp, Point pt...
Give a code snippet in #C.23 Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Scala
Scala
object ListMethods extends App {   private val obj = new { def examplePublicInstanceMethod(c: Char, d: Double) = 42   private def examplePrivateInstanceMethod(s: String) = true } private val clazz = obj.getClass   println("All public methods (including inherited):") clazz.getMethods.foreach(m => print...
Give a code snippet in #Scala Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
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,...
#ALGOL_W
ALGOL W
begin  % declare an array % integer array a ( 1 :: 10 );  % set the values % for i := 1 until 10 do a( i ) := i;  % change the 3rd element % a( 3 ) := 27;  % display the 4th element % write( a( 4 ) ); % would show 4 %  % arrays with sizes not known at compile-time must be created in inner...
Give a code snippet in #ALGOL_W 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 ret...
christopher/rosetta-code
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#Go
Go
package main   import ( "encoding/hex" "fmt" "io" "net" "os" "strconv" "strings" "text/tabwriter" )   // parseIPPort parses an IP with an optional port, returning an IP and a port (or nil // if no port was present in the given address). func parseIPPort(address string) (net.IP, *uint64, error) { ip := net.Pars...
Give a code snippet in #Go The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [:...
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Gema
Gema
$ gema -p '\B=Hello\n@end' Hello
Give a code snippet in #Gema Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Net;   class Program { static List<string> GetTitlesFromCategory(string category) { string searchQueryFormat = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle...
Give a code snippet in #C.23 Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out ab...
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"
#Factor
Factor
USING: io sequences command-line ; (command-line) [ print ] each
Give a code snippet in #Factor 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/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Sparkling
Sparkling
spn:1> reduce({ 1, 2, 3, 4, 5 }, 0, function(x, y) { return x + y; }) = 15 spn:2> reduce({ 1, 2, 3, 4, 5 }, 1, function(x, y) { return x * y; }) = 120
Give a code snippet in #Sparkling Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Euphoria
Euphoria
puts(2,"Goodbye, world!\n") -- 2 means output to 'standard error'
Give a code snippet in #Euphoria Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard o...
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...
#MATLAB
MATLAB
function [randSuccess,idealSuccess]=prisoners(numP,numG,numT) %numP is the number of prisoners %numG is the number of guesses %numT is the number of trials randSuccess=0;   %Random for trial=1:numT drawers=randperm(numP); won=1; for i=1:numP correct=0; ...
Give a code snippet in #MATLAB 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell
Terminal control/Ringing the terminal bell
Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usua...
#D
D
void main() { import std.stdio; writeln('\a'); }
Give a code snippet in #D Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h>   #define R 6371 #define TO_RAD (3.1415926536 / 180) double dist(double th1, double ph1, double th2, double ph2) { double dx, dy, dz; ph1 -= ph2; ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD;   dz = sin(th1) - sin(th2); dx = cos(ph1) * cos(th1) - cos(th2); d...
Give a code snippet in #C 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. leap-year.   DATA DIVISION. WORKING-STORAGE SECTION. 01 examples VALUE "19001994199619972000". 03 year PIC 9(4) OCCURS 5 TIMES INDEXED BY year-index.   01 remainders. 03 400-rem PIC 9(4). ...
Give a code snippet in #COBOL Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols
Idiomatically determine all the characters that can be used for symbols
Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ...
#F.23
F#
  let ``+`` = 5 printfn "%d" ``+``  
Give a code snippet in #F.23 Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer p...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Factor
Factor
USE: prettyprint get-callstack callstack.
Give a code snippet in #Factor Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the p...
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 ...
#Rust
Rust
fn fix_price(num: f64) -> f64 { match num { 0.96...1.00 => 1.00, 0.91...0.96 => 0.98, 0.86...0.91 => 0.94, 0.81...0.86 => 0.90, 0.76...0.81 => 0.86, 0.71...0.76 => 0.82, 0.66...0.71 => 0.78, 0.61...0.66 => 0.74, 0.56...0.61 => 0.70, 0.5...
Give a code snippet in #Rust 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  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#J
J
require'format/printf'   (opcodes)=: opcodes=: ;:{{)n fetch store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt }}-.LF   (ndDisp)=: ndDisp=:;:{{)n Sequence Multiply Divide Mod Add Subtract Negate Less LessEqual Greater GreaterEqual Equal NotEqual Not And Or Prts Assign Prti x ...
Give a code snippet in #J A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code...
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Nim
Nim
type Foo = ref object x, y: float   var f: Foo new f
Give a code snippet in #Nim 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 Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#VBA
VBA
  Option Explicit   Sub Main_Phrase_Reversals() Const PHRASE As String = "rosetta code phrase reversal" Debug.Print "Original String  : " & PHRASE Debug.Print "Reverse String  : " & Reverse_String(PHRASE) Debug.Print "Reverse each individual word : " & Reverse_each_individual_word(P...
Give a code snippet in #VBA Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#F.23
F#
  open System.Windows.Forms open System.Drawing open System   let sz = 300 let polygon = [Point(sz/2, int (float sz*(1.0-sin(Math.PI/3.0)))); Point(0, sz-1); Point(sz-1, sz-1)]   let bmp = new Bitmap(sz, sz) let paint (p: Point) = bmp.SetPixel(p.X, p.Y, Color.Black)   let random = Random() let seed = Point(int (random....
Give a code snippet in #F.23 The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#PL.2FI
PL/I
Proc DivideDZ(a,b) Returns(Float Bin(33)); Dcl (a,b,c) Float Bin(33); On ZeroDivide GoTo MyError; c=a/b; Return(c); MyError: Put Skip List('Divide by Zero Detected!'); End DivideDZ;   xx=DivideDZ(1,0);
Give a code snippet in #PL.2FI Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#zkl
zkl
var [const] gnames=T("fullname","office","extension","homephone","email"), pnames=T("account","password","uid","gid","gecos","directory","shell");   class Gecos{ var fullname, office, extension, homephone, email; fcn init(str){ gnames.zipWith(setVar,vm.arglist) } fcn toString { gnames.apply(setVar).conc...
Give a code snippet in #zkl Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most use...
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) ...
#Fortran
Fortran
program fizzbuzz_if integer :: i   do i = 1, 100 if (mod(i,15) == 0) then; print *, 'FizzBuzz' else if (mod(i,3) == 0) then; print *, 'Fizz' else if (mod(i,5) == 0) then; print *, 'Buzz' else; print *, i end if end do end program fizzbuzz_if
Give a code snippet in #Fortran 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   FizzBu...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Logtalk
Logtalk
leap_year(Year) :- ( mod(Year, 4) =:= 0, mod(Year, 100) =\= 0 -> true ; mod(Year, 400) =:= 0 ).
Give a code snippet in #Logtalk Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#MATLAB
MATLAB
  %screen = Bitmap object %startPoint = [x0,y0] %endPoint = [x1,y1] %color = [red,green,blue]   function bresenhamLine(screen,startPoint,endPoint,color)   if( any(color > 255) ) error 'RGB colors must be between 0 and 255'; end   %Check for vertical line, x0 == x1 if( startPoint(1) == endPoint...
Give a code snippet in #MATLAB Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#AutoHotkey
AutoHotkey
/* ; https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection#Algebraic_form l = line vector lo = point on the line n = plane normal vector Po = point on the plane   if (l . n) = 0 ; line and plane are parallel. if (Po - lo) . n = 0 ; line is contained in the plane.   (P - Po) . n = 0 ; vector equatio...
Give a code snippet in #AutoHotkey Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vecto...
christopher/rosetta-code
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write ...
#BASIC256
BASIC256
arraybase 1 dim array = {{3,4}, {5,11}, {12,8}, {9,5}, {5,6}}   print "The area of the polygon = "; Shoelace(array) end   function Shoelace(p) sum = 0 for i = 1 to p[?][] -1 sum += p[i][1] * p[i +1][2] sum -= p[i +1][1] * p[i][2] next i sum += p[i][1] * p[1][2] sum -= p[1][1] * p[i][...
Give a code snippet in #BASIC256 Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Ruby
Ruby
def f(x) x.abs ** 0.5 + 5 * x ** 3 end   puts "Please enter 11 numbers:" nums = 11.times.map{ gets.to_f }   nums.reverse_each do |n| print "f(#{n}) = " res = f(n) puts res > 400 ? "Overflow!" : res end
Give a code snippet in #Ruby The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Permanent[m_List] := With[{v = Array[x, Length[m]]}, Coefficient[Times @@ (m.v), Times @@ v] ]
Give a code snippet in #Mathematica.2FWolfram_Language 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_{...
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#EchoLisp
EchoLisp
  (define (string-reverse string) (list->string (reverse (string->list string))))   (define (task str) (for-each writeln (list (string-reverse str) (string-join (map string-reverse (string-split str ))) (string-join (reverse (string-split str ))))))     (task "rosetta code phrase reversal") ...
Give a code snippet in #EchoLisp Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of ...
christopher/rosetta-code
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the...
#Ruby
Ruby
require 'set'   # 26 prime numbers Primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] States = [ "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", ...
Give a code snippet in #Ruby Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rea...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Liberty_BASIC
Liberty BASIC
  'N queens '>10 would not work due to way permutations used 'anyway, 10 doesn't fit in memory Input "Input N for N queens puzzle (4..9) ";N if N<4 or N>9 then print "N out of range - quitting": end   ABC$= " " dash$ = "" for i = 0 to N-1 ABC$=ABC$+" "+chr$(asc("a")+i) dash$ = dash$+"--" next   dim q(N) t0=time...
Give a code snippet in #Liberty_BASIC Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Kn...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Groovy
Groovy
class Example { def foo(value) { "Invoked with '$value'" } }   def example = new Example() def method = "foo" def arg = "test value"   assert "Invoked with 'test value'" == example."$method"(arg)
Give a code snippet in #Groovy Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Smalltalk
Smalltalk
  Date today isLeapYear.  
Give a code snippet in #Smalltalk Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#SQL
SQL
;WITH DATA AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum, NUMBER, LEN(CAST(ABS(NUMBER) AS NVARCHAR(MAX))) LcharNum FROM TABLE1) SELECT CASE WHEN ( LCHARNUM >= 3 AND LCHARNUM % 2 = 1 ) THEN SUBSTRING(CHARNUM, LCHARNUM / 2, 3) ...
Give a code snippet in #SQL Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be test...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#FreeBASIC
FreeBASIC
' version 04-11-2016 ' compile with: fbc -s console   #Macro deg2rad (x) (x) * Atn(1) / 45 #EndMacro   #Macro rad2deg (x) (x) * 45 / Atn(1) #EndMacro   ' ------=< MAIN >=------   Dim As Double latitude, longitude, meridian, hra, hla Dim As ULong h   Input " Enter latitude (degrees): ", latitude Input " ...
Give a code snippet in #FreeBASIC Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Is...
christopher/rosetta-code