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/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...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
plural i: if = 1 i "" "s"   bottles i: local :s plural i !print( to-str i " bottle"s" of beer on the wall, " to-str i " bottle"s" of beer," ) !print\ "You take one down, pass it around, " set :i -- i if i: set :s plural i !print( to-str i " bottle"s" of beer on the wall." ) bottles i else: !print "no mor...
Give a code snippet in #D.C3.A9j.C3.A0_Vu 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   ...
#Yabasic
Yabasic
limite = 2200 s = 3 dim l(limite) dim ladd(limite * limite * 2)   for x = 1 to limite x2 = x * x for y = x to limite ladd(x2 + y * y) = 1 next y next x   for x = 1 to limite s1 = s s = s + 2 s2 = s for y = x +1 to limite if ladd(s1) = 1 l(y) = 1 s1 = s1 + s2 ...
Give a code snippet in #Yabasic One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (i...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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
Procedure Stooge_Sort(Array L.i(1), i=0 , j=0) If j=0 j=ArraySize(L()) EndIf If L(i)>L(j) Swap L(i), L(j) EndIf If j-i>1 Protected t=(j-i+1)/3 Stooge_Sort(L(), i, j-t) Stooge_Sort(L(), i+t, j ) Stooge_Sort(L(), i, j-t) EndIf EndProcedure
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/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#D
D
import std.stdio;   extern(C) int isatty(int);   void main() { if (isatty(0)) writeln("Input comes from tty."); else writeln("Input doesn't come from tty."); }
Give a code snippet in #D Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#NetRexx
NetRexx
  $ TNRX=`mktemp T_XXXXXXXXXXXX` && test ! -e $TNRX.* && (echo 'say "Goodbye, World!"' >$TNRX; nrc -exec $TNRX; rm $TNRX $TNRX.*; unset TNRX)  
Give a code snippet in #NetRexx Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementa...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#PowerShell
PowerShell
  Get-Date | Get-Member -MemberType Property  
