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/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 ≤...
#Genie
Genie
[indent=4] /* A+B in Genie valac aplusb-genie.gs ./aplusb-genie */ init a:int64 = 0 b:int64 = 0 leftover:string = ""   print "Enter A and B, two numbers separated by space" line:string = stdin.read_line() res:bool = int64.try_parse(line, out a, out leftover) res = int64.try_parse(lefto...
Give a code snippet in #Genie 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/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
#Swift
Swift
import Foundation   // See https://en.wikipedia.org/wiki/Divisor_function func divisorCount(number: Int) -> Int { var n = number var total = 1 // Deal with powers of 2 first while (n & 1) == 0 { total += 1 n >>= 1 } // Odd prime factors up to the square root var p = 3 whi...
Give a code snippet in #Swift 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/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#OCaml
OCaml
open Graphics   let round x = truncate (floor (x +. 0.5))   let () = open_graph ""; let width = size_x () and height = size_y () in let bars = [| 8; 16; 32; 64 |] in let n = Array.length bars in Array.iteri (fun i bar -> let part = float width /. float bar in let y = (height / n) * (n - i - 1) in ...
Give a code snippet in #OCaml The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we h...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Kotlin
Kotlin
fun main(args: Array<String>) { val a: Array<Int> = arrayOf(1, 2, 3) // initialise a val b: Array<Int> = arrayOf(4, 5, 6) // initialise b val c: Array<Int> = (a.toList() + b.toList()).toTypedArray() println(c) }
Give a code snippet in #Kotlin Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Smalltalk
Smalltalk
|a| a := Array new: 100 . 1 to: 100 do: [ :i | a at: i put: false ].   1 to: 100 do: [ :pass | pass to: 100 by: pass do: [ :door | a at: door put: (a at: door) not . ] ].   "output" 1 to: 100 do: [ :door | ( 'door #%1 is %2' % { door . (a at: door) ifTrue: [ 'open' ] ifFalse: [ 'closed' ] } ) displayNl ...
Give a code snippet in #Smalltalk There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Raku
Raku
class Vector { has Real $.x; has Real $.y;   multi submethod BUILD (:$!x!, :$!y!) { * } multi submethod BUILD (:$length!, :$angle!) { $!x = $length * cos $angle; $!y = $length * sin $angle; } multi submethod BUILD (:from([$x1, $y1])!, :to([$x2, $y2])!) { $!x =...
Give a code snippet in #Raku Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (le...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#AutoHotkey
AutoHotkey
list := ["abc", "def", "gh", "ijklmnop", "hello", "world"] Random, randint, 1, % list.MaxIndex() MsgBox % List[randint]
Give a code snippet in #AutoHotkey Demonstrate how to pick a random element from a list.
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 |...
#Groovy
Groovy
def arithmetic = { a, b -> println """ a + b = ${a} + ${b} = ${a + b} a - b = ${a} - ${b} = ${a - b} a * b = ${a} * ${b} = ${a * b} a / b = ${a} / ${b} = ${a / b}  !!! Converts to floating point! (int)(a / b) = (int)(${a} / ${b}) = ${(int)(a / b)} ...
Give a code snippet in #Groovy Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#Julia
Julia
dosomething() = sleep(abs(randn()))   function runNsecondsworthofjobs(N) times = Vector{Float64}() totaltime = 0 runcount = 0 while totaltime < N t = @elapsed(dosomething()) push!(times, t) totaltime += t runcount += 1 end println("Ran job $runcount times, for tot...
Give a code snippet in #Julia Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish the...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
data = Import["Readings.txt","TSV"]; Print["duplicated dates: "]; Select[Tally@data[[;;,1]], #[[2]]>1&][[;;,1]]//Column Print["number of good records: ", Count[(Times@@#[[3;;All;;2]])& /@ data, 1], " (out of a total of ", Length[data], ")"]
Give a code snippet in #Mathematica.2FWolfram_Language 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...
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) ...
#Turing
Turing
for i : 1 .. 100 if i mod 15 = 0 then put "Fizzbuzz" elsif i mod 5 = 0 then put "Buzz" elsif i mod 3 = 0 then put "Fizz" else put i end if end for
Give a code snippet in #Turing 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   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#PARI.2FGP
PARI/GP
compose(f, g)={ x -> f(g(x)) };   compose(x->sin(x),x->cos(x)(1)
Give a code snippet in #PARI.2FGP Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_sentence_from_book
Random sentence from book
Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too). Keep a...
#ALGOL_68
ALGOL 68
# generate random sentences using text from a book as a basis #   # use the associative array in the Associate array/iteration task # PR read "aArray.a68" PR   # returns s with chars removed # PRIO REMOVE = 1; OP REMOVE = ( STRING s, chars )STRING: BEGIN [ ...
Give a code snippet in #ALGOL_68 Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence ...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Maple
Maple
convert(binomial(n,k),factorial);   binomial(5,3);
Give a code snippet in #Maple This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Tcl
Tcl
proc repstring {text} { set len [string length $text] for {set i [expr {$len/2}]} {$i > 0} {incr i -1} { set sub [string range $text 0 [expr {$i-1}]] set eq [string repeat $sub [expr {int(ceil($len/double($i)))}]] if {[string equal -length $len $text $eq]} { return $sub } } error "no repetition...
Give a code snippet in #Tcl Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.23
C#
using System;   class Program { static void Main() { int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); if (a < b) Console.WriteLine("{0} is less than {1}", a, b); if (a == b) Console.WriteLine("{0} equals {1}", a, b); if...
Give a code snippet in #C.23 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/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 ...
#Nemerle
Nemerle
if (the_answer == 42) FindQuestion() else Foo(); when (stock.price < buy_order) stock.Buy(); unless (text < "") Write(text);
Give a code snippet in #Nemerle 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. Commo...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#Phix
Phix
function lcs(string a, b) integer longest = 0 string best = "" for i=1 to length(a) do integer ch = a[i] for j=1 to length(b) do if ch=b[j] then integer n=1 while i+n<=length(a) and j+n<=length(b) and a[i+n]=b[j+n] do ...
Give a code snippet in #Phix Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecuti...
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: ...
#PHP
PHP
$a = array('a', 'b', 'c'); $b = array('A', 'B', 'C'); $c = array('1', '2', '3'); //These don't *have* to be strings, but it saves PHP from casting them later   if ((sizeOf($a) !== sizeOf($b)) || (sizeOf($b) !== sizeOf($c))){ throw new Exception('All three arrays must be the same length'); } foreach ($a as $key => $v...
Give a code snippet in #PHP 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 exampl...
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...
#AutoHotkey
AutoHotkey
; Submitted by MasterFocus --- http://tiny.cc/iTunis   ; [1] Generate the Hailstone Seq. for a number   List := varNum := 7 ; starting number is 7, not counting elements While ( varNum > 1 ) List .= ", " ( varNum := ( Mod(varNum,2) ? (varNum*3)+1 : varNum//2 ) ) MsgBox % List   ; [2] Seq. for starting number 27 has 1...
Give a code snippet in #AutoHotkey 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)...
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 ...
#CMake
CMake
set_property(GLOBAL PROPERTY fibonacci_0 0) set_property(GLOBAL PROPERTY fibonacci_1 1) set_property(GLOBAL PROPERTY fibonacci_next 2)   # var = nth number in Fibonacci sequence. function(fibonacci var n) # If the sequence is too short, compute more Fibonacci numbers. get_property(next GLOBAL PROPERTY fibonacci_nex...
Give a code snippet in #CMake 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/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#Perl
Perl
use strict; use warnings; use feature 'say'; use bigint try=>"GMP"; use ntheory qw<is_prime>;   # index of mininum value in list sub min_index { my $b = $_[my $i = 0]; $_[$_] < $b && ($b = $_[$i = $_]) for 0..$#_; $i }   sub iter1 { my $m = shift; my $e = 0; return sub { $m ** $e++; } } sub iter2 { my $m = shift; my...
Give a code snippet in #Perl A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the f...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#ARM_Assembly
ARM Assembly
.text .global _start _start: mov r0,#4 @ 4 disks, mov r1,#1 @ from pole 1, mov r2,#2 @ via pole 2, mov r3,#3 @ to pole 3. bl move mov r0,#0 @ Exit to Linux afterwards mov r7,#1 swi #0 @@@ Move r0 disks from r1 via r2 to r3 move: subs r0,r0,#1 @ One fewer disk in next iteration beq show @ If last disk, ju...
Give a code snippet in #ARM_Assembly Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/The_Name_Game
The Name Game
Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like this: Gary, Gary, bo-bary...
#VBA
VBA
Option Explicit   Sub Main() Dim a, r, i As Integer Const SCHEM As String = "(X), (X), bo-b(Y)^Banana-fana fo-f(Y)^Fee-fi-mo-m(Y)^(X)!^" 'init a = Array("GaRY", "Earl", "Billy", "Felix", "Mary", "Mike", "Frank") 'compute r = TheGameName(a, SCHEM) 'return For i = LBound(r) To UBound(r) Debug.Prin...
Give a code snippet in #VBA Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like ...
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...
#Elena
Elena
singleton linkHelper { insertAfter(Link prev, IntNumber i) { prev.Next := new Link(i, prev.Next) } }
Give a code snippet in #Elena 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 definitio...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Racket
Racket
  #lang Racket (define (radix-sort l r) (define queues (for/vector #:length r ([_ r]) (make-queue))) (let loop ([l l] [R 1]) (define all-zero? #t) (for ([x (in-list l)]) (define x/R (quotient x R)) (enqueue! (vector-ref queues (modulo x/R r)) x) (unless (zero? x/R) (set! all-zero? #f))) ...
Give a code snippet in #Racket Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Seed7
Seed7
var string: s is "12345";   s := str(succ(integer parse s));
Give a code snippet in #Seed7 Task Increment a numerical string.
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 ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Leonardo is   function Leo (N  : Natural; Step  : Natural := 1; First  : Natural := 1; Second : Natural := 1) return Natural is L : array (0..1) of Natural := (First, Second); begin for i in 1 .. N loop L := (L(1), L(0)+L(1)+St...
Give a code snippet in #Ada 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Ol
Ol
  (import (lib gl)) (import (OpenGL version-1-0))   ; init (glClearColor 0.3 0.3 0.3 1) (glOrtho 0 320 0 240 0 1)   ; draw loop (gl:set-renderer (lambda (mouse) (glClear GL_COLOR_BUFFER_BIT) (glBegin GL_POINTS) (glColor3f 255 0 0) (glVertex2f 100 100) (glEnd)))  
Give a code snippet in #Ol Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Nanoquery
Nanoquery
// create a list of numbers 1-10 numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}   // display the list as it is println numbers   // square each element in the list for i in range(1, len(numbers) - 1) numbers[i] = numbers[i] * numbers[i] end   // display the squared list println numbers
Give a code snippet in #Nanoquery Task Take a combined set of elements and apply a function to each element.
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: ...
#Fortran
Fortran
  ! compilation ! gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f ! ! EXAMPLE ! !$ ./f !rock, paper, scissors? papier !scoring computer choice (r) and your choice (p) !rock, paper, scissors? sizzerz !scoring computer choice (s) and your choice (s) !rock, paper, scissors? quit !scori...
Give a code snippet in #Fortran 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 winn...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Nanoquery
Nanoquery
try invalid "this statement will fail" catch e println "caught an exception" println e end try
Give a code snippet in #Nanoquery Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Except...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#OxygenBasic
OxygenBasic
  type KnapSackItem string name,sys dag,value,tag   KnapSackItem it[100]   sys dmax=400 sys items=22   it=>   "map", 9, 150, 0, "compass", 13, 35, 0, "water", 153, 200, 0, "sandwich", 50, 160, 0, "glucose", 15, 60, 0, "tin", 6...
Give a code snippet in #OxygenBasic A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#11l
11l
F hello() print(‘Hello, world!’)   String src F quine() print(:src)   F bottles() L(i) (99.<2).step(-1) print(‘#. bottles of beer on the wall’.format(i)) print(‘#. bottles of beer’.format(i)) print(‘Take one down, pass it around’) print(‘#. bottles of beer on the wall’.format(i - 1)) ...
Give a code snippet in #11l Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Lua
Lua
  function sum(var, a, b, str) local ret = 0 for i = a, b do ret = ret + setfenv(loadstring("return "..str), {[var] = i})() end return ret end print(sum("i", 1, 100, "1/i"))  
Give a code snippet in #Lua Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL...
christopher/rosetta-code
http://rosettacode.org/wiki/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....
#CLU
CLU
fitness = proc (s, t: string) returns (int) f: int := 0 for i: int in int$from_to(1,string$size(s)) do if s[i] ~= t[i] then f := f-1 end end return(f) end fitness   mutate = proc (mut: int, s: string) returns (string) own charset: string := " ABCDEFGHIJKLMNOPQRSTUVWXYZ" out: array[char] ...
Give a code snippet in #CLU 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Lingo
Lingo
-- parent script "CallFunction"   property _code   -- if the function is supposed to return something, the code must contain a line that starts with "res=" on new (me, code) me._code = code return me end   on call (me) ---------------------------------------- -- If custom arguments were passed, evaluate them ...
Give a code snippet in #Lingo Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
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 |...
#OCaml
OCaml
let extra = "little" in Printf.printf "Mary had a %s lamb." extra
Give a code snippet in #OCaml Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Jaro_similarity
Jaro similarity
The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   0   equates to no similarities and   1   is an exact match. Definition The...
#J
J
jaro=: dyad define d=. ((x >.&# y)%2)-1 e=. (x =/y) * d >: |x -/&(i.@#) y xm=. (+./"1 e)#x ym=. (+./"2 e)#y m=. xm <.&# ym t=. (+/xm ~:&(m&{.) ym)%2 s1=. #x s2=. #y ((m%s1)+(m%s2)+(m-t)%m)%3 )
Give a code snippet in #J The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   0   equates to no similarities and   1   is an exa...
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#D
D
void main() { import std.stdio, std.algorithm, std.range;   // Not true sets, items can be repeated, but must be sorted. auto s1 = [1, 2, 3, 4, 5, 6].assumeSorted; auto s2 = [2, 5, 6, 3, 4, 8].sort(); // [2,3,4,5,6,8]. auto s3 = [1, 2, 5].assumeSorted;   assert(s1.canFind(4)); // Linear search. ...
Give a code snippet in #D Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creat...
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...
#C.2B.2B
C++
#include <iostream>   int main() { std::cout << (int)'a' << std::endl; // prints "97" std::cout << (char)97 << std::endl; // prints "a" return 0; }
Give a code snippet in #C.2B.2B 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/HTTPS/Client-authenticated
HTTPS/Client-authenticated
Demonstrate how to connect to a web server over HTTPS where that server requires that the client present a certificate to prove who (s)he is. Unlike with the HTTPS request with authentication task, it is not acceptable to perform the authentication by a username/password or a set cookie. This task is in general useful...
#Rust
Rust
reqwest = {version = "0.11", features = ["native-tls", "blocking"]}
Give a code snippet in #Rust Demonstrate how to connect to a web server over HTTPS where that server requires that the client present a certificate to prove who (s)he is. Unlike with the HTTPS request with authentication task, it is not acceptable to perform the authentication by a username/password or a set cookie. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#Haskell
Haskell
import Data.Set (Set, fromList, insert, member)   ------------------- MIAN-CHOWLA SEQUENCE ----------------- mianChowlas :: Int -> [Int] mianChowlas = reverse . snd . (iterate nextMC (fromList [2], [1]) !!) . subtract 1   nextMC :: (Set Int, [Int]) -> (Set Int, [Int]) nextMC (sumSet, mcs@(n:_)) = (foldr insert sumS...
Give a code snippet in #Haskell The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairw...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Ruby
Ruby
def palindrome?(s) s == s.reverse end
Give a code snippet in #Ruby A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#AutoHotkey
AutoHotkey
myCol := Object() mycol.mykey := "my value!" mycol["mykey"] := "new val!" MsgBox % mycol.mykey ; new val
Give a code snippet in #AutoHotkey This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Run_BASIC
Run BASIC
for i = 0 to 100 print " fctrI(";right$("00";str$(i),2); ") = "; fctrI(i) print " fctrR(";right$("00";str$(i),2); ") = "; fctrR(i) next i end   function fctrI(n) fctrI = 1 if n >1 then for i = 2 To n fctrI = fctrI * i next i end if end function   function fctrR(n) fctrR = 1 if n > 1 then fctrR = n * fct...
Give a code snippet in #Run_BASIC Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#D
D
void main() { import std.stdio, std.algorithm;   levenshteinDistance("kitten", "sitting").writeln; }
Give a code snippet in #D This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and compute...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#FreeBASIC
FreeBASIC
' version 06-07-2015 ' compile with: fbc -s console ' uses gmp   #Include Once "gmp.bi"   ' in case the two #define's are missing from 'gmp.bi' define them now #Ifndef mpq_numref #Define mpq_numref(Q) (@(Q)->_mp_num) #Define mpq_denref(Q) (@(Q)->_mp_den) #EndIf   Dim As String prog(0 To ...) = {"17/91", "78/85"...
Give a code snippet in #FreeBASIC FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an in...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Unicode_output
Terminal control/Unicode output
The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note that it is permissible to use sys...
#Kotlin
Kotlin
// version 1.1.2   fun main(args: Array<String>) { val supportsUnicode = "UTF" in System.getenv("LANG").toUpperCase() if (supportsUnicode) println("This terminal supports unicode and U+25b3 is : \u25b3") else println("This terminal does not support unicode") }
Give a code snippet in #Kotlin The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note t...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   iArray = [ 1, 2, 3, 4, 5 ] -- a traditional array iList = Arrays.asList(iArray) -- a Java Collection "List" object iWords = '1 2 3 4 5' -- a list as a string of space delimited words     v1 = iArray[Random().nextInt(iA...
Give a code snippet in #NetRexx Demonstrate how to pick a random element from a list.
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.
#BASIC256
BASIC256
arraybase 1 dim array(5) array[1] = 1 array[2] = 2 array[3] = 3 array[4] = 4 array[5] = 5   sum = 0 prod = 1 for index = 1 to array[?] sum += array[index] prod *= array[index] next index print "The sum is "; sum #15 print "and the product is "; prod #120 end
Give a code snippet in #BASIC256 Task Compute the sum and product of an array of integers.
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...
#Elena
Elena
import extensions;   fib(n) { if (n < 0) { InvalidArgumentException.raise() };   ^ (n) { if (n > 1) { ^ this self(n - 2) + (this self(n - 1)) } else { ^ n } }(n) }   public program(...
Give a code snippet in #Elena 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 unwant...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#D.C3.A9j.C3.A0_Vu
Déjà Vu
stuff-going-wrong: raise :value-error   try: stuff-going-wrong catch value-error: !print "Whoops!"
Give a code snippet in #D.C3.A9j.C3.A0_Vu Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#PureBasic
PureBasic
#palletteSize = 128 Procedure.f XorPattern(x, y) ;compute the gradient value from the pixel values Protected result = x ! y ProcedureReturn Mod(result, #palletteSize) / #palletteSize EndProcedure   Procedure drawPattern() StartDrawing(ImageOutput(0)) DrawingMode(#PB_2DDrawing_Gradient) CustomGradient(@Xor...
Give a code snippet in #PureBasic Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Arturo
Arturo
powers: map 0..9 'x [ map 0..9 'y [ x ^ y ] ]   getPair: function [p,sz].memoize[ if not? numeric? last p -> return powers\[to :integer to :string first p]\[sz] return powers\[to :integer to :string first p]\[sz] + powers\[to :integer to :string last p]\[sz] ]   narcissistic?: function [n][ ...
Give a code snippet in #Arturo A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m...
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...
#Wren
Wren
import "/fmt" for Fmt   var multiplier = Fn.new { |n1, n2| Fn.new { |m| n1 * n2 * m } }   var orderedCollection = Fn.new { var x = 2.0 var xi = 0.5 var y = 4.0 var yi = 0.25 var z = x + y var zi = 1.0 / ( x + y ) return [[x, y, z], [xi, yi, zi]] }   var oc = orderedCollection.call() for (...
Give a code snippet in #Wren 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/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...
#8086_Assembly
8086 Assembly
mov ax,0070h call EncodeRoman mov si,offset StringRam call PrintString call NewLine   mov ax,1776h call EncodeRoman mov si,offset StringRam call PrintString call NewLine   mov ax,2021h call EncodeRoman mov si,offset StringRam call PrintString call NewLine   mov ax,3999h call EncodeRoman mov si,offset...
Give a code snippet in #8086_Assembly 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 wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#ALGOL_68
ALGOL 68
# String creation # STRING a,b,c,d,e,f,g,h,i,j,l,r; a := "hello world"; print((a, new line));   # String destruction (for garbage collection) # b := (); BEGIN LOC STRING lb := "hello earth"; # allocate off the LOC stack # HEAP STRING hb := "hello moon"; # allocate out of the HEAP space # ~ END; # local variable...
Give a code snippet in #ALGOL_68 Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings ac...
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...
#Excel
Excel
SLEEPINGB =LAMBDA(n, LET( headsWakes, LAMBDA(x, IF(1 = x, {1,1}, {0,2} ) )( RANDARRAY(n, 1, 0, 1, TRUE) ), CHOOSE( {1,2}, SUM(INDEX(headsWakes, 0, 1)), SUM(INDEX(headsWakes, 0, 2)) ...
Give a code snippet in #Excel 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 Su...
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
#Scheme
Scheme
(define str (read)) (define num (read)) (display "String = ") (display str) (display "Integer = ") (display num)
Give a code snippet in #Scheme 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/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#EchoLisp
EchoLisp
  (define -∏*2 (complex 0 (* -2 PI)))   (define (fft xs N) (if (<= N 1) xs (let* [ (N/2 (/ N 2)) (even (fft (for/vector ([i (in-range 0 N 2)]) [xs i]) N/2)) (odd (fft (for/vector ([i (in-range 1 N 2)]) [xs i]) N/2)) ] (for ((k N/2)) (vector*= odd k (exp (/ (* -∏*2 k) N )))) (vector-append (vector-map + ev...
Give a code snippet in #EchoLisp Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#HicEst
HicEst
REAL :: n=4, x(n), y(n) CHARACTER :: outP = "Test.txt"   OPEN(FIle = outP) x = (1, 2, 3, 1E11) y = x ^ 0.5 DO i = 1, n WRITE(FIle=outP, Format='F5, F10.3') x(i), y(i) ENDDO
Give a code snippet in #HicEst Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2,...
christopher/rosetta-code
http://rosettacode.org/wiki/Quoting_constructs
Quoting constructs
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati...
#Go
Go
package main   import ( "fmt" "os" "regexp" "strconv" )   /* Quoting constructs in Go. */   // In Go a Unicode codepoint, expressed as a 32-bit integer, is referred to as a 'rune' // but the more familiar term 'character' will be used instead here.   // Character literal (single quotes). // Can contain ...
Give a code snippet in #Go Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their p...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Smalltalk
Smalltalk
Directory extend [ wholeContent: aPattern do: twoBlock [ self wholeContent: aPattern withLevel: 0 do: twoBlock. ] wholeContent: aPattern withLevel: l do: twoBlock [ |cont| cont := (self contents) asSortedCollection. cont remove: '.'; remove: '..'. cont do: [ :n | |fn ps| ps := (Dire...
Give a code snippet in #Smalltalk Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative example of Currying in a specific la...
#zkl
zkl
addOne:= Op("+").fp(1); addOne(5) //-->6 minusOne:=Op("-").fp1(1); minusOne(5) //-->4, note that this fixed 1 as the second parameter // fix first and third parameters: foo:=String.fpM("101","<foo>","</foo>"); foo("zkl"); //-->"<foo>zkl</foo>" fcn g(x){x+1} f:=fcn(f,x){f(x)+x}.fp(g); f(5); //-->11 f:=fcn(f,x){f(x)+x...
Give a code snippet in #zkl This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative example...
christopher/rosetta-code
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603...
#Go
Go
package main   import ( "fmt" "strconv" )   func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd ...
Give a code snippet in #Go Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Common_Lisp
Common Lisp
(make-list n :initial-element (make-the-distinct-thing)) (make-array n :initial-element (make-the-distinct-thing))
Give a code snippet in #Common_Lisp Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are co...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Powershell
Powershell
  1..100 | Get-Random -Count 3  
Give a code snippet in #Powershell Demonstrate how to pick a random element from a list.
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...
#Maple
Maple
drawCircles := proc(x1, y1, x2, y2, r, $) local c1, c2, p1, p2; use geometry in if x1 = x2 and y1 = y2 then if r = 0 then printf("The circle is a point at [%a, %a].\n", x1, y1); else printf("The two points are the same. Infinite circles can be drawn.\n"); end if; elif evalf(distance(point(A, x1, ...
Give a code snippet in #Maple 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Picat
Picat
fact(N) = prod(1..N)
Give a code snippet in #Picat Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a n...
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...
#Nial
Nial
|loaddefs 'niallib/gcd.ndf' |gcd 6 4 =2
Give a code snippet in #Nial 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/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#Run_BASIC
Run BASIC
global basCvt$ basCvt$ ="0123456789abcdefghijklmnopqrstuvwxyz" html "<table border=1><tr bgcolor=wheat align=center><td>Decimal</td><td>To Base</td><td>Num</td><td>to Dec</td></tr>"   for i =1 to 10 RandNum = int(100 * rnd(1)) base = 2 +int(35 * rnd(1))   html "<tr align=right><td>";using("###...
Give a code snippet in #Run_BASIC Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in bi...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Logo
Logo
; Return the low 1-bits of :n ; For example if n = binary 10110111 = 183 ; then return binary 111 = 7 to low.ones :n output ashift (bitxor :n (:n+1)) -1 end   ; :fibbinary should be a fibbinary value ; return the next larger fibbinary value to fibbinary.next :fibbinary localmake "filled bitor :fibbinar...
Give a code snippet in #Logo The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#J
J
NB. check points on a regular grid within the bounding box     N=: 400 NB. grids in each dimension. Controls accuracy.     'X Y R'=: |: XYR=: (_&".;._2~ LF&=)0 :0 1.6417233788 1.6121789534 0.0848270516 -1.4944608174 1.2077959613 1.1039549836 0.6110294452 -0.6907087527 0.9089162485 0.3844862411 0.2923344616 0.23...
Give a code snippet in #J Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#Java
Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Locale; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;   public class WriteToWindowsEventLog { public static void main(String[] args) throws IOExceptio...
Give a code snippet in #Java Task Write script status to the Windows Event Log
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number i...
#FreeBASIC
FreeBASIC
Dim Shared seed As Integer = 675248 Dim i As Integer Declare Function Rand As Integer For i = 1 To 5 Print Rand Next i Sleep   Function Rand As Integer Dim s As String s = Str(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function  
Give a code snippet in #FreeBASIC Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of th...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#Lua
Lua
  tokens = 12   print("Nim Game\n") print("Starting with " .. tokens .. " tokens.\n\n")   function printRemaining() print(tokens .. " tokens remaining.\n") end   function playerTurn(take) take = math.floor(take) if (take < 1 or take > 3) then print ("\nTake must be between 1 and 3.\n") return false end   token...
Give a code snippet in #Lua Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Phix
Phix
global function factorial(integer n) atom res = 1 while n>1 do res *= n n -= 1 end while return res end function
Give a code snippet in #Phix Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Euphoria
Euphoria
sequence baseString, subString, findString integer findChar integer m, n   baseString = "abcdefghijklmnopqrstuvwxyz"   -- starting from n characters in and of m length; n = 12 m = 5 subString = baseString[n..n+m-1] puts(1, subString ) puts(1,'\n')   -- starting from n characters in, up to the end of the string; n = 12 ...
Give a code snippet in #Euphoria 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 Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related ...
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading;   namespace RotatingCube { public partial class Form1 : Form { double[][] nodes = { new double[] {-1, -1, -1}, new double[] {-1, -1, 1}, new double[] {-1, 1, -1}, ...
Give a code snippet in #C.23 Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspec...
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 ...
#QB64
QB64
    Print "QB64/Qbasic conditional structures" Dim k As String Menu 1 View Print 13 To 23 Print "A menu example using the many options of IF statement" k = " " 12: While k <> "" k = UCase$(Input$(1)) If k = "O" GoTo O If k = "F" Then 22 If k = "S" Then GoSub S: GoTo 12 If k = "C" Then GoSub 4: GoTo ...
Give a code snippet in #QB64 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/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 ...
#E
E
/** returns a if it is nonzero, otherwise b() */ def nonzeroOr(a, b) { return if (a.isZero()) { b() } else { a } }   ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] \ .sort(fn a, b { nonzeroOr(b.size().op__cmp(a.size()), fn { a.compareToIgnoreCase(b) }) ...
Give a code snippet in #E Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Befunge
Befunge
v > 543** >  :#v_ $&>  :#v_ 1 > :0g >  :#v_ $ 1+: 543** `! #v_ 25*,@ ^-1p0\0:< ^-1 p0\+1 g0:&< ^-1\.:\< ^ <
Give a code snippet in #Befunge Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Oforth
Oforth
q)3*2+1 9 q)(3*2)+1 / Brackets give the usual order of precedence 7 q)x:5 q)(x+5; x:20; x-5) 25 20 0
Give a code snippet in #Oforth 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/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Modula-2
Modula-2
MODULE ForBy; IMPORT InOut;   VAR i: INTEGER;   BEGIN FOR i := 0 TO 100 BY 2 DO InOut.WriteInt(i, 3); InOut.WriteLn END END ForBy.
Give a code snippet in #Modula-2 Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Plain_English
Plain English
To run: Start up. Write SPAM forever. Shut down.   To write SPAM forever: Write "SPAM" to the console. Repeat.
Give a code snippet in #Plain_English Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach...
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...
#R
R
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) # [,1] [,2] [,3] # [1,] 5 0 0 # [2,] 3 3 0 # [3,] -1 1 3   t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4))) # [,1] [,2] [,3] [,4] # [1,] 4.2426...
Give a code snippet in #R 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 interprete...
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
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 ...
#REXX
REXX
/*REXX program verifies that an array is sorted using a jortSort algorithm. */ parse arg $ /*obtain the list of numbers from C.L. */ if $='' then $=1 2 4 3 /*Not specified? Then use the default.*/ say 'array items=' space($) ...
Give a code snippet in #REXX 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/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#PicoLisp
PicoLisp
(let (Str "Here am I" Len (format (opt))) # Get length from command line (unless (>= (size Str) Len) # Check buffer size (prinl Str) ) ) # Return string if OK
Give a code snippet in #PicoLisp This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Dat...
christopher/rosetta-code
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PureBasic
PureBasic
#EndOfDataMarker$ = "::EndOfData::" DataSection ;"LIBRARY: [LIBRARY_DEPENDENCY_1 LIBRARY_DEPENDENCY_2 ... LIBRARY_DEPENDENCY_N] Data.s "des_system_lib: [std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]" Data.s "dw01: [ieee dw01 dware gtech]" ;Data.s "dw01: [ieee dw01 dware gtech dw04]" ;comment t...
Give a code snippet in #PureBasic Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#SPL
SPL
n = 1024 > #.output(n) n /= 2 < n!<1
Give a code snippet in #SPL Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward ...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Nanoquery
Nanoquery
def j(n, k) p = list(range(0, n-1)) i = 0 seq = {} while len(p) > 0 i = (i+k-1) % len(p) seq.append(p[i]) p.remove(i) end sur = seq[len(seq) - 1]; seq.remove(len(seq) - 1) return format("Prisoner killing order: %s\nS...
Give a code snippet in #Nanoquery Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
m = {{1, 3, 7, 8, 10}, {2, 4, 16, 14, 4}, {3, 1, 9, 18, 11}, {12, 14, 17, 18, 20}, {7, 1, 3, 9, 5}}; Total[LowerTriangularize[m, -1], 2]
Give a code snippet in #Mathematica.2FWolfram_Language Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,...
christopher/rosetta-code
http://rosettacode.org/wiki/Compile-time_calculation
Compile-time calculation
Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#Oforth
Oforth
10 seq reduce(#*) Constant new: FACT10 : newFunction FACT10 . ;
Give a code snippet in #Oforth Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
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...
#ALGOL_68
ALGOL 68
PROC eval_with_x = (STRING code, INT a, b)STRING: (INT x=a; evaluate(code) ) + (INT x=b; evaluate(code)); print((eval_with_x("2 ** x", 3, 5), new line))
Give a code snippet in #ALGOL_68 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#360_Assembly
360 Assembly
* calendar 08/06/2016 CALENDAR CSECT USING CALENDAR,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " ...
Give a code snippet in #360_Assembly Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 displa...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#UNIX_Shell
UNIX Shell
#!/bin/sh cd # Make our home directory current echo "Hello World!" > hello.jnk # Create a junk file # tape rewind # Uncomment this to rewind the tape tar c hello.jnk # Traditional archivers use magnetic tape by default # tar c hello.jnk > /dev/tape # With newer archivers redir...
Give a code snippet in #UNIX_Shell The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
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...
#Plain_TeX
Plain TeX
\newlinechar`\^^J \edef\tagetnumber{\number\numexpr1+\pdfuniformdeviate9}% \message{^^JI'm thinking of a number between 1 and 10, try to guess it!}% \newif\ifnotguessed \notguessedtrue \loop \message{^^J^^JYour try: }\read -1 to \useranswer \ifnum\useranswer=\tagetnumber\relax \message{You win!^^J}\notguessedfalse ...
Give a code snippet in #Plain_TeX 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Picat
Picat
fruit(apple,1). fruit(banana,2). fruit(cherry,4).   print_fruit_name(N) :- fruit(Name,N), printf("It is %w\nn", Name).
Give a code snippet in #Picat Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Julia
Julia
using Printf   analytical(n::Integer) = sum(factorial(n) / big(n) ^ i / factorial(n - i) for i = 1:n)   function test(n::Integer, times::Integer = 1000000) c = 0 for i = range(0, times) x, bits = 1, 0 while (bits & x) == 0 c += 1 bits |= x x = 1 << rand(0:(n -...
Give a code snippet in #Julia Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number ...
christopher/rosetta-code