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/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Julia
Julia
using Dates, TimeZones, HTTP, Printf   function geturlbyday(n) d = DateTime(now(tz"Europe/Berlin")) + Day(n) # n should be <= 0 uri = @sprintf("http://tclers.tk/conferences/tcl/%04d-%02d-%02d.tcl", year(d), month(d), day(d)) return uri, String(HTTP.request("GET", uri).body) end   function searchlog...
Give a code snippet in #Julia Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#OCaml
OCaml
let mycmp s1 s2 = if String.length s1 <> String.length s2 then compare (String.length s2) (String.length s1) else String.compare (String.lowercase s1) (String.lowercase s2)
Give a code snippet in #OCaml 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Kotlin
Kotlin
import java.util.Arrays   fun main(args: Array<String>) { val strings = arrayOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")   fun printArray(message: String, array: Array<String>) = with(array) { print("$message [") forEachIndexed { index, string -> print(if (in...
Give a code snippet in #Kotlin Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Nim
Nim
import tables, os   var t = initCountTable[char]() for l in paramStr(1).lines: for c in l: t.inc(c) echo t
Give a code snippet in #Nim Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assig...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#PureBasic
PureBasic
;An array, map, or list can be used as a parameter to a procedure and in the ;process contain values to be returned as well. Procedure example_1(x, y, Array r(1)) ;array r() will contain the return values Dim r(2) ;clear and resize the array r(0) = x + y ;return these values in the array r(1) = x - y r(2) = x...
Give a code snippet in #PureBasic Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Scala
Scala
object PointCircle extends App {   class Point(x: Int = 0, y: Int = 0) {   def copy(x: Int = this.x, y: Int = this.y): Point = new Point(x, y)   override def toString = s"Point x: $x, y: $y" }   object Point { def apply(x: Int = 0, y: Int = 0): Point = new Point(x, y) }   case class Circle(x: Int...
Give a code snippet in #Scala Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Aime
Aime
integer n, pc, sp; file f; text s; index code, Data; list l, stack, strings;   f.affix(argv(1));   f.list(l, 0);   n = atoi(l[-1]); while (n) { f.lead(s); strings.append(erase(s, -1, 0)); n -= 1; }   while (f.list(l, 0) ^ -1) { code.put(atoi(lf_x_text(l)), l); }   pc = sp = 0; while (1) { l = code[p...
Give a code snippet in #Aime A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read inpu...
christopher/rosetta-code
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#BBC_BASIC
BBC BASIC
MOUSE xmouse%, ymouse%, buttons% PRINT xmouse%, ymouse%
Give a code snippet in #BBC_BASIC Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#CLU
CLU
weekday = proc (d: date) returns (int) y: int := d.year m: int := d.month if m<3 then y, m := y-1, m+10 else m := m-2 end c: int := y/100 y := y//100 z: int := (26*m-2)/10 + d.day + y + y/4 + c/4 - 2*c + 777 return(z//7) end weekday   start_up = proc () po: stream :=...
Give a code snippet in #CLU A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 20...
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 ...
#Perl
Perl
use utf8; binmode STDOUT, ":utf8";   # to reverse characters (code points): print reverse('visor'), "\n";   # to reverse graphemes: print join("", reverse "José" =~ /\X/g), "\n";   $string = 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧‍ 👨‍👩‍👧‍👦🆗🗺'; print join("", reverse $string =~ /\X/g), "\n";
Give a code snippet in #Perl 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/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Rust
Rust
use std::io::{stdin, prelude::*}; fn main() { let src = include_str!("main.rs"); let mut input = String::new(); stdin() .lock() .read_to_string(&mut input) .expect("Could not read from STDIN"); println!("{}", src == input); }
Give a code snippet in #Rust Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#Wren
Wren
import "/sort" for Sort import "/fmt" for Fmt   var cubesSum = {} var taxicabs = []   for (i in 1..1199) { for (j in i+1..1200) { var sum = i*i*i + j*j*j if (!cubesSum[sum]) { cubesSum[sum] = [i, j] } else { taxicabs.add([sum, cubesSum[sum], [i, j]]) } } }...
Give a code snippet in #Wren A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also kno...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Myrddin
Myrddin
use std   const main = { match std.dial("tcp!localhost!256") | `std.Ok fd: std.write(fd, "hello socket world") std.close(fd) | `std.Err err: std.fatal("could not open fd: {}\n", err) ;; }
Give a code snippet in #Myrddin For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#XPL0
XPL0
string 0; \use zero-terminated string convention code Text=12;   func StrLen(A); \Return number of characters in an ASCIIZ string char A; int I; for I:= 0 to -1>>1-1 do if A(I) = 0 then return I;   proc IncStr(S); \Increment a numeric string char S; int I; [for I:= StrLen(S)-1 do...
Give a code snippet in #XPL0 Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Perl
Perl
use 5.020; use feature qw<signatures>; no warnings qw<experimental::signatures>;   use constant zero => sub ($f) { sub ($x) { $x }};   use constant succ => sub ($n) { sub ($f) { sub ($x) { $f->($n->($f)($x)) }}};   use constant add => sub ($n) { ...
Give a code snippet in #Perl Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Wren
Wren
var lines = [ "---------- Ice and Fire ------------", " ", "fire, in end will world the say Some", "ice. in say Some ", "desire of tasted I've what From ", "fire. favor who those with hold I ", " ...
Give a code snippet in #Wren Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by space...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8
Read a file character by character/UTF8
Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support the reading of files contain...
#zkl
zkl
fcn readUTF8c(chr,s=""){ // transform UTF-8 character stream s+=chr; try{ s.len(8); return(s) } catch{ if(s.len()>6) throw(__exception) } // 6 bytes max for UTF-8 return(Void.Again,s); // call me again with s & another character }
Give a code snippet in #zkl Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#MUMPS
MUMPS
DOTPROD(A,B)  ;Returns the dot product of two vectors. Vectors are assumed to be stored as caret-delimited strings of numbers.  ;If the vectors are not of equal length, a null string is returned. QUIT:$LENGTH(A,"^")'=$LENGTH(B,"^") "" NEW I,SUM SET SUM=0 FOR I=1:1:$LENGTH(A,"^") SET SUM=SUM+($PIECE(A,"^",I)*$PIECE(...
Give a code snippet in #MUMPS Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#WDTE
WDTE
let memo a m n => true { == m 0 => + n 1; == n 0 => a (- m 1) 1; true => a (- m 1) (a m (- n 1)); };
Give a code snippet in #WDTE The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#PicoLisp
PicoLisp
(scl 6)   (de leftRect (Fun X) (Fun X) )   (de rightRect (Fun X H) (Fun (+ X H)) )   (de midRect (Fun X H) (Fun (+ X (/ H 2))) )   (de trapezium (Fun X H) (/ (+ (Fun X) (Fun (+ X H))) 2) )   (de simpson (Fun X H) (*/ (+ (Fun X) (* 4 (Fun (+ X (/ H 2)))) (Fun (+ X H)) ) ...
Give a code snippet in #PicoLisp Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#APL
APL
binsrch←{ ⎕IO(⍺{ ⍝ first lower bound is start of array ⍵<⍺:⍬ ⍝ if high < low, we didn't find it mid←⌊(⍺+⍵)÷2 ⍝ calculate mid point ⍺⍺[mid]>⍵⍵:⍺∇mid-1 ⍝ if too high, search from ⍺ to mid-1 ⍺⍺[mid]<⍵⍵:(mid+1)∇⍵ ⍝ if too low, sea...
Give a code snippet in #APL A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret num...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isPangram(s As Const String) As Boolean Dim As Integer length = Len(s) If length < 26 Then Return False Dim p As String = LCase(s) For i As Integer = 97 To 122 If Instr(p, Chr(i)) = 0 Then Return False Next Return True End Function   Dim s(1 To 3) As String = _ { _ "The qui...
Give a code snippet in #FreeBASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity...
#Clojure
Clojure
: \ ? = ~ / ! # $ % & * + - < > @ ^ ` | , ' ;
Give a code snippet in #Clojure This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#R
R
x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) y <- c(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0)
Give a code snippet in #R Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58....
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Rust
Rust
fn is_prime(n: u64) -> bool { match n { 0 | 1 => false, 2 => true, _even if n % 2 == 0 => false, _ => { let sqrt_limit = (n as f64).sqrt() as u64; (3..=sqrt_limit).step_by(2).find(|i| n % i == 0).is_none() } } }   fn main() { for i in (1..30).f...
Give a code snippet in #Rust Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Tcl
Tcl
proc writefile {filename data} { set fd [open $filename w] ;# truncate if exists, else create try { puts -nonewline $fd $data } finally { close $fd } }
Give a code snippet in #Tcl Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#Phix
Phix
with javascript_semantics procedure test(atom a) if -3*PI/4 >= a then ?9/0 end if if 5*PI/4 <= a then ?9/0 end if string s = sprint(tan(a)) ?s -- or test for "1.0"/"1", but not 1.0 end procedure test( arctan(1 / 2) + arctan(1 / 3)) test( 2*arctan(1 / 3) + arctan(1 / 7)) test( 4*arctan(...
Give a code snippet in #Phix Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing th...
christopher/rosetta-code
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\inft...
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) fcn dconv1D(f,g){ fsz,hsz:=f.len(), g.len() - fsz +1; A:=GSL.Matrix(g.len(),hsz); foreach n,fn in ([0..].zip(f)){ foreach rc in (hsz){ A[rc+n,rc]=fn } } h:=A.AxEQb(g); h }
Give a code snippet in #zkl The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Wren
Wren
import "meta" for Meta   var x Meta.eval("x = 2") System.print("First x = %(x)") var y = x // save this value   Meta.eval("x = 5") System.print("Second x = %(x)")   Meta.eval("x = x - y") System.print("Delta x = %(x)")
Give a code snippet in #Wren x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Nim
Nim
import os   moveFile("input.txt", "output.txt") moveFile("docs", "mydocs")   moveFile(DirSep & "input.txt", DirSep & "output.txt") moveFile(DirSep & "docs", DirSep & "mydocs")
Give a code snippet in #Nim Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the righ...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Forth
Forth
variable bitsbuff   : char>6bits ( c -- u ) dup 43 = if drop 62 exit then ( + case ) dup 47 = if drop 63 exit then ( / case ) dup 48 58 within if 48 - 52 + exit then ( 0-9 case ) dup 65 91 within if 65 - exit then ( A-Z case ) dup 97 123 within if 97 - 26 + exit t...
Give a code snippet in #Forth See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output wi...
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...
#Rascal
Rascal
import IO; import util::Math;   str html(str title, str content) = item("html", item("title", title) + item("body", content)); str item(str op, str content) = "\<<op>\><content>\</<op>\>"; str table(str content) = item("table border=\"0\"", content); str tr(str content) = item("tr", content); str td(str content) = item...
Give a code snippet in #Rascal 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 wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#Lingo
Lingo
---------------------------------------- -- Returns string representation of given date object in YYYY-MM-DD hh:mm:ii format -- @param {date} dateObj -- @returns {string} ---------------------------------------- on dateToDateTimeString (dateObj) str = "" s = string(dateObj.year) if s.length<4 then put "0000".char...
Give a code snippet in #Lingo Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Java
Java
if(s.equals("Hello World")) { foo(); } else if(s.equals("Bye World")) bar();//{}'s optional for one-liners else { deusEx(); }
Give a code snippet in #Java Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common c...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#Scala
Scala
import scala.io.Source   object HttpTest extends App { System.setProperty("http.agent", "*")   Source.fromURL("http://www.rosettacode.org").getLines.foreach(println) }
Give a code snippet in #Scala Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Frink
Frink
  e pi, π // Unicode can also be written in ASCII programs as \u03C0 sqrt[x] ln[x] // Natural log log[x] // Log to base 10 exp[x], e^x abs[x] floor[x] // Except for complex numbers where there's no good interpretation. ceil[x] // Except for complex numbers where there's no good interpretation. x^y  
Give a code snippet in #Frink Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "m...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#MiniScript
MiniScript
singles = " one two three four five six seven eight nine ".split teens = "ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen ".split tys = " twenty thirty forty fifty sixty seventy eighty ninety".split ions = "thousand million billion".split   numberName = function(n) if n == 0 then re...
Give a code snippet in #MiniScript Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than...
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 ...
#Ruby
Ruby
def fib(n) if n < 2 n else prev, fib = 0, 1 (n-1).times do prev, fib = fib, fib + prev end fib end end   p (0..10).map { |i| fib(i) }
Give a code snippet in #Ruby 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Java
Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;   public class Narcissist { private static final String SOURCE = "import java.io.BufferedReader;%nimport java.io.IOException;%nimport java.io.InputStreamReader;%n%npublic class Narcissist {%n private static final String ...
Give a code snippet in #Java Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C.23
C#
  public static class PancakeSorter { public static void Sort<T>(List<T> list) where T : IComparable { if (list.Count < 2) { return; } int i, a, max_num_pos; for (i = list.Count; i > 1; i--) { max_num_pos = 0; for (a = 0; a < i;...
Give a code snippet in #C.23 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#D
D
import std.stdio, std.algorithm, std.complex; import std.math: PI;   auto radians(T)(in T d) pure nothrow @nogc { return d * PI / 180; } auto degrees(T)(in T r) pure nothrow @nogc { return r * 180 / PI; }   real meanAngle(T)(in T[] D) pure nothrow @nogc { immutable t = reduce!((a, d) => a + d.radians.expi)(0.comple...
Give a code snippet in #D When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#JavaScript
JavaScript
Math.max.apply(null, [ 0, 1, 2, 5, 4 ]); // 5
Give a code snippet in #JavaScript Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Stata
Stata
n=7 exp(2i*pi()/n*(0::n-1)) 1 +-----------------------------+ 1 | 1 | 2 | .623489802 + .781831482i | 3 | -.222520934 + .974927912i | 4 | -.900968868 + .433883739i | 5 | -.900968868 - .433883739i | 6 | -.222520934 - .974927912i | 7 | ...
Give a code snippet in #Stata The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Lingo
Lingo
-- in a movie script on assert (ok, message) if not ok then if not voidP(message) then _player.alert(message) abort -- exits from current call stack, i.e. also from the caller function end if end   -- anywhere in the code on test x = 42 assert(x=42, "Assertion 'x=42' failed") put "this shows up" x =...
Give a code snippet in #Lingo Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#K
K
  /Matrix Exponentiation /mpow.k pow: {:[0=y; :({a=/:a:!x}(#x))];a: x; do[y-1; a: x _mul a]; :a}    
Give a code snippet in #K Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Rust
Rust
fn main() { // Rust has a lot of neat things you can do with functions: let's go over the basics first fn no_args() {} // Run function with no arguments no_args();   // Calling a function with fixed number of arguments. // adds_one takes a 32-bit signed integer and returns a 32-bit signed intege...
Give a code snippet in #Rust Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a var...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#GW-BASIC
GW-BASIC
10 RANDOMIZE TIMER  : REM set random number seed to something arbitrary 20 DIM ARR(10)  : REM initialise array 30 FOR I = 1 TO 10 40 ARR(I) = I*I  : REM squares of the integers is OK as a demo 50 NEXT I 60 C = 1 + INT(RND*10)  : REM get a random index from 1 to 10 inclusive 70 PRINT ARR(...
Give a code snippet in #GW-BASIC Demonstrate how to pick a random element from a list.
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 ...
#Befunge
Befunge
55+~>:48>*#8\#4`#:!#<#~_$>:#,_@
Give a code snippet in #Befunge 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 Emp...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Mirah
Mirah
empty_string1 = "" empty_string2 = String.new   puts "empty string is empty" if empty_string1.isEmpty() puts "empty string has no length" if empty_string2.length() == 0 puts "empty string is not nil" unless empty_string1 == nil
Give a code snippet in #Mirah Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Oth...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#PowerShell
PowerShell
  function dotproduct( $a, $b) { $a | foreach -Begin {$i = $res = 0} -Process { $res += $_*$b[$i++] } -End{$res} } dotproduct (1..2) (1..2) dotproduct (1..10) (11..20)  
Give a code snippet in #PowerShell Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -...
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind
Stirling numbers of the second kind
Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: S2(n, 0) and S2(0, k) = 0 ...
#Phix
Phix
with javascript_semantics include mpfr.e constant lim = 100, lim1 = lim+1, last = 12 sequence s2 = repeat(0,lim1) for n=1 to lim1 do s2[n] = mpz_inits(lim1) mpz_set_si(s2[n][n],1) end for mpz {t, m100} = mpz_inits(2) for n=1 to lim do for k=1 to n do mpz_set_si(t,k) mpz_...
Give a code snippet in #Phix Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Smart_BASIC
Smart BASIC
  'by rbytes, January 2017 OPTION BASE 1 P(" B U L L S A N D C O W S")!l P("A secret 4-digit number has been created, with") P("no repeats and no zeros. You must guess the number.") P("After each guess, you will be shown how many of your") P("digits are correct and in the matching location (bulls),") P("and how m...
Give a code snippet in #Smart_BASIC Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins i...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#gnuplot
gnuplot
# this is a comment   # backslash continues \ a comment to the next \ line or lines
Give a code snippet in #gnuplot Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Lasso
Lasso
define printArgs(...items) => stdoutnl(#items) define printEachArg(...) => with i in #rest do stdoutnl(#i)   printArgs('a', 2, (:3)) printEachArg('a', 2, (:3))
Give a code snippet in #Lasso Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. R...
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 |...
#68000_Assembly
68000 Assembly
ADD.L D0,D1 ; add two numbers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; SUB.L D1,D0 ; subtract D1 from D0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MULU D0,D1 ; multiply two unsigned numbers. Use MULS for signed numbers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DIVU D1,D0 ; Divide D0 by D1. Use DIVS for signed numbers. Upper two bytes of D0 ar...
Give a code snippet in #68000_Assembly 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 Op...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#WebAssembly
WebAssembly
(module  ;;The entry point for WASI is called _start (func $main (export "_start")   ) )  
Give a code snippet in #WebAssembly Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program caresarcode.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ STRINGSIZE, 500   /* Initialized data ...
Give a code snippet in #ARM_Assembly Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrappi...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#J
J
  wilson=: 0 = (| !&.:<:) (#~ wilson) x: 2 + i. 30 2 3 5 7 11 13 17 19 23 29 31  
Give a code snippet in #J Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wiki...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Component_Pascal
Component Pascal
  MODULE CountOctal; IMPORT StdLog,Strings;   PROCEDURE Do*; VAR i: INTEGER; resp: ARRAY 32 OF CHAR; BEGIN FOR i := 0 TO 1000 DO Strings.IntToStringForm(i,8,12,' ',TRUE,resp); StdLog.String(resp);StdLog.Ln END END Do; END CountOctal.    
Give a code snippet in #Component_Pascal Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Tcl
Tcl
package require Tk   proc output_ppm {image filename} { $image write $filename -format ppm }   set img [newImage 150 150] fill $img red setPixel $img green 40 40 output_ppm $img filename.ppm   # check the file format: set fh [open filename.ppm] puts [gets $fh] ;# ==> P6 puts [gets $fh] ;# ==> 150 150 puts [gets $fh...
Give a code snippet in #Tcl Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#Pascal
Pascal
Program ImageNoise;   uses SDL;   var surface: PSDL_Surface; pixel: ^byte; frameNumber, totalTime, lastTime, time, i: longint;   begin frameNumber := 0; totalTime := 0; lastTime := 0; randomize; SDL_Init(SDL_INIT_TIMER or SDL_INIT_VIDEO); surface := SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF o...
Give a code snippet in #Pascal Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Rust
Rust
  use rand::prelude::*; use std::collections::HashMap; use std::fmt::{Display, Formatter, Error};   pub struct Seq<'a> { alphabet: Vec<&'a str>, distr: rand::distributions::Uniform<usize>, pos_distr: rand::distributions::Uniform<usize>, seq: Vec<&'a str>, }   impl Display for Seq<'_> { fn fmt(&self,...
Give a code snippet in #Rust Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Smalltalk
Smalltalk
"Comments traditionally are in double quotes." "Multiline comments are also supported. Comments are saved as metadata along with the source to a method. A comment just after a method signature is often given to explain the usage of the method. The class browser may display such comments specially."
Give a code snippet in #Smalltalk Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of...
#C.2B.2B
C++
#include <array> #include <iostream>   int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; }   class RNG { private: // First generator const std::array<int64_t, 3> a1{ ...
Give a code snippet in #C.2B.2B MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0]...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#DBL
DBL
XCALL RENAM ("output.txt","input.txt") .IFDEF UNIX XCALL SPAWN ("mv docs mydocs") .ENDC .IFDEF DOS XCALL SPAWN ("ren docs mydocs") .ENDC .IFDEF VMS XCALL SPAWN ("rename docs.dir mydocs.dir") .ENDC
Give a code snippet in #DBL Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the righ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or ...
#QB64
QB64
_Title "Pythagoras Tree"   Dim As Integer sw, sh sw = 640 sh = 480   Screen _NewImage(sw, sh, 32)   Call pythTree(sw / 2 - sw / 12, sh - 30, sw / 2 + sw / 12, sh - 30, 0)   Sleep System   Sub pythTree (ax As Integer, ay As Integer, bx As Integer, by As Integer, depth As Integer) Dim As Single cx, cy, dx, dy, ex, ey...
Give a code snippet in #QB64 The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using...
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
#Elixir
Elixir
defmodule RC do def find_roots(f, range, step \\ 0.001) do first .. last = range max = last + step / 2 Stream.iterate(first, &(&1 + step)) |> Stream.take_while(&(&1 < max)) |> Enum.reduce(sign(first), fn x,sn -> value = f.(x) cond do abs(value) < step / 100 -> ...
Give a code snippet in #Elixir 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/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#D
D
import std.stdio, std.array;   T[] lcs(T)(in T[] a, in T[] b) pure nothrow @safe { if (a.empty || b.empty) return null; if (a[0] == b[0]) return a[0] ~ lcs(a[1 .. $], b[1 .. $]); const longest = (T[] x, T[] y) => x.length > y.length ? x : y; return longest(lcs(a, b[1 .. $]), lcs(a[1 .. $], b)); ...
Give a code snippet in #D Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings d...
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#Scala
Scala
  import scala.io.Source   object WebTime extends Application { val text = Source.fromURL("http://tycho.usno.navy.mil/cgi-bin/timer.pl") val utc = text.getLines.find(_.contains("UTC")) utc match { case Some(s) => println(s.substring(4)) case _ => println("error") } }  
Give a code snippet in #Scala Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this pa...
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#VBA
VBA
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant '-- Machine definitions Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ ...
Give a code snippet in #VBA One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine i...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#SNOBOL4
SNOBOL4
define('chr(n)') :(chr_end) chr &alphabet tab(n) len(1) . chr :s(return)f(freturn) chr_end   define('asc(str)c') :(asc_end) asc str len(1) . c &alphabet break(c) @asc :s(return)f(freturn) asc_end   * # Test and display output = char(65) ;* Built-in output = chr(65) ...
Give a code snippet in #SNOBOL4 Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. ...
#C.2B.2B
C++
  #include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector>   typedef std::pair<int, std::vector<int> > puzzle;   class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { ...
Give a code snippet in #C.2B.2B Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the...
christopher/rosetta-code
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Swift
Swift
func cholesky(matrix: [Double], n: Int) -> [Double] { var res = [Double](repeating: 0, count: matrix.count)   for i in 0..<n { for j in 0..<i+1 { var s = 0.0   for k in 0..<j { s += res[i * n + k] * res[j * n + k] }   if i == j { res[i * n + j] = (matrix[i * n + i] - s).s...
Give a code snippet in #Swift Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interp...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Batch_File
Batch File
if condition exit
Give a code snippet in #Batch_File Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object final...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Arturo
Arturo
nums: [[1000 "M"] [900 "CM"] [500 "D"] [400 "CD"] [100 "C"] [90 "XC"] [50 "L"] [40 "XL"] [10 "X"] [9 "IX"] [5 "V"] [4 "IV"] [1 "I"])   toRoman: function [x][ ret: "" idx: 0 initial: x loop nums 'num [ d: num\0 l: num\1   i: 0 while [i<initial/d] [ ret: ret ++ l ...
Give a code snippet in #Arturo Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a va...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#AutoIt
AutoIt
  $irnd = Random(1, 10, 1) $iinput = -1 While $input <> $irnd $iinput = InputBox("Choose a number", "Please chosse a Number between 1 and 10") WEnd MsgBox(0, "Success", "Well guessed!")  
Give a code snippet in #AutoIt Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Clojure
Clojure
(mapc #'use-package '(#:toadstool #:toadstool-system)) (defstruct (red-black-tree (:constructor tree (color left val right))) color left val right)   (defcomponent tree (operator macro-mixin)) (defexpand tree (color left val right) `(class red-black-tree red-black-tree-color ,color red-blac...
Give a code snippet in #Clojure Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example,...
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...
#F.23
F#
open System open System.Threading   // current time in seconds let now() = float( DateTime.Now.Ticks / 10000L ) / 1000.0   type Integrator( intervalMs ) as x = let mutable k = fun _ -> 0.0 // function to integrate let mutable s = 0.0 // current value let mutable t0 = now() // last time s was upd...
Give a code snippet in #F.23 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 me...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/2
Text processing/2
The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters...
#Ursala
Ursala
#import std #import nat   readings = (*F ~&c/;digits+ rlc ==+ ~~ -={` ,9%cOi&,13%cOi&}) readings_dot_txt   valid_format = all -&length==49,@tK27 all ~&w/`.&& ~&jZ\digits--'-.',@tK28 all ~&jZ\digits--'-'&-   duplicate_dates = :/'duplicated dates:'+ ~&hK2tFhhPS|| -[(none)]-!   good_readings = --' good readin...
Give a code snippet in #Ursala The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one...
christopher/rosetta-code
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the i...
#Python
Python
import requests   for addr in ['88:53:2E:67:07:BE', 'FC:FB:FB:01:FA:21', 'D4:F4:6F:C9:EF:8D', '23:45:67']: vendor = requests.get('http://api.macvendors.com/' + addr).text print(addr, vendor)
Give a code snippet in #Python Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#Ol
Ol
  (define p (open-output-file "/dev/lp0")) (when p (print-to p "Hello world!") (close-port p))  
Give a code snippet in #Ol Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some sy...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Tcl
Tcl
set toTTY [dict exists [fconfigure stdout] -mode] puts [expr {$toTTY ? "Output goes to tty" : "Output doesn't go to tty"}]
Give a code snippet in #Tcl Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Racket
Racket
  #lang racket/base   ;; define a quick SH256 FFI interface, similar to the Racket's default ;; SHA1 interface (require ffi/unsafe ffi/unsafe/define openssl/libcrypto (only-in openssl/sha1 bytes->hex-string)) (define-ffi-definer defcrypto libcrypto) (defcrypto SHA256_Init (_fun _pointer -> _int)) (defcrypto ...
Give a code snippet in #Racket SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b7...
christopher/rosetta-code
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Python
Python
from collections import namedtuple from math import sqrt   Pt = namedtuple('Pt', 'x, y') Circle = Cir = namedtuple('Circle', 'x, y, r')   def circles_from_p1p2r(p1, p2, r): 'Following explanation at http://mathforum.org/library/drmath/view/53027.html' if r == 0.0: raise ValueError('radius of zero') ...
Give a code snippet in #Python Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number o...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#XLISP
XLISP
(DEFUN A-PLUS-B () (DISPLAY "Enter two numbers separated by a space.") (NEWLINE) (DISPLAY "> ") (DEFINE A (READ)) (DEFINE B (READ)) (+ A B))
Give a code snippet in #XLISP A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separate...
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#R
R
    library(combinat)   col <- factor(c("Red","Green","White","Yellow","Blue")) own <- factor(c("English","Swedish","Danish","German","Norwegian")) pet <- factor(c("Dog","Birds","Cats","Horse","Zebra")) drink <- factor(c("Coffee","Tea","Milk","Beer","Water")) smoke <- factor(c("PallMall", "Blend", "Dunhill", "BlueMaste...
Give a code snippet in #R Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Perl
Perl
sub entropy { my %count; $count{$_}++ for @_; my $entropy = 0; for (values %count) { my $p = $_/@_; $entropy -= $p * log $p; } $entropy / log 2 }   print entropy split //, "1223334444";
Give a code snippet in #Perl Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), t...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Bracmat
Bracmat
No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall.
Give a code snippet in #Bracmat Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall ...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts She...
#ACL2
ACL2
ACL2 !>(lexorder '(1 2 3) '(1 2 3 4)) T ACL2 !>(lexorder '(1 2 4) '(1 2 3)) NIL
Give a code snippet in #ACL2 sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin...
#Python
Python
from random import choice   def sleeping_beauty_experiment(repetitions): """ Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see how often we had heads on waking Sleeping Beauty. """ gotheadsonwaking = 0 wakenings = 0 for _ in range(repetitions): coin_resu...
Give a code snippet in #Python Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a S...
christopher/rosetta-code
http://rosettacode.org/wiki/Cut_a_rectangle
Cut a rectangle
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles...
#Raku
Raku
sub solve($hh, $ww, $recurse) { my ($h, $w, $t, @grid) = $hh, $ww, 0; state $cnt; $cnt = 0 if $recurse;   ($t, $w, $h) = ($w, $h, $w) if $h +& 1; return 0 if $h == 1; return 1 if $w == 1; return $h if $w == 2; return $w if $h == 2;   my ($cy, $cx) = ($h, $w) «div» 2; my $len = ...
Give a code snippet in #Raku A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#TorqueScript
TorqueScript
  while(isobject(RockPaperScissors)) RockPaperScissors.delete();   new scriptObject(RockPaperScissors);   function RockPaperScissors::startGame(%this) { %this.idle = true; echo("Starting rock paper scissors, please type choose(\"choice\"); to proceed!"); }   function RockPaperScissors::endGame(%this) { %this.idle =...
Give a code snippet in #TorqueScript Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#Fortran
Fortran
  !*************************************************************************************************** module evolve_routines !*************************************************************************************************** implicit none   !the target string: character(len=*),parameter :: targ = 'METHINKS ...
Give a code snippet in #Fortran Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of i...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: isPrime (in integer: number) is func result var boolean: result is FALSE; local var integer: count is 2; begin if number = 2 then result := TRUE; elsif number > 2 then while number rem count <> 0 and count * count <= number do inc...
Give a code snippet in #Seed7 Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:...
christopher/rosetta-code
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statemen...
#Tcl
Tcl
package require Tcl 8.6   # Function to evaluate the truth of a statement proc tcl::mathfunc::S {idx} { upvar 1 state s apply [lindex $s [expr {$idx - 1}]] $s } # Procedure to count the number of statements which are true proc S+ args { upvar 1 state state tcl::mathop::+ {*}[lmap i $args {expr {S($i)}}]...
Give a code snippet in #Tcl This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If state...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#Axe
Axe
.Enable 15 MHz full speed mode Full .Disable memory access delays (adds 1 FPS) Fullʳ   .Flush key presses While getKey(0) End   .Setup 0→F 0→N Fix 5 fnInt(FPS,6)   Repeat getKey(0) NOISE() F++ .Reset the FPS counter before it overflows F>606?0→F→N Text(0,0,F*108/N▶Dec) DispGraph End   .Clean up LnRegʳ Fix 4 Retur...
Give a code snippet in #Axe Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Icon_and_Unicon
Icon and Unicon
link graphics,printf   procedure main(A) e := ( 0 < integer(\A[1])) | 100 # 100 or whole number from command line LangtonsAnt(e) end   record antrec(x,y,nesw)   procedure LangtonsAnt(e) size := sprintf("size=%d,%d",e,e) label := sprintf("Langton's Ant %dx%d [%d]",e,e,0) &window := open(label,"g","bg=...
Give a code snippet in #Icon_and_Unicon Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Elena
Elena
import system'routines; import system'collections; import extensions;   class SMA { object thePeriod; object theList;   constructor new(period) { thePeriod := period; theList :=new List(); }   append(n) { theList.append(n);   var count := theList.Length; ...
Give a code snippet in #Elena Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#jq
jq
# Input: an array of strings. # Output: an object with the strings as keys, the values of which are the corresponding frequencies. def counter: reduce .[] as $item ( {}; .[$item] += 1 ) ;   # entropy in bits of the input string def entropy: (explode | map( [.] | implode ) | counter | [ .[] | . * log ] | add) as...
Give a code snippet in #jq Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Julia
Julia
  # Calling a function that requires no arguments: f() = print("Hello world!") f()     # Calling a function with a fixed number of arguments: function f(x, y, z) x*y - z^2 end   f(3, 4, 2)     # Calling a function with optional arguments: # Note Julia uses multiple dispatch based on argument number and type, so...
Give a code snippet in #Julia Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a va...
christopher/rosetta-code