Give a code snippet in #PowerShell Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 ...
#Whitespace
Whitespace
var shellSort = Fn.new { |a| var n = a.count var gaps = [701, 301, 132, 57, 23, 10, 4, 1] for (gap in gaps) { if (gap < n) { for (i in gap...n) { var t = a[i] var j = i while (j >= gap && a[j-gap] > t) { a[j] = a[j - gap...
Give a code snippet in #Whitespace 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 | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#6502_Assembly
6502 Assembly
JSR $FFED ;returns screen width in X and screen height in Y dex  ;subtract 1. This is more useful for comparisons. dey  ;subtract 1. This is more useful for comparisons. stx $20 ;store in zero page ram sty $21 ;store in zero page ram
Give a code snippet in #6502_Assembly Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item...
#Lua
Lua
-- SUPPORT: function T(t) return setmetatable(t, {__index=table}) end function S(t) local s=T{} for k,v in ipairs(t) do s[v]=v end return s end table.each = function(t,f,...) for _,v in pairs(t) do f(v,...) end end table.copy = function(t) local s=T{} for k,v in pairs(t) do s[k]=v end return s end table.keys = function...
Give a code snippet in #Lua Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input set...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Tcl
Tcl
set Username "TestUser" set Filter "((&objectClass=*)(sAMAccountName=$Username))" set Base "dc=skycityauckland,dc=sceg,dc=com" set Attrs distinguishedName
Give a code snippet in #Tcl Make sure you Connect to Active Directory
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.
#PostScript
PostScript
[1 2 3 4 5] { dup mul = } forall
Give a code snippet in #PostScript Task Take a combined set of elements and apply a function to each element.
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 |...
#Standard_ML
Standard ML
val () = let val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in print ("a + b = " ^ Int.toString (a + b) ^ "\n"); print ("a - b = " ^ Int.toString (a - b) ^ "\n"); print ("a * b = " ^ Int.toString (a * b) ...
Give a code snippet in #Standard_ML 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 Opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_wheel
Color wheel
Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you understand how color wheels work and ...
#Raku
Raku
use Image::PNG::Portable;   my ($w, $h) = 300, 300;   my $out = Image::PNG::Portable.new: :width($w), :height($h);   my $center = $w/2 + $h/2*i;   color-wheel($out);   $out.write: 'Color-wheel-perl6.png';   sub color-wheel ( $png ) { ^$w .race.map: -> $x { for ^$h -> $y { my $vector = $center...
Give a code snippet in #Raku Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you underst...
christopher/rosetta-code
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many compu...
#J
J
sameFringe=: -:&([: ; <S:0)
Give a code snippet in #J Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic 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. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Haskell
Haskell
import Data.Complex (Complex, realPart)   type CD = Complex Double   quadraticRoots :: (CD, CD, CD) -> (CD, CD) quadraticRoots (a, b, c) | 0 < realPart b = ( (2 * c) / (- b - d), (- b - d) / (2 * a) ) | otherwise = ( (- b + d) / (2 * a), (2 * c) / (- b + d) ) where d = sqrt $ b ^ 2...
Give a code snippet in #Haskell This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . You...
christopher/rosetta-code
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Python
Python
'''Cheryl's Birthday'''   from itertools import groupby from re import split     # main :: IO () def main(): '''Derivation of the date.'''   month, day = 0, 1 print( # (3 :: A "Then I also know") # (A's month contains only one remaining day) uniquePairing(month)( # (2 :: ...
Give a code snippet in #Python Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Lingo
Lingo
//-------------------------------------- // Simple (unsafe) JSON decoder based on eval() // @param {string} json // @return {any} //-------------------------------------- function json_decode (json){ var o; eval('o='+json); return _json_decode_val(o); }   function _json_decode_val (o){ if (o==null) return undef...
Give a code snippet in #Lingo Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneous...
#Fortran
Fortran
program Wireworld implicit none   integer, parameter :: max_generations = 12 integer :: nrows = 0, ncols = 0, maxcols = 0 integer :: gen, ierr = 0 integer :: i, j character(1), allocatable :: cells(:,:) character(10) :: form, sub character(80) :: buff   ! open input file open(unit=8, file="wwinput.txt...
Give a code snippet in #Fortran Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cel...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Amazing_Hopper
Amazing Hopper
  #include <flow.h>   DEF-MAIN(argv, argc) BREAK-ON SET(c,0) WHILE (1) COND( KEY-PRESSED? ) SCAN-CODE(c) BREAK-IF ( c ) IS-ESCAPE CEND PRNL( "CODE = ", c ) WEND PRNL( "Last key pressed: ", c ) END  
Give a code snippet in #Amazing_Hopper Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
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...
#Raku
Raku
sub msq { state $seed = 675248; $seed = $seed² div 1000 mod 1000000; }   say msq() xx 5;
Give a code snippet in #Raku 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 res...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#R
R
#!/usr/bin/env Rscript   getProgram <- function(args) { sub("--file=", "", args[grep("--file=", args)]) }   args <- commandArgs(trailingOnly = FALSE) program <- getProgram(args)   cat("Program: ", program, "\n")   q("no")
Give a code snippet in #R The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name...
christopher/rosetta-code
http://rosettacode.org/wiki/Honeycombs
Honeycombs
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position...
#Scala
Scala
import java.awt.{BasicStroke, BorderLayout, Color, Dimension, Font, FontMetrics, Graphics, Graphics2D, Point, Polygon, RenderingHints} import java.awt.event.{KeyAdapter, KeyEvent, MouseAdapter, MouseEvent}   import javax.swing.{JFrame, JPanel}   import scala.math.{Pi, cos, sin}   object Honeycombs extends App { pri...
Give a code snippet in #Scala The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two a...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Fantom
Fantom
TRUE . \ -1 FALSE . \ 0
Give a code snippet in #Fantom Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Nim
Nim
import tables import sets import strformat   type Date = tuple[month: string, day: int]   const Dates = [Date ("May", 15), ("May", 16), ("May", 19), ("June", 17), ("June", 18), ("July", 14), ("July", 16), ("August", 14), ("August", 15), ("August", 17)]   const   MonthTable: Table[int, HashSet[string]] ...
Give a code snippet in #Nim Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Al...
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#Red
Red
Red [ Title: "Abstract Type" Original-Author: oofoe ]   ; The "shape" class is an abstract class -- it defines the "pen" ; property and "line" method, but "size" and "draw" are undefined and ; unimplemented.   shape: make object! [ pen: "X" size: none   line: func [count][loop count [prin self/pen] prin newl...
Give a code snippet in #Red Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#BASIC
BASIC
a = 0 DO a = a + 1 PRINT a LOOP WHILE a MOD 6 <> 0
Give a code snippet in #BASIC Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/D...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#jq
jq
def is_prime: if . == 2 then true else 2 < . and . % 2 == 1 and (. as $in | (($in + 1) | sqrt) as $m | [false, 3] | until( .[0] or .[1] > $m; [$in % .[1] == 0, .[1] + 2]) | .[0] | not) end ;   def relatively_prime: .[0] as $n | .[1] as $primes | ($n | sqrt) as $s |...
Give a code snippet in #jq An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emi...
christopher/rosetta-code
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#F.23
F#
  // QR decomposition. Nigel Galloway: January 11th., 2022 let n=[[12.0;-51.0;4.0];[6.0;167.0;-68.0];[-4.0;24.0;-41.0]]|>MathNet.Numerics.LinearAlgebra.MatrixExtensions.matrix let g=n|>MathNet.Numerics.LinearAlgebra.Matrix.qr printfn $"Matrix\n------\n%A{n}\nQ\n-\n%A{g.Q}\nR\n-\n%A{g.R}"  
Give a code snippet in #F.23 Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#REXX
REXX
/*REXX program solves the knapsack/unbounded problem: highest value, weight, and volume.*/   /* value weight volume */ maxPanacea= 0 /* ═══════ ══════ ══════ */ maxIchor = 0; panacea.$ = 3000  ; ...
Give a code snippet in #REXX A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Fantom
Fantom
  class Main { static Int f (Int n) { if (n <= 0) // ensure n > 0 return 1 else return n - m(f(n-1)) }   static Int m (Int n) { if (n <= 0) // ensure n > 0 return 0 else return n - f(m(n-1)) }   public static Void main () { 50.times |Int n| { echo (f(n)) } }...
Give a code snippet in #Fantom Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n...
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) ...
#Golfscript
Golfscript
100,{)6,{.(&},{1$1$%{;}{4*35+6875*25base{90\-}%}if}%\or}%n*
Give a code snippet in #Golfscript 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   Fiz...
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.
#Burlesque
Burlesque
  blsq ) {88 99 77 66 55}>] 99  
Give a code snippet in #Burlesque 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/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a function to compute the arithmetic-geomet...
#Python
Python
from math import sqrt   def agm(a0, g0, tolerance=1e-10): """ Calculating the arithmetic-geometric mean of two numbers a0, g0.   tolerance the tolerance for the converged value of the arithmetic-geometric mean (default value = 1e-10) """ an, gn = (a0 + g0) / ...
Give a code snippet in #Python This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a function ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#BASIC256
BASIC256
global f, max max = 36000 dim f(max)   call fusc()   for i = 0 to 60 print f[i]; " "; next i   print : print print " Index Value" d = 0 for i = 0 to max-1 if f[i] >= d then print rjust(string(i),10," "), rjust(string(f[i]),10," ") if d = 0 then d = 1 d *= 10 end if next i end   subroutine fus...
Give a code snippet in #BASIC256 Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Potion
Potion
"Hello world!\n" print
Give a code snippet in #Potion Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#MiniScript
MiniScript
swap = function(map, a, b) temp = map[a] map[a] = map[b] map[b] = temp end function   x = 1 y = 2 print "BEFORE: x=" + x + ", y=" + y swap(locals, "x", "y") print "AFTER: x=" + x + ", y=" + y
Give a code snippet in #MiniScript Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides gene...
christopher/rosetta-code
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#REXX
REXX
{blanks} {-│+} {blanks} {digits} {.} {digits} { {e│E} {-│+} exponent } {blanks}
Give a code snippet in #REXX Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Genie
Genie
[indent=4] init print args[0] print Path.get_basename(args[0]) print Environment.get_application_name() print Environment.get_prgname()
Give a code snippet in #Genie The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#MATLAB_.2F_Octave
MATLAB / Octave
  s=strsplit('Hello,How,Are,You,Today',',') fprintf(1,'%s.',s{:})  
Give a code snippet in #MATLAB_.2F_Octave Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Ot...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#HicEst
HicEst
CHARACTER string*100   DLG(Edit=string, Edit=num_value, Button='&OK', TItle='Enter 75000 for num_value') WRITE(Messagebox, Name) "You entered", string, num_value
Give a code snippet in #HicEst In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#Phix
Phix
with javascript_semantics sequence numbers = repeat(0,6) integer t,n while true do for i=1 to length(numbers) do sequence ni = sq_rand(repeat(6,4)) numbers[i] = sum(ni)-min(ni) end for t = sum(numbers) n = sum(sq_ge(numbers,15)) if t>=75 and n>=2 then exit end if ?"re-rolling..."...
Give a code snippet in #Phix RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sid...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#Quackery
Quackery
[ tuck over peek 1+ unrot poke ] is item++ ( n [ --> [ )   [ [] 10 times [ 0 join ] swap [ 10 /mod rot item++ swap dup 0 = until ] drop ] is digitcount ( n --> [ )   [ 0 swap witheach + ] is sum ( [ --> n )   [ 0 swap witheach [ swap 10 *...
Give a code snippet in #Quackery Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Elena
Elena
import forms; import extensions;   public class MainWindow : SDIDialog { Label lblClicks; Button btmClickMe;   //Store how much clicks the user doed int clicksCount;   constructor new() <= new() { lblClicks := Label.new(); btmClickMe := Button.new();   cli...
Give a code snippet in #Elena Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#SNUSP
SNUSP
/++.# \>.--.++<..+ +\ />+++++++.>-.+/ / \ />++++++>++\ < +  ? < > \ -<<++++++/ $++++\ - +  ! /++++/ > \++++++++++\ \+ %!/!\?/>>>,>>>>>>+++\/ !/?\<?\>>/ ...
Give a code snippet in #SNUSP 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/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Elena
Elena
import extensions;   swap(ref object v1, ref object v2) { var tmp := v1;   v1 := v2; v2 := tmp }   public program() { var n := 2; var s := "abc";   console.printLine(n," ",s);   swap(ref n, ref s);   console.printLine(n," ",s) }
Give a code snippet in #Elena Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericit...
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
#SmileBASIC
SmileBASIC
XSCREEN 3 DISPLAY 1 GPSET 100, 100, RGB(255, 0, 0) WAIT 60
Give a code snippet in #SmileBASIC 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/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Julia
Julia
using Printf   p = [1/i for i in 5:11] plen = length(p) q = [0.0, [sum(p[1:i]) for i = 1:plen]] plab = [char(i) for i in 0x05d0:(0x05d0+plen)] hi = 10^6 push!(p, 1.0 - sum(p)) plen += 1   accum = zeros(Int, plen)   for i in 1:hi accum[sum(rand() .>= q)] += 1 end   r = accum/hi   println("Rates at which items are se...
Give a code snippet in #Julia Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because flo...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Stata
Stata
mata function iseven(n) { return(mod(n,2)==0) }   function isodd(n) { return(mod(n,2)==1) } end
Give a code snippet in #Stata Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divi...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#LLVM
LLVM
; ModuleID = 'test.o' ;e means little endian ;p: { pointer size : pointer abi : preferred alignment for pointers } ;i same for integers ;v is for vectors ;f for floats ;a for aggregate types ;s for stack objects ;n: {size:size:size...}, best integer sizes target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:3...
Give a code snippet in #LLVM 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/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Go
Go
package main   import ( "fmt" "log" "math/big" )   var ( primes []*big.Int smallPrimes []int )   // cache all primes up to 521 func init() { two := big.NewInt(2) three := big.NewInt(3) p521 := big.NewInt(521) p29 := big.NewInt(29) primes = append(primes, two) smallPrimes...
Give a code snippet in #Go n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   ...
#FreeBASIC
FreeBASIC
' version 12-08-2017 ' compile with: fbc -s console   #Define max 2200   Dim As UInteger l, m, n, l2, l2m2 Dim As UInteger limit = max * 4 \ 15 Dim As UInteger max2 = limit * limit * 2 ReDim As Ubyte list_1(max2), list_2(max2 +1)   ' prime sieve, list_2(l) contains a 0 if l = prime For l = 4 To max2 Step 2 list_1...
Give a code snippet in #FreeBASIC One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#11l
11l
V prod = 1 V s = 0   -V x = +5 y = -5 z = -2 one = 1 three = 3 seven = 7   F body(j)  :s += abs(j) I abs(:prod) < 2 ^ 27 & j != 0  :prod *= j   L(j) (-three .. 3 ^ 3).step(three) {body(j)} L(j) (-seven .. seven).step(x) {body(j)} L(j) 555 .. 550 - y {body(j)} L(j) (22 .. -...
Give a code snippet in #11l Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as...
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,...
#App_Inventor
App Inventor
  when ScrapeButton.Click do set ScrapeWeb.Url to SourceTextBox.Text call ScrapeWeb.Get   when ScrapeWeb.GotText url,responseCode,responseType,responseContent do initialize local Left to split at first text (text: get responseContent, at: PreTextBox.Text) initialize local Right to "" in set Right to select ...
Give a code snippet in #App_Inventor 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (also trivalent, ternary, or trinary...
#PicoLisp
PicoLisp
(de 3not (A) (or (=0 A) (not A)) )   (de 3and (A B) (cond ((=T A) B) ((=0 A) (and B 0)) ) )   (de 3or (A B) (cond ((=T A) T) ((=0 A) (or (=T B) 0)) (T B) ) )   (de 3impl (A B) (cond ((=T A) B) ((=0 A) (or (=T B) 0)) (T T) ) )   (de 3equiv (A B) (cond ...
Give a code snippet in #PicoLisp This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (a...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Emacs_Lisp
Emacs Lisp
(defun move (n from to via) (if (= n 1) (message "Move from %S to %S" from to) (move (- n 1) from via to) (message "Move from %S to %S" from to) (move (- n 1) via to from)))
Give a code snippet in #Emacs_Lisp Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
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. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Elixir
Elixir
  defmodule TwoDimArray do   def create(w, h) do List.duplicate(0, w) |> List.duplicate(h) end   def set(arr, x, y, value) do List.replace_at(arr, x, List.replace_at(Enum.at(arr, x), y, value) ) end   def get(arr, x, y) do arr |> Enum.at(x) |> Enum.at(y) end end     width = IO.g...
Give a code snippet in #Elixir 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. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those num...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Julia
Julia
using Dates   has53weeks(year) = week(Date(year, 12, 28)) == 53   println(" Year 53 weeks?\n----------------") for year in 1990:2021 println(year, " ", has53weeks(year) ? "Yes" : "No") end  
Give a code snippet in #Julia Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#D
D
import std.stdio, std.random, std.algorithm;   // Zero-based line numbers. int oneOfN(in int n) { int choice = 0; foreach (immutable i; 1 .. n) if (!uniform(0, i + 1)) choice = i; return choice; }   void main() { int[10] bins; foreach (immutable i; 0 .. 1_000_000) bins[10...
Give a code snippet in #D A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#PL.2FI
PL/I
recaman: procedure options(main); declare A(0:30) fixed;   /* is X in the first N terms of the Recaman sequence? */ find: procedure(x, n) returns(bit); declare (x, n, i) fixed; do i=0 to n-1; if A(i)=x then return('1'b); end; return('0'b); end find;   /* g...
Give a code snippet in #PL.2FI The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. T...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#PARI.2FGP
PARI/GP
game()={ my(v=vecsort(vector(4,i,random(8)+1))); print("Form 24 using */+-() and: "v); while(1, my(ans=input); if (!valid(s,v), next); trap(, print("Arithmetic error"); next , if(eval(s)==24, break, print("Bad sum")) ) ); print("You win!") }; valid(s,v)={ my(op=vecsort(...
Give a code snippet in #PARI.2FGP The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those fou...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#langur
langur
var .hash = h{1: "abc", "1": 789}   # may assign with existing or non-existing hash key (if hash is mutable) .hash[7] = 49   writeln .hash[1] writeln .hash[7] writeln .hash["1"]   # using an alternate value in case of invalid index; prevents exception writeln .hash[1; 42] writeln .hash[2; 42]
Give a code snippet in #langur Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition,...
christopher/rosetta-code
http://rosettacode.org/wiki/Mastermind
Mastermind
Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may be repeated in the code The (...
#REXX
REXX
/*REXX pgm scores mastermind game with a human or CBLFs (Carbon Based Life Forms). */ parse arg let wid mxG oRep seed _ /*obtain optional arguments from the CL*/ arg . . . rep . /*get uppercase 4th argument " " " */ if let=='' | let=="," then let= 20 ...
Give a code snippet in #REXX Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may b...
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...
#Pascal
Pascal
var MyArray: array[1..5] of real; begin MyArray[1] := 4.35; end;
Give a code snippet in #Pascal 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Groovy
Groovy
'Enjoy Rosetta Code'.tokenize().collect { w -> Thread.start { Thread.sleep(1000 * Math.random() as int) println w } }.each { it.join() }
Give a code snippet in #Groovy Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your ...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Wren
Wren
import "random" for Random   var montyHall = Fn.new { |games| var rand = Random.new() var switchWins = 0 var stayWins = 0 for (i in 1..games) { var doors = [0] * 3 // all zero (goats) by default doors[rand.int(3)] = 1 // put car in a random door var choice = rand.int(3) ...
Give a code snippet in #Wren Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#R
R
a <- c( "John", "Bob", "Mary", "Serena" ) b <- c( "Jim", "Mary", "John", "Bob" ) c(setdiff(b, a), setdiff(a, b))   a <- c("John", "Serena", "Bob", "Mary", "Serena") b <- c("Jim", "Mary", "John", "Jim", "Bob") c(setdiff(b, a), setdiff(a, b))
Give a code snippet in #R Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\display...
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...
#Factor
Factor
USE: roman ( scratchpad ) 3333 >roman . "mmmcccxxxiii"
Give a code snippet in #Factor 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/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.
#Wren
Wren
import "dome" for Window import "graphics" for Canvas import "input" for Mouse   class Game { static init() { Window.title = "Mouse position" Canvas.resize(400, 400) Window.resize(400, 400) // get initial mouse coordinates __px = Mouse.x __py = Mouse.y __...
Give a code snippet in #Wren 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/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#S-lang
S-lang
variable foo = NULL; print(foo); if (foo == NULL) print(typeof(foo));  
Give a code snippet in #S-lang Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your lang...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Neko
Neko
/** Loops/Do-while in Neko Tectonics: nekoc loops-do-while.neko neko loops-do-while */   var index = 0; do { index += 1; $print(index, "\n"); } while (index % 6) != 0
Give a code snippet in #Neko Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Do...
christopher/rosetta-code
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#Fortran
Fortran
program nivengaps implicit none integer*8 prev /1/, gap /0/, sum /0/ integer*8 nividx /0/, niven /1/ integer gapidx /1/   character*13 idxfmt character*14 nivfmt write (*,*) 'Gap no Gap Niven index Niven number ' write (*,*) '------ --- ------...
Give a code snippet in #Fortran Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#Haskell
Haskell
  data DList a = Leaf | Node (DList a) a (DList a)   updateLeft _ Leaf = Leaf updateLeft Leaf (Node _ v r) = Node Leaf v r updateLeft new@(Node nl _ _) (Node _ v r) = current where current = Node prev v r prev = updateLeft nl new   updateRight _ Leaf = Leaf updateRight Leaf (Node l v _) = Node l v Leaf ...
Give a code snippet in #Haskell Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#REXX
REXX
/*REXX program demonstrates null strings, and also undefined values. */   if symbol('ABC')=="VAR" then say 'variable ABC is defined, value='abc"<<<" else say "variable ABC isn't defined." xyz=47 if symbol('XYZ')=="VAR" then say 'variable XYZ is defined, value='xyz"<<<" el...
Give a code snippet in #REXX Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your langua...
christopher/rosetta-code
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers
Index finite lists of positive integers
It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns an integer to any finite, arbi...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Rank,Unrank] Rank[x_List]:=FromDigits[Catenate[Riffle[IntegerDigits/@x,{{15}},{1,-1,2}]],16] Unrank[n_Integer]:=FromDigits/@SequenceSplit[IntegerDigits[n,16],{15}] Rank[{0,1,2,3,10,100,987654321,0}] Unrank[%] First@*Unrank@*Rank@*List /@ Range[0, 20]
Give a code snippet in #Mathematica_.2F_Wolfram_Language It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#ZX_Spectrum_Basic
ZX Spectrum Basic
9000 REM The function is immediately visible and usable 9010 DEF FN s(x)=x*x   PRINT FN s(5): REM This will work immediately GO TO 50: REM This will work immediately
Give a code snippet in #ZX_Spectrum_Basic Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
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
#QBasic
QBasic
' http://rosettacode.org/wiki/Draw_a_pixel ' This program can run in QBASIC, QuickBASIC, gw-BASIC (adding line numbers) and VB-DOS SCREEN 1 COLOR , 0 PSET (100, 100), 2 END
Give a code snippet in #QBasic 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/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...
#Emacs_Lisp
Emacs Lisp
(let ((i 99)) (while (> i 0) (message "%d bottles of beer on the wall" i) (message "%d bottles of beer" i) (message "Take one down, pass it around") (message "%d bottles of beer on the wall" (1- i)) (setq i (1- i))))
Give a code snippet in #Emacs_Lisp 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/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Swift
Swift
import Foundation   let path = "~/input.txt".stringByExpandingTildeInPath if let string = String(contentsOfFile: path, encoding: NSUTF8StringEncoding) { println(string) // print contents of file }
Give a code snippet in #Swift Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#Shen
Shen
(defmacro branch-if-macro [branch-if Cond1 Cond2 Both Fst Snd None] -> [if Cond1 [if Cond2 Both Fst] [if Cond2 Snd None]])
Give a code snippet in #Shen Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Perl
Perl
($y, $x) = ($x, $y);
Give a code snippet in #Perl Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Scala
Scala
import scala.math.BigInt   object MillerRabinPrimalityTest extends App { val (n, certainty )= (BigInt(args(0)), args(1).toInt) println(s"$n is ${if (n.isProbablePrime(certainty)) "probably prime" else "composite"}") }
Give a code snippet in #Scala This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin prima...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#PARI.2FGP
PARI/GP
const   DEC_VALUE = 15; HEX_VALUE = $F; OCTAL_VALUE = &017; BINARY_VALUE = %1111;  
Give a code snippet in #PARI.2FGP Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but shoul...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. 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 body...
#bc
bc
for (i = 10; i >= 0; i--) i quit
Give a code snippet in #bc Task Write a   for   loop which writes a countdown from   10   to   0. 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...
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...
#Euphoria
Euphoria
include std\console.e include std\graphics.e   sequence grid = repeat(repeat(1,100),100) --fill 100 by 100 grid with white (1) sequence antData = {48, 53, 360} --ant x coordinate, y coordinate, facing angle integer iterations = 0   --while ant isn't out of bounds of the 100 by 100 area.. while antData[1] > 0 and antDat...
Give a code snippet in #Euphoria 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#PowerShell
PowerShell
Function SubSequence ( [Array] $S, [Boolean] $all=$false ) { $sc = $S.count if( $sc -gt ( 2 - [Int32] $all ) ) { [void] $sc-- 0..$sc | ForEach-Object { $gap = $_ "$( $S[ $_ ] )" if( $gap -lt $sc ) { SubSequence ( ( $gap + 1 )..$sc | Where-Object { $_ -ne...
Give a code snippet in #PowerShell Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the fir...
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...
#Racket
Racket
  #lang racket (require math) (binomial 10 5)  
Give a code snippet in #Racket 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/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#FreeBASIC
FreeBASIC
' version 23-10-2016 ' compile with: fbc -s console   #Define max 9999 ' max number for the sieve   #Include Once "gmp.bi"   Dim As mpz_ptr p, p1 p = Allocate(Len(__mpz_struct)) : Mpz_init_set_ui(p, 1) p1 = Allocate(Len(__mpz_struct)) : Mpz_init(p1)   Dim As UInteger i, n, x Dim As Byte prime(max)   ' Sieve of Erat...
Give a code snippet in #FreeBASIC The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-of...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game/Player
Pig the dice game/Player
Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strategies involved. Show play dur...
#Raku
Raku
player 0 uses the default strategy, always roll if it can. player 1 will roll up to 5 times then lock in whatever it earned. player 2 will try to get at least 20 points per turn. player 3 randomly picks whether to roll again or not biased so that there is a 90% chance that it will. player 4 randomly chooses to ro...
Give a code snippet in #Raku Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strat...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#IS-BASIC
IS-BASIC
100 PRINT MODINV(42,2017) 120 DEF MODINV(A,B) 130 LET B=ABS(B) 140 IF A<0 THEN LET A=B-MOD(-A,B) 150 LET T=0:LET NT=1:LET R=B:LET NR=MOD(A,B) 160 DO WHILE NR<>0 170 LET Q=INT(R/NR) 180 LET TMP=NT:LET NT=T-Q*NT:LET T=TMP 190 LET TMP=NR:LET NR=R-Q*NR:LET R=TMP 200 LOOP 210 IF R>1 THEN 220 LET ...
Give a code snippet in #IS-BASIC From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Euphoria
Euphoria
include get.e   integer n,g n = rand(10)   puts(1,"I have thought of a number from 1 to 10.\n") puts(1,"Try to guess it!\n")   while 1 do g = prompt_number("Enter your guess: ",{1,10}) if n = g then exit end if puts(1,"Your guess was wrong. Try again!\n") end while   puts(1,"Well done! You guess...
Give a code snippet in #Euphoria 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/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#Ruby
Ruby
def euler(y, a, b, h) a.step(b,h) do |t| puts "%7.3f %7.3f" % [t,y] y += h * yield(t,y) end end   [10, 5, 2].each do |step| puts "Step = #{step}" euler(100,0,100,step) {|time, temp| -0.07 * (temp - 20) } puts end
Give a code snippet in #Ruby Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: ...
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 |...
#HolyC
HolyC
I64 *a, *b; a = Str2I64(GetStr("Enter your first number: ")); b = Str2I64(GetStr("Enter your second number: "));   if (b == 0) Print("Error: The second number must not be zero.\n"); else { Print("a + b = %d\n", a + b); Print("a - b = %d\n", a - b); Print("a * b = %d\n", a * b); Print("a / b = %d\n", a / b); /...
Give a code snippet in #HolyC 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/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
#Gambas
Gambas
Public Sub Main() Dim iInteger As Integer   MakeError DivError   iInteger = "2.54"   Catch Print Error.Text   End '______________________ Public Sub DivError()   Print 10 / 0   Catch Print Error.Text   End '______________________ Public Sub MakeError()   Error.Raise("My Error")   Catch Print Error.Text   End
Give a code snippet in #Gambas 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   Exception...
christopher/rosetta-code
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#OCaml
OCaml
let color_add (r1,g1,b1) (r2,g2,b2) = ( (r1 + r2), (g1 + g2), (b1 + b2) )   let color_div (r,g,b) d = ( (r / d), (g / d), (b / d) )   let compare_as_grayscale (r1,g1,b1) (r2,g2,b2) = let v1 = (2_126 * r1 + 7_152 * g1 + 722 * b1) and v2 = (2_126 * r2 + 7_152 * g2 + 722 * b2) in (Pervasives.co...
Give a code snippet in #OCaml The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
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.
#Logo
Logo
print apply "sum arraytolist {1 2 3 4 5} print apply "product arraytolist {1 2 3 4 5}
Give a code snippet in #Logo Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#Perl
Perl
#!/usr/bin/perl -w use strict ; use GD ;   my $image = new GD::Image( 320 , 240 ) ; my %colors = ( "white" => [ 255 , 255 , 255 ] , "red" => [255 , 0 , 0 ] , "green" => [ 0 , 255 , 0 ] , "blue" => [ 0 , 0 , 255 ] , "magenta" => [ 255 , 0 , 255 ] , "yellow" => [ 255 , 255 , 0 ] , "cyan" => [ 0 , 255 ,...
Give a code snippet in #Perl The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   mage...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#dc
dc
[* * (n) (c) lpx * Print number n, using at least c characters. * * Different from normal, this function: * 1. Uses the current ibase (not the obase) to print the number. * 2. Prunes "0" digits from the right, so [1.500 1 lxp] prints "1.5". * 3. Pads "0" digits to the left, so [_1.5 6 lxp] prints "-001.5". *...
Give a code snippet in #dc Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#Sidef
Sidef
require('XML::Simple');   var ref = %S'XML::Simple'.XMLin('<Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> ...
Give a code snippet in #Sidef Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender=...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#RapidQ
RapidQ
dim Blocks as string dim InWord as string   Function CanMakeWord (FInWord as string, FBlocks as string) as integer dim WIndex as integer, BIndex as integer   FBlocks = UCase$(FBlocks) - " " - "," FInWord = UCase$(FInWord)   for WIndex = 1 to len(FInWord) BIndex = instr(FBlocks, FInWord[WIndex]) ...
Give a code snippet in #RapidQ ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphab...
christopher/rosetta-code
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming langua...
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (de hailstone (N) (make (until (= 1 (link N)) (setq N (if (bit? 1 N) (inc (* N 3)) (/ N 2) ) ) ) ) )   (de hailtest () (let L (hailstone 27) (test 112 (length L)) (test (27 82 41 124) (head 4 L)) ...
Give a code snippet in #PicoLisp The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared o...
christopher/rosetta-code