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/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#360_Assembly
360 Assembly
ROT13 CSECT USING ROT13,R15 use calling register XPRNT CC,L'CC TR CC,TABLE translate XPRNT CC,L'CC TR CC,TABLE translate XPRNT CC,L'CC BR R14 return to caller CC DC CL10'{NOWHERE!}' TA...
Give a code snippet in #360_Assembly Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line...
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Groovy
Groovy
enum Pivoting { NONE({ i, it -> 1 }), PARTIAL({ i, it -> - (it[i].abs()) }), SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });   public final Closure comparer   private Pivoting(Closure c) { comparer = c } }   def isReducibleMatrix = { matrix -> def ...
Give a code snippet in #Groovy Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenie...
christopher/rosetta-code
http://rosettacode.org/wiki/One-time_pad
One-time pad
Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random encryption / decryption ( basic...
#Perl
Perl
# 20200814 added Perl programming solution   use strict; use warnings;   use Crypt::OTP; use Bytes::Random::Secure qw( random_bytes );   print "Message  : ", my $message = "show me the monKey", "\n";   my $otp = random_bytes(length $message); print "Ord(OTP)  : ", ( map { ord($_).' ' } (split //, $otp) ) , "\n";...
Give a code snippet in #Perl Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random e...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#Common_Lisp
Common Lisp
(setf (symbol-function '^) #'expt) ; Make ^ an alias for EXPT   (defun print-stack (token stack) (format T "~a: ~{~a ~}~%" token (reverse stack)))   (defun rpn (tokens &key stack verbose ) (cond ((and (not tokens) (not stack)) 0) ((not tokens) (car stack)) (T (let* ((current (car tokens)) ...
Give a code snippet in #Common_Lisp Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Run_BASIC
Run BASIC
print ackermann(1, 2)   function ackermann(m, n) if (m = 0) then ackermann = (n + 1) if (m > 0) and (n = 0) then ackermann = ackermann((m - 1), 1) if (m > 0) and (n > 0) then ackermann = ackermann((m - 1), ackermann(m, (n - 1))) end function
Give a code snippet in #Run_BASIC The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#E
E
#!/usr/bin/env rune   def f := <file:notes.txt> def date := makeCommand("date")   switch (interp.getArgs()) { match [] { if (f.exists()) { for line in f { print(line) } } } match noteArgs { def w := f.textWriter(true) w.print(date()[0], "\t", " ".rjoin(noteArgs), ...
Give a code snippet in #E Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT fol...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Crystal
Crystal
class String ALPHABET = ("A".."Z").to_a   def caesar_cipher(num) self.tr(ALPHABET.join, ALPHABET.rotate(num).join) end end   # demo encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5) decrypted = encrypted.caesar_cipher(-5)  
Give a code snippet in #Crystal Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z ...
christopher/rosetta-code
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#Delphi
Delphi
  program History_variables;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type THistoryVarType = record value: variant; timestamp: TDateTime; function ToString: string; end;   THistoryVar = record Fvalue: variant; FHistory: TArray<THistoryVarType>; private procedure SetValue(const Va...
Give a code snippet in #Delphi Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables a...
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...
#PL.2FI
PL/I
  dcl value fixed bin (31) init (0); do forever; value = value + 1;   if mod(value, 6) = 0 then leave;   put list (value); end;  
Give a code snippet in #PL.2FI 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/...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Go
Go
package main   import "fmt"   func main(){ fmt.Println(TimeStr(7259)) fmt.Println(TimeStr(86400)) fmt.Println(TimeStr(6000000)) }   func TimeStr(sec int)(res string){ wks, sec := sec / 604800,sec % 604800 ds, sec := sec / 86400, sec % 86400 hrs, sec := sec / 3600, sec % 3600 mins, sec := sec / 60, sec % 60 Comm...
Give a code snippet in #Go Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2...
christopher/rosetta-code
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Racket
Racket
#lang racket   (define has-left-wall? (lambda (x) (bitwise-bit-set? x 0))) (define has-right-wall? (lambda (x) (bitwise-bit-set? x 1))) (define has-top-wall? (lambda (x) (bitwise-bit-set? x 2))) (define has-bottom-wall? (lambda (x) (bitwise-bit-set? x 3))) (define has-fluid? (lambda (x) (bitwise-bit-set? x ...
Give a code snippet in #Racket Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean clu...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Oforth
Oforth
import: mapping   5 4 3 2 pow pow pow >string dup left( 20 ) . dup right( 20 ) . size .
Give a code snippet in #Oforth Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Factor
Factor
USING: arrays combinators.extras kernel math math.matrices.laplace math.vectors prettyprint sequences ;   : det ( pt pt -- x ) 2array determinant ;   : numerator ( x y pt pt quot -- z ) bi@ swapd [ 2array ] 2bi@ det ; inline   : intersection ( pt pt pt pt -- pt ) [ [ det ] 2bi@ ] [ [ v- ] 2bi@ ] 4bi [ [...
Give a code snippet in #Factor [1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
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...
#Raku
Raku
  # cert creation commands   # openssl req -newkey rsa:4096 -keyout my_key.pem -out my_csr.pem -nodes -subj "/CN=ME"   # openssl x509 -req -in my_csr.pem -signkey my_key.pem -out my_cert.pem   use v6; use OpenSSL;   my $host = "github.com";   my $ssl = OpenSSL.new(:client);   $ssl.use-certificate-file("./my_cert.pem");...
Give a code snippet in #Raku 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/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Fortran
Fortran
CHARACTER(10) :: intstr = "12345", realstr = "1234.5" INTEGER :: i REAL :: r   READ(intstr, "(I10)") i ! Read numeric string into integer i i = i + 1 ! increment i WRITE(intstr, "(I10)") i ! Write i back to string   READ(realstr, "(F10.1)") r r = r + 1.0 WRITE(realstr, "(F10.1)")...
Give a code snippet in #Fortran Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#Elena
Elena
import extensions; import system'routines; import extensions'text;   string text = "In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Cl...
Give a code snippet in #Elena Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or prov...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Racket
Racket
  #lang racket (require net/uri-codec) (uri-decode "http%3A%2F%2Ffoo%20bar%2F")  
Give a code snippet in #Racket This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory qw(factorial); use List::Util qw(max);   sub Lah { my($n, $k) = @_; return factorial($n) if $k == 1; return 1 if $k == $n; return 0 if $k > $n; return 0 if $k < 1 or $n < 1; (factorial($n) * factorial($n - 1)) / (factorial($k) * factorial(...
Give a code snippet in #Perl Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly o...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Delphi
Delphi
program MultiplicationTables;   {$APPTYPE CONSOLE}   uses SysUtils;   const MAX_COUNT = 12; var lRow, lCol: Integer; begin Write(' | '); for lRow := 1 to MAX_COUNT do Write(Format('%4d', [lRow])); Writeln(''); Writeln('--+-' + StringOfChar('-', MAX_COUNT * 4)); for lRow := 1 to MAX_COUNT do begin ...
Give a code snippet in #Delphi Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Yabasic
Yabasic
dim a(4, 2) a(0, 0) = 1 : a(0, 1) = 2 a(1, 0) = 3 : a(1, 1) = 4 a(2, 0) = 5 : a(2, 1) = 6 a(3, 0) = 7 : a(3, 1) = 8 dim b(2, 3) b(0, 0) = 1 : b(0, 1) = 2 : b(0, 2) = 3 b(1, 0) = 4 : b(1, 1) = 5 : b(1, 2) = 6 dim prod(arraysize(a(),1), arraysize(b(),2))   if (arraysize(a(),2) = arraysize(b(),1)) then for i = 0 to array...
Give a code snippet in #Yabasic Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_chain_multiplication
Matrix chain multiplication
Problem Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe...
#Racket
Racket
#lang racket   (define (memoize f) (define table (make-hash)) (λ args (hash-ref! table args (thunk (apply f args)))))   (struct $ (cost expl)) (define @ vector-ref)   (define (+: #:combine [combine (thunk* #f)] . xs) ($ (apply + (map $-cost xs)) (apply combine (map $-expl xs))))   (define (min: . xs) (argmin $-co...
Give a code snippet in #Racket Problem Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matr...
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...
#Maxima
Maxima
bottles(n) := for i from n thru 1 step -1 do ( printf(true, "~d bottle~p of beer on the wall~%", i, i), printf(true, "~d bottle~p of beer~%", i, i), printf(true, "Take one down, pass it around~%"), printf(true, "~d bottle~p of beer on the wall~%", i - 1, i - 1), disp(""))$   bottles(3); /*   3 bottles of beer...
Give a code snippet in #Maxima 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 9...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#NetRexx
NetRexx
/* NetRexx ************************************************************ * Test digroot **********************************************************************/ Say 'number -> digital_root persistence' test_digroot(7 ,7, 0) test_digroot(627615 ,9, 2) test_digroot(39390 ,6, 2) test_digroot(588225 ...
Give a code snippet in #NetRexx The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Nim
Nim
  # Prime conspiracy.   from algorithm import sorted from math import sqrt from sequtils import toSeq from strformat import fmt import tables   const N = 1_020_000_000.int # Size of sieve of Eratosthenes.   proc newSieve(): seq[bool] = ## Create a sieve with only odd values. ## Index "i" in sieve represents val...
Give a code snippet in #Nim A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preference...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#C.23
C#
namespace Search { using System;   public static partial class Extensions { /// <summary>Use Binary Search to find index of GLB for value</summary> /// <typeparam name="T">type of entries and value</typeparam> /// <param name="entries">array of entries</param> /// <param name="value">search value</p...
Give a code snippet in #C.23 A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret nu...
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...
#Klingphix
Klingphix
include ..\Utilitys.tlhy   %n 100 !n 0 $n repeat   $n [dup sqrt int dup * over == ( [1 swap set] [drop] ) if] for   $n [ ( "The door " over " is " ) lprint get ( ["OPEN"] ["closed"] ) if print nl] for   ( "Time elapsed: " msec " seconds" ) lprint nl   pstack " " input
Give a code snippet in #Klingphix 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/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Elena
Elena
move = (n,from,to,via) { if (n == 1) { console.printLine("Move disk from pole ",from," to pole ",to) } else { move(n-1,from,via,to); move(1,from,to,via); move(n-1,via,to,from) } };
Give a code snippet in #Elena Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#Fortran
Fortran
module Q_mod implicit none   type quaternion real :: a, b, c, d end type   public :: norm, neg, conj public :: operator (+) public :: operator (*)   private :: q_plus_q, q_plus_r, r_plus_q, & q_mult_q, q_mult_r, r_mult_q, & norm_q, neg_q, conj_q   interface norm modu...
Give a code snippet in #Fortran Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#Latitude
Latitude
Singleton ::= Object clone tap { self id := 0. self newID := { self id := self id + 1. }. self clone := { err ArgError clone tap { self message := "Singleton object!". } throw. }. }.   println: Singleton newID. ; 1 println: Singleton newID. ; 2 println: Singleton newID. ; 3
Give a code snippet in #Latitude A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Dart
Dart
class Delegator { var delegate;   String operation() { if (delegate == null) return "default implementation"; else return delegate.thing(); } }   class Delegate { String thing() => "delegate implementation"; }   main() { // Without a delegate: Delegator a = new Delegator(); Expect.equa...
Give a code snippet in #Dart A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Haskell
Haskell
import System.Random   data Pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Ord, Enum, Bounded, Eq, Show)   data Suit = Diamonds | Spades | Hearts | Clubs deriving (Ord, Enum, Bounded, Eq, Show)   type Card = (Pip, Suit)   fullRange :: (Bounded a...
Give a code snippet in #Haskell Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 ...
#True_BASIC
True BASIC
  !creamos la matriz y la inicializamos LET lim = 20 DIM array(20) FOR i = 1 TO lim LET array(i) = INT(RND * 100) + 1 NEXT i   SUB printArray (lim) FOR i = 1 TO lim  !PRINT USING("###", array(i)); PRINT array(i); " "; NEXT i PRINT END SUB   SUB heapify (count) LET start = INT(count / ...
Give a code snippet in #True_BASIC 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/Terminal_control/Cursor_positioning
Terminal control/Cursor positioning
Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
#Blast
Blast
# This will display a message at a specific position on the terminal screen .begin cursor 6,3 display "Hello!" return # This is the end of the script
Give a code snippet in #Blast Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
christopher/rosetta-code
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
TableCreation="CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL )"; Needs["DatabaseLink`"] conn=OpenSQLConnection[ JDBC[ "mysql","databases:1234/conn_test"], "Username" -> "test"] SQLExecute[ conn, Tab...
Give a code snippet in #Mathematica.2FWolfram_Language Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a f...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#Clojure
Clojure
(ns tanevaulator (:gen-class))   ;; Notation: [a b c] -> a x arctan(a/b) (def test-cases [ [[1, 1, 2], [1, 1, 3]], [[2, 1, 3], [1, 1, 7]], [[4, 1, 5], [-1, 1, 239]], [[5, 1, 7], [2, 3, 79]], ...
Give a code snippet in #Clojure Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Racket
Racket
  #lang racket (copy-port (current-input-port) (current-output-port))  
Give a code snippet in #Racket Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Kotlin
Kotlin
// version 1.1.2   data class Item(val name: String, val value: Double, val weight: Double, val volume: Double)   val items = listOf( Item("panacea", 3000.0, 0.3, 0.025), Item("ichor", 1800.0, 0.2, 0.015), Item("gold", 2500.0, 2.0, 0.002) )   val n = items.size val count = IntArray(n) val best = IntArray(n...
Give a code snippet in #Kotlin 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/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Icon_and_Unicon
Icon and Unicon
link graphics   procedure main(arglist)   WOpen("size=300, 300", "fg=blue", "bg=light gray") WDone() end
Give a code snippet in #Icon_and_Unicon Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#J
J
rom2d=: [: (+/ .* _1^ 0,~ 2</\ ]) 1 5 10 50 100 500 1000 {~ 'IVXLCDM'&i.
Give a code snippet in #J Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starti...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#Scala
Scala
class SEDOL(s: String) { require(s.size == 6 || s.size == 7, "SEDOL length must be 6 or 7 characters") require(s.size == 6 || s(6).asDigit == chksum, "Incorrect SEDOL checksum") require(s forall (c => !("aeiou" contains c.toLower)), "Vowels not allowed in SEDOL") def chksum = 10 - ((s zip List(1, 3, 1, 7, 3, 9)...
Give a code snippet in #Scala Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842...
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...
#Erlang
Erlang
-module(tok). -export([start/0]).   start() -> Lst = string:tokens("Hello,How,Are,You,Today",","), io:fwrite("~s~n", [string:join(Lst,".")]), ok.
Give a code snippet in #Erlang 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 r...
christopher/rosetta-code
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#C.2B.2B
C++
  #include <windows.h> #include <vector> #include <string>   using namespace std;   ////////////////////////////////////////////////////// struct Point { int x, y; };   ////////////////////////////////////////////////////// class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen...
Give a code snippet in #C.2B.2B A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
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
#Sidef
Sidef
try { die "I'm dead!"; # throws an exception of type 'error' } catch { |type, msg| say "type: #{type}"; # type: error say "msg: #{msg}"; # msg: I'm dead! at test.sf line 2. };   say "I'm alive..."; die "Now I'm dead!"; # this line terminates the program say "Or am I?"; # Y...
Give a code snippet in #Sidef 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#Pascal
Pascal
program BellNumbers; {$Ifdef FPC} {$optimization on,all} {$ElseIf} {Apptype console} {$EndIf} uses sysutils,gmp; var T0 :TDateTime; procedure BellNumbersUint64(OnlyBellNumbers:Boolean); var BList : array[0..24] of Uint64; BellNum : Uint64; BListLenght,i :nativeUInt; begin IF OnlyBellNUmbers then Begin...
Give a code snippet in #Pascal Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Futhark
Futhark
  fun main(n: int): [n]int = loop (a = replicate n 0) = for i < n do (loop (s = 0) = for j < i+1 do s + j let a[i] = s in a) in a  
Give a code snippet in #Futhark “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract struc...
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...
#Suneido
Suneido
val = 0 do { Print(++val) } while (val % 6 isnt 0)
Give a code snippet in #Suneido 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#OoRexx
OoRexx
/*REXX pgm shows: hour, sun hour angle, dial hour line angle, 6am ---> 6pm*/ /* Use trigonometric functions provided by rxCalc */ parse arg lat lng mer . /*get the optional arguments from the CL*/ /*None specified? Then use the default of Jules ...
Give a code snippet in #OoRexx Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Islan...
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...
#Falcon
Falcon
  /* created by Aykayayciti Earl Lamont Montgomery April 9th, 2018 */   a = [] a = strSplit("Hello,How,Are,You,Today", ",") index = 0 start = 0 b = "" for index in [ start : len(a)-1 : 1 ] b = b + a[i] + "." end   > b  
Give a code snippet in #Falcon 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 r...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Icon_and_Unicon
Icon and Unicon
invocable all procedure main()   d := 30 # degrees r := dtor(d) # convert to radians   every write(f := !["sin","cos","tan"],"(",r,")=",y := f(r)," ",fi := "a" || f,"(",y,")=",x := fi(y)," rad = ",rtod(x)," deg") end
Give a code snippet in #Icon_and_Unicon Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments ...
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...
#AutoHotkey
AutoHotkey
msgbox % first := evalWithX("x + 4", 5) msgbox % second := evalWithX("x + 4", 6) msgbox % second - first return   evalWithX(expression, xvalue) { global script script = ( expression(){ x = %xvalue% ; := would need quotes return %expression% } ) renameFunction("expression", "") ; remove any previous exp...
Give a code snippet in #AutoHotkey 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 example...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Lasso
Lasso
define br => '<br />\n'   define sumdigits(int, base = 10) => { fail_if(#base < 2, -1, 'Base need to be at least 2') local( out = integer, divmod ) while(#int) => { #divmod = #int -> div(#base) #int = #divmod -> first #out += #divmod -> second } return #out }   sumdigits(1) br sumdigits(12345) br su...
Give a code snippet in #Lasso Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Perl
Perl
perl -n -e '/(\S+)\s*$/ and $1 > 6 and print' data.txt
Give a code snippet in #Perl Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines f...
christopher/rosetta-code
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function shou...
#Delphi
Delphi
  program Secure_temporary_file;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.IOUtils;   var FileName, buf: string;   begin FileName := TPath.GetTempFileName; with TFile.Open(FileName, TFileMode.fmCreate, TFileAccess.faReadWrite, Tfileshare.fsNone) do begin buf := 'This is a exclusive temp fi...
Give a code snippet in #Delphi Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race condition...
christopher/rosetta-code
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d ...
#XPL0
XPL0
func real Noise; real X, Y, Z; real U, V, W; int IX, IY, IZ, P(512), A, AA, AB, B, BA, BB;   func real Fade; real T; return T*T*T * (T*(T*6.-15.) + 10.);   func real Lerp; real T, A, B; return A + T*(B-A);   func real Grad; int Hash; real X, Y, Z; int H; real U, V; [H:= Hash & $0F; ...
Give a code snippet in #XPL0 The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#REBOL
REBOL
print ["Original: " original: "alphaBETA"] print ["Uppercase:" uppercase original] print ["Lowercase:" lowercase original]
Give a code snippet in #REBOL Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not r...
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   robject = Rexx -- create an object for which the value is undefined say String.valueOf(robject) -- will report the text "null" if robject = null then say 'Really, it''s "null"!'  
Give a code snippet in #NetRexx 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 lan...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: bestShuffle (in string: stri) is func result var string: shuffled is ""; local var char: tmp is ' '; var integer: i is 0; var integer: j is 0; begin shuffled := stri; for key i range shuffled do for key j range shuffled do if i <...
Give a code snippet in #Seed7 Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time ...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Elm
Elm
module Main exposing ( main )   import Html exposing ( Html, text )   -- As with most of the strict (non-deferred or non-lazy) languages, -- this is the Z-combinator with the additional value parameter...   -- wrap type conversion to avoid recursive type definition... type Mu a b = Roll (Mu a b -> a -> b)   unroll : Mu...
Give a code snippet in #Elm In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a vari...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Lua
Lua
print( os.getenv( "PATH" ) )
Give a code snippet in #Lua Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Perl
Perl
package Vector; use Moose; use feature 'say';   use overload '+' => \&add, '-' => \&sub, '*' => \&mul, '/' => \&div, '""' => \&stringify;   has 'x' => (is =>'rw', isa => 'Num', required => 1); has 'y' => (is =>'rw', isa => 'Num', required => 1);   sub add { my($a, $...
Give a code snippet in #Perl 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/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Run_BASIC
Run BASIC
'Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007". print date$("yyyy-mm-dd") print date$("dddd");", "; 'return full day of the week (eg. Wednesday print date$("mmmm");" "; 'return full month name (eg. March) print date$("dd, yyyy") ...
Give a code snippet in #Run_BASIC This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#Io
Io
rms := method (figs, (figs map(** 2) reduce(+) / figs size) sqrt)   rms( Range 1 to(10) asList ) println
Give a code snippet in #Io Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Racket
Racket
  #lang racket (require racket/draw)   (define (read-ppm port) (parameterize ([current-input-port port]) (define magic (read)) (define width (read)) (define height (read)) (define maxcol (read)) (define bm (make-object bitmap% width height)) (define dc (new bitmap-dc% [bitmap bm])) (send d...
Give a code snippet in #Racket Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grays...
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...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_XOR is type Person is (John, Bob, Mary, Serena, Jim); type Group is array (Person) of Boolean; procedure Put (Set : Group) is First : Boolean := True; begin for I in Set'Range loop if Set (I) then if First then ...
Give a code snippet in #Ada 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 ) {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Standard_ML
Standard ML
fun comb (0, _ ) = [[]] | comb (_, [] ) = [] | comb (m, x::xs) = map (fn y => x :: y) (comb (m-1, xs)) @ comb (m, xs) ; comb (3, [0,1,2,3,4]);
Give a code snippet in #Standard_ML Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case...
#EchoLisp
EchoLisp
  (define dim 250)   ;; speed up n^5 (define (p5 n) (* n n n n n)) (remember 'p5) ;; memoize   ;; build vector of all y^5 - x^5 diffs - length 30877 (define all-y^5-x^5 (for*/vector [(x (in-range 1 dim)) (y (in-range (1+ x) dim))] (- (p5 y) (p5 x))))   ;; sort to use vector-search (begin (vector-sort! < all...
Give a code snippet in #EchoLisp There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth powe...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 ...
#Wren
Wren
var beadSort = Fn.new { |a| var res = [] var max = a.reduce { |acc, i| (i > acc) ? i : acc } var trans = [0] * max for (i in a) { for (n in 0...i) trans[n] = trans[n] + 1 } for (i in a) { res.add(trans.count { |n| n > 0 }) for (n in 0...trans.count) trans[n] = trans[n] - ...
Give a code snippet in #Wren 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/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#Standard_ML
Standard ML
(* * val mkHtmlTable : ('a list * 'b list) -> ('a -> string * 'b -> string) * -> (('a * 'b) -> string) -> string * The int list is list of colums, the function returns the values * at a given colum and row. * returns the HTML code of the generated table. *) fun mkHtmlTable (columns, rows) (rowToStr, colToStr)...
Give a code snippet in #Standard_ML Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is fill...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always ...
#REXX
REXX
/*REXX program solves a Numbrix (R) puzzle, it also displays the puzzle and solution. */ maxR=0; maxC=0; maxX=0; minR=9e9; minC=9e9; minX=9e9; cells=0; @.= parse arg xxx; PZ='Hidato puzzle' /*get the cell definitions from the CL.*/ xxx=translate(xxx, , "/\;:_", ',') ...
Give a code snippet in #REXX The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connect...
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...
#PHP
PHP
<?php $a = array(); array_push($a, 0);   $used = array(); array_push($used, 0);   $used1000 = array(); array_push($used1000, 0);   $foundDup = false; $n = 1;   while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $already...
Give a code snippet in #PHP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#PHP
PHP
<?php $a = '2988348162058574136915891421498819466320163312926952423791023078876139'; $b = '2351399303373464486466122544523690094744975233415544072992656881240319'; $m = '1' . str_repeat('0', 40); echo bcpowmod($a, $b, $m), "\n";
Give a code snippet in #PHP Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373464...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#REXX
REXX
/*REXX program illustrates building a simple inverted index and a method of word find.*/ @.= /*a dictionary of words (so far). */ != /*a list of found words (so far). */ call invertI 0, 'BURMA0.TXT' ...
Give a code snippet in #REXX An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / ter...
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...
#Scheme
Scheme
  (import (scheme base) (scheme inexact) (scheme write))   ;; c1 and c2 are pairs (x y), r a positive radius (define (find-circles c1 c2 r) (define x-coord car) ; for easier to read coordinate extraction from list (define y-coord cadr) (define (approx= a b) (< (- a b) 0.000001)) ; equal within tol...
Give a code snippet in #Scheme Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number o...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Modula-2
Modula-2
MODULE Harshad; FROM InOut IMPORT WriteString, WriteCard, WriteLn;   VAR n, i: CARDINAL;   PROCEDURE DigitSum(n: CARDINAL): CARDINAL; VAR sum: CARDINAL; BEGIN sum := 0; WHILE n > 0 DO; sum := sum + n MOD 10; n := n DIV 10; END; RETURN sum; END DigitSum;   PROCEDURE NextHarshad(n: CARDINA...
Give a code snippet in #Modula-2 The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#D
D
class LinkedQueue(T) { private static struct Node { T data; Node* next; }   private Node* head, tail;   bool empty() { return head is null; }   void push(T item) { if (empty()) head = tail = new Node(item); else { tail.next = new Node(item); ...
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues,...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#C.23
C#
using System; //4790@3.6 class Program { static void Main() { Console.WriteLine(knapSack(15) + "\n"); var sw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 1000; i > 0; i--) knapSack(15); Console.Write(sw.Elapsed); Console.Read(); // 0.60 µs }   static string...
Give a code snippet in #C.23 A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Phix
Phix
-- demo\rosetta\Bitmap_Greyscale.exw (runnable version)   function to_grey(sequence image) integer dimx = length(image), dimy = length(image[1]) for x=1 to dimx do for y=1 to dimy do integer pixel = image[x][y] -- red,green,blue sequence r_g_b = sq_and_bit...
Give a code snippet in #Phix Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#8086_Assembly
8086 Assembly
.model small .stack 1024 .data ; data segment begins here UserRam byte 256 dup (0) ; the next 256 bytes have a value of zero. The address of the 0th of these bytes can be referenced as "UserRam"   tempByte equ UserRam ;this variable's address is the same as that of the 0th byte of UserRam tempWor...
Give a code snippet in #8086_Assembly Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Ope...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Emacs_Lisp
Emacs Lisp
(dotimes (i most-positive-fixnum) (message "%d" (1+ i)))
Give a code snippet in #Emacs_Lisp Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementatio...
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...
#Ring
Ring
  for i = 0 to 10 step 2 see i + nl next  
Give a code snippet in #Ring 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/Incr...
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...
#Yabasic
Yabasic
roman$ = "M, CM, D, CD, C, XC, L, XL, X, IX, V, IV, I" decml$ = "1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1"   sub toRoman$(value) local res$, i, roman$(1), decml$(1), long   long = token(roman$, roman$(), ", ") long = token(decml$, decml$(), ", ")   for i=1 to long while(value ...
Give a code snippet in #Yabasic 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 v...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program functMul.s */ /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1   /***********************/ /* Initialized data */ /***********************/ .data szRetourLigne: .asciz "\n" szMessResult: .ascii "Resultat : " @ message result sMessValeur: .fill 12,...
Give a code snippet in #ARM_Assembly A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to di...
christopher/rosetta-code
http://rosettacode.org/wiki/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: ...
#C
C
  #include<string.h> #include<stdlib.h> #include<ctype.h> #include<stdio.h>   #define UNITS_LENGTH 13   int main(int argC,char* argV[]) { int i,reference; char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"}; double fact...
Give a code snippet in #C Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and retu...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#REXX
REXX
/*REXX program generates a chess position (random pieces & positions) in a FEN format.*/ parse arg seed CBs . /*obtain optional arguments from the CL*/ if datatype(seed,'W') then call random ,,seed /*SEED given for RANDOM repeatability? */ if CBs=='' | CBs=="," then CBs=1 ...
Give a code snippet in #REXX Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent sq...
christopher/rosetta-code
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#C.2B.2B
C++
#include <stdexcept>   class tiny_int { public: tiny_int(int i): value(i) { if (value < 1) throw std::out_of_range("tiny_int: value smaller than 1"); if (value > 10) throw std::out_of_range("tiny_int: value larger than 10"); } operator int() const { return value; } tiny_int& op...
Give a code snippet in #C.2B.2B Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#BASIC
BASIC
DECLARE SUB show (pattern AS STRING)   show "*.*"   SUB show (pattern AS STRING) DIM f AS STRING f = DIR$(pattern) DO WHILE LEN(f) PRINT f f = DIR$ LOOP END SUB
Give a code snippet in #BASIC Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#PicoLisp
PicoLisp
(let Str1 "First text" (prinl Str1 " literal") (let Str2 (pack Str1 " literal") (prinl Str2) ) )
Give a code snippet in #PicoLisp String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string ...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Sidef
Sidef
foo(); # without arguments foo(1, 2); # with two arguments foo(args...); # with a variable number of arguments foo(name: 'Bar', age: 42); # with named arguments   var f = foo; # store the function foo inside 'f' var result = f(); # obta...
Give a code snippet in #Sidef Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a va...
christopher/rosetta-code
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 ...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program condstr.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szMessTest1: .asciz "The test 1 is equal.\n" szMessTest1N: .asciz "The test 1 is not equal.\n...
Give a code snippet in #ARM_Assembly 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#Standard_ML
Standard ML
(*------------------------------------------------------------------*) (* The Rosetta Code lexical analyzer, in Standard ML. Based on the ATS and the OCaml. The intended compiler is Mlton or Poly/ML; there is a tiny difference near the end of the file, depending on which compiler is used. *)   (*--------------...
Give a code snippet in #Standard_ML Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer...
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 ...
#VBA
VBA
Option Base 1 Function levenshtein(s1 As String, s2 As String) As Integer Dim n As Integer: n = Len(s1) + 1 Dim m As Integer: m = Len(s2) + 1 Dim d() As Integer, i As Integer, j As Integer ReDim d(n, m)   If n = 1 Then levenshtein = m - 1 Exit Function Else If m = 1 Then ...
Give a code snippet in #VBA 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 compu...
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.
#Scheme
Scheme
(load "srfi-54.scm") (load "srfi-54.scm") ;; Don't ask.   (define x 295643087.65432)   (dotimes (i 4) (print (cat x 25 3.0 #\0 (list #\, (- 4 i)))))  
Give a code snippet in #Scheme 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/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash mapfile -t name <<EOF Aimhacks EOF   main() { banner3d_1 "${name[@]}" echo banner3d_2 "${name[@]}" echo banner3d_3 "${name[@]}" }   space() { local -i n i (( n=$1 )) || n=1 if (( n < 1 )); then n=1; fi for ((i=0; i<n; ++i)); do printf ' ' done printf '\n' }   banner3d_1() {...
Give a code snippet in #UNIX_Shell Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#Tcl
Tcl
foreach d0 {1 2 3 4 5 6} { foreach d1 {1 2 3 4 5 6} { ... foreach dN {1 2 3 4 5 6} { dict incr sum [::tcl::mathop::+ $n $d0 $d1 ... $DN] } ... } }
Give a code snippet in #Tcl Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player w...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome 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 ...
#PowerBASIC
PowerBASIC
SUB gnomeSort (a() AS LONG) DIM i AS LONG, j AS LONG i = 1 j = 2 WHILE (i < UBOUND(a) + 1) IF (a(i - 1) <= a(i)) THEN i = j INCR j ELSE SWAP a(i - 1), a(i) DECR i IF 0 = i THEN i = j INCR j ...
Give a code snippet in #PowerBASIC 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/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#AutoHotkey
AutoHotkey
factorize(n){ if n = 1 return 1 if n < 1 return false result := 0, m := n, k := 2 While n >= k{ while !Mod(m, k){ result .= " * " . k, m /= k } k++ } return SubStr(result, 5) } Loop 22 out .= A_Index ": " factorize(A_index) "`n" MsgBox % out
Give a code snippet in #AutoHotkey Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it ...
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...
#ALGOL_68
ALGOL 68
  BEGIN print ((program idf, newline)) END  
Give a code snippet in #ALGOL_68 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 scri...
christopher/rosetta-code
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Phix
Phix
constant maxIt = 13, maxItJ = 10 atom a1 = 1.0, a2 = 0.0, d1 = 3.2 puts(1," i d\n") for i=2 to maxIt do atom a = a1 + (a1 - a2) / d1 for j=1 to maxItJ do atom x = 0, y = 0 for k=1 to power(2,i) do y = 1 - 2*y*x x = a - x*x end for ...
Give a code snippet in #Phix Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Frink
Frink
  a = new set[1,2,3,4] a.subsets[]  
Give a code snippet in #Frink A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given...
christopher/rosetta-code
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#Common_Lisp
Common Lisp
#!/bin/sh #|-*- mode:lisp -*-|# #| exec ros -Q -- $0 "$@" |# (progn ;;init forms (ros:ensure-asdf) #+quicklisp(ql:quickload '() :silent t) )   (defpackage :ros.script.floyd-warshall.3861181636 (:use :cl)) (in-package :ros.script.floyd-warshall.3861181636)   ;;; ;;; Floyd-Warshall algorithm. ;;; ;;; See https://...
Give a code snippet in #Common_Lisp The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has alre...
christopher/rosetta-code