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/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#CLU
CLU
% This program uses the 'bigint' cluster from % the 'misc.lib' included with PCLU.   isqrt = proc (s: int) returns (int) x0: int := s/2 if x0=0 then return(s) end x1: int := (x0 + s/x0)/2 while x1 < x0 do x0 := x1 x1 := (x0 + s/x0)/2 end return(x0) end isqrt   sieve = proc (n: in...
Give a code snippet in #CLU Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primori...
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Pascal
Pascal
program ConcurrentComputing; {$IFdef FPC} {$MODE DELPHI} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses {$IFDEF UNIX} cthreads, {$ENDIF} SysUtils, Classes;   type TRandomThread = class(TThread) private FString: string; T0 : Uint64; protected procedure Execute; override; public constructo...
Give a code snippet in #Pascal Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Euphoria
Euphoria
  include std/console.e include std/mathcons.e   atom lat = prompt_number("Enter Latitude: ",{}) atom lng = prompt_number("Enter Longitude: ",{}) atom lm = prompt_number("Enter Legal Meridian: ",{}) puts(1,'\n')   atom ha, hla   function D2R(atom degrees) return degrees * PI / 180 end function   function R2D(atom radi...
Give a code snippet in #Euphoria 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 Isl...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#Fortran
Fortran
MODULE LAIROTCAF !Calculates "left factorials". CONTAINS !The usual suspects. INTEGER*8 FUNCTION FACT(N) !Factorial, the ordinary. INTEGER N !The number won't ever get far. INTEGER I !The stepper. FACT = 1 !Here we go. DO I = 2,N !Does nothing for N < 2. ...
Give a code snippet in #Fortran Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n...
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.
#Kotlin
Kotlin
// version 1.1.2   object Singleton { fun speak() = println("I am a singleton") }   fun main(args: Array<String>) { Singleton.speak() }
Give a code snippet in #Kotlin 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/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#zkl
zkl
const games=0d100_000;   reg switcherWins=0, keeperWins=0, shown=0; do(games){ doors := L(0,0,0); doors[(0).random(3)] = 1; // Set which one has the car choice := (0).random(3); // Choose a door while(1){ shown = (0).random(3); if (not (shown == choice or doors[shown] == 1)) break; } switcherWins...
Give a code snippet in #zkl Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the t...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Java
Java
import java.math.BigInteger; import java.util.List;   public class Brazilian { private static final List<Integer> primeList = List.of( 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 1...
Give a code snippet in #Java Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits ...
#Ruby
Ruby
def crunch(ascii) bitstring = ascii.bytes.collect {|b| "%07b" % b}.join [bitstring].pack("B*") end   def expand(binary) bitstring = binary.unpack("B*")[0] bitstring.scan(/[01]{7}/).collect {|b| b.to_i(2).chr}.join end   original = "This is an ascii string that will be crunched, written, read and expanded." puts...
Give a code snippet in #Ruby The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the ou...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Scheme
Scheme
  (define-syntax sum (syntax-rules () ((sum var low high . body) (let loop ((var low) (result 0)) (if (> var high) result (loop (+ var 1) (+ result . body)))))))  
Give a code snippet in #Scheme Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the AL...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#M2000_Interpreter
M2000 Interpreter
  Module Tic.Tac.Toe { Dim Board$(1 to 3, 1 to 3)=" " WinGame=False p=Board$() RandomPosition=lambda -> { =(random(1,3), random(1,3)) }   BoardItemEmpty=Lambda p (x, y) -> { =Array$(p, x, y)=" " } BoardSetItem=Lambda p (x, y, w$) -> { l...
Give a code snippet in #M2000_Interpreter Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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
import "timer" for Timer import "io" for Stdout import "os" for Process   var args = Process.arguments var n = args.count if (n < 2) Fiber.abort("There must be at least two arguments passed.") var list = args.map{ |a| Num.fromString(a) }.toList if (list.any { |i| i == null || !i.isInteger || i < 0 } ) { Fiber.abort...
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/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming langua...
#Lua
Lua
#!/usr/bin/env luajit bit32=bit32 or bit local lib={ hailstone=function(n) local seq={n} while n>1 do n=bit32.band(n,1)==1 and 3*n+1 or n/2 seq[#seq+1]=n end return seq end }   if arg[0] and arg[0]:match("hailstone.lua") then local function printf(fmt, ...) io.write(string.format(fmt, ...)) end local...
Give a code snippet in #Lua The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#Clojure
Clojure
(defn mean-fn [k coll] (let [n (count coll) trig (get {:sin #(Math/sin %) :cos #(Math/cos %)} k)] (* (/ 1 n) (reduce + (map trig coll)))))   (defn mean-angle [degrees] (let [radians (map #(Math/toRadians %) degrees) a (mean-fn :sin radians) b (mean-fn :cos radians)] (Math/toDegre...
Give a code snippet in #Clojure When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first re...
christopher/rosetta-code
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Ruby
Ruby
require "bigdecimal"   LN2 = BigMath::log(2,16) #Use LN2 = Math::log(2) to see the difference with floats FACTORIALS = Hash.new{|h,k| h[k] = k * h[k-1]} FACTORIALS[0] = 1   def hickerson(n) FACTORIALS[n] / (2 * LN2 ** (n+1)) end   def nearly_int?(n) int = n.round n.between?(int - 0.1, int + 0.1) end   1.upto(17)...
Give a code snippet in #Ruby The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle ...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const pi As Double = 3.141592653589793 Randomize   ' Generates normally distributed random numbers with mean 0 and standard deviation 1 Function randomNormal() As Double Return Cos(2.0 * pi * Rnd) * Sqr(-2.0 * Log(Rnd)) End Function   Sub normalStats(sampleSize As Integer) If sampleSize < 1 The...
Give a code snippet in #FreeBASIC The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform ra...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Ada
Ada
  3.141_592_6 1.0E-12 0.13  
Give a code snippet in #Ada Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/AB...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Z80_Assembly
Z80 Assembly
;assumes this runs inline org &1000 ;program start main: call GetInput ;unimplemented input get routine, returns key press in accumulator cp 'Y' ;compare to ascii capital Y ret z ;return to BASIC if equal jp main ;loop back to main
Give a code snippet in #Z80_Assembly Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object fin...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Agena
Agena
 
Give a code snippet in #Agena Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#Applesoft_BASIC
Applesoft BASIC
  PR#1 PRINT "HELLO WORLD!"  
Give a code snippet in #Applesoft_BASIC Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#D
D
import kxml.xml; char[]xmlinput = "<Students> <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" /> <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" /> <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" /> <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\"> ...
Give a code snippet in #D Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" ...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#APL
APL
fpg←{⎕IO←0 ⍺←4 4 (s∨.<0)∨2≠⍴s←⍺:'invalid shape:'s 0≠⍴⍴⍵:'invalid shuffle count:'⍵ d←d,-d←↓2 2⍴3↑1 e←¯1+⍴c←'↑↓←→○' b←w←s⍴w←1⌽⍳×/s z←⊃{ z p←⍵ n←(?⍴p)⊃p←(p≡¨(⊂s)|p)/p←(d~p)+⊂z b[z n]←b[n z] -⍨\n z }⍣⍵⊢(s-1)0 ⎕←b ⍬{ b≡w:'win' 0=⍴⍺:⍞∇ ⍵ ...
Give a code snippet in #APL Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Lcm_Test is function Gcd (A, B : Integer) return Integer is M : Integer := A; N : Integer := B; T : Integer; begin while N /= 0 loop T := M; M := N; N := T mod N; end loop; return M; end Gcd;   func...
Give a code snippet in #Ada Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has b...
christopher/rosetta-code
http://rosettacode.org/wiki/The_ISAAC_Cipher
The ISAAC Cipher
ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming...
#Raku
Raku
my uint32 (@mm, @randrsl, $randcnt, $aa, $bb, $cc); my \ϕ := 2654435769; constant MOD = 95; constant START = 32;   constant MAXINT = uint.Range.max; enum CipherMode < ENCIPHER DECIPHER NONE >;   sub mix (\n) { sub mix1 (\i, \v) { n[i] +^= v; n[(i+3)%8] += n[i]; n[(i+1)%8] += n[(i+2)%8]; } ...
Give a code snippet in #Raku ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architect...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Standard_ML
Standard ML
val stdoutRefersToTerminal : bool = Posix.ProcEnv.isatty Posix.FileSys.stdout
Give a code snippet in #Standard_ML Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor
Terminal control/Hiding the cursor
The task is to hide the cursor and show it again.
#Nemerle
Nemerle
using System.Console; using System.Threading.Thread;   module CursorVisibility { Main() : void { repeat(3) { CursorVisible = !CursorVisible; Sleep(5000); } } }
Give a code snippet in #Nemerle The task is to hide the cursor and show it again.
christopher/rosetta-code
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#Java
Java
  public class StrongAndWeakPrimes {   private static int MAX = 10_000_000 + 1000; private static boolean[] primes = new boolean[MAX];   public static void main(String[] args) { sieve(); System.out.println("First 36 strong primes:"); displayStrongPrimes(36); for ( int...
Give a code snippet in #Java Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p...
christopher/rosetta-code
http://rosettacode.org/wiki/Odd_word_problem
Odd word problem
Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one punctuation, the stream will...
#Ada
Ada
with Ada.Text_IO;   procedure Odd_Word_Problem is   use Ada.Text_IO; -- Get, Put, and Look_Ahead   function Current return Character is -- reads the current input character, without consuming it End_Of_Line: Boolean; C: Character; begin Look_Ahead(C, End_Of_Line); if End_Of_Line t...
Give a code snippet in #Ada Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one ...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#PicoLisp
PicoLisp
(de dotProduct (A B) (sum * A B) )   (de crossProduct (A B) (list (- (* (cadr A) (caddr B)) (* (caddr A) (cadr B))) (- (* (caddr A) (car B)) (* (car A) (caddr B))) (- (* (car A) (cadr B)) (* (cadr A) (car B))) ) )   (de scalarTriple (A B C) (dotProduct A (crossProduct B C)) )   (de vectorTrip...
Give a code snippet in #PicoLisp A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of...
christopher/rosetta-code
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#CoffeeScript
CoffeeScript
Point = (@x,@y) ->   pointInPoly = (point,poly) -> segments = for pointA, index in poly pointB = poly[(index + 1) % poly.length] [pointA,pointB] intesected = (segment for segment in segments when rayIntesectsSegment(point,segment)) intesected.length % 2 != 0   rayInte...
Give a code snippet in #CoffeeScript This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygo...
christopher/rosetta-code
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#Python
Python
#!/usr/bin/env python3   import curses from random import randrange, choice # generate and place new tile from collections import defaultdict   letter_codes = [ord(ch) for ch in 'WASDRQwasdrq'] actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit'] actions_dict = dict(zip(letter_codes, actions * 2))   def get_use...
Give a code snippet in #Python Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Objective-C
Objective-C
@interface NSString (RosettaCodeAddition) - (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times; @end   @implementation NSString (RosettaCodeAddition) - (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times { return [@"" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0];...
Give a code snippet in #Objective-C Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*...
christopher/rosetta-code
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Java
Java
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone;   public class NauticalBell extends Thread {   public static void main(String[] args) { NauticalBell bells = new NauticalBell(); bells.setDaemon(true); bells.start(); try { bells.jo...
Give a code snippet in #Java Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in...
#C.23
C#
using Mpir.NET; // 0.4.0 using System; // 4790@3.6 using System.Collections.Generic; class MaxLftTrP_B { static void Main() { mpz_t p; var sw = System.Diagnostics.Stopwatch.StartNew(); L(3); for (uint b = 3; b < 13; b++) { sw.Restart(); p = L(b); Console.Wri...
Give a code snippet in #C.23 A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 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) .
#AWK
AWK
  # syntax: GAWK -f FIND_THE_INTERSECTION_OF_TWO_LINES.AWK # converted from Ring BEGIN { intersect(4,0,6,10,0,3,10,7) exit(0) } function intersect(xa,ya,xb,yb,xc,yc,xd,yd, errors,x,y) { printf("the 1st line passes through (%g,%g) and (%g,%g)\n",xa,ya,xb,yb) printf("the 2nd line passes through (%g,%g) a...
Give a code snippet in #AWK [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/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...
#Scala
Scala
import scala.collection.mutable   object RecamansSequence extends App { val (a, used) = (mutable.ArrayBuffer[Int](0), mutable.BitSet()) var (foundDup, hop, nUsed1000) = (false, 1, 0)   while (nUsed1000 < 1000) { val _next = a(hop - 1) - hop val next = if (_next < 1 || used.contains(_next)) _next + 2 * hop...
Give a code snippet in #Scala 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. Ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
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 |...
#QB64
QB64
  Dim Words(1 To 4) As String Dim Lengths As Integer, Index As Integer, Position As Integer, Done As String, Index2 As Integer ' inititialization Words(1) = "abcd" Words(2) = "123456789" Words(3) = "abcdef" Words(4) = "1234567"   Print " Word Length" For Index2 = 1 To 4 Step 1 Lengths = 0 Position = 0 ...
Give a code snippet in #QB64 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#GAP
GAP
# Built-in Factorial(5);   # An implementation fact := n -> Product([1 .. n]);
Give a code snippet in #GAP Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a num...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#JavaScript
JavaScript
var DRAGON = (function () { // MATRIX MATH // -----------   var matrix = { mult: function ( m, v ) { return [ m[0][0] * v[0] + m[0][1] * v[1], m[1][0] * v[0] + m[1][1] * v[1] ]; },   minus: function ( a, b ) { return [ a[0]-b[0], a[1]-b[1] ]; },   ...
Give a code snippet in #JavaScript Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon follow...
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.
#Prolog
Prolog
:- dynamic pt/6. voronoi :- V is random(20) + 20, retractall(pt(_,_,_,_)), forall(between(1, V, I), ( X is random(390) + 5, Y is random(390) + 5, R is random(65535), G is random(65535), B is random(65535), assertz(pt(I,X,Y, R, G, B)) )), voronoi(manhattan, V), voronoi(euclide,...
Give a code snippet in #Prolog 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/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Swift
Swift
import Cocoa   var found = false let fh = NSFileHandle.fileHandleWithStandardInput() println("Enter an integer between 1 and 100 for me to guess: ") let data = fh.availableData var num:Int! var low = 0.0 var high = 100.0 var lastGuess:Double!     if let numFromData = NSString(data: data, encoding: NSUTF8StringEncoding)...
Give a code snippet in #Swift Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Octave
Octave
r = gcd(a, b)
Give a code snippet in #Octave Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greates...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_literals,_with_continuations
Long literals, with continuations
This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). The literal is to be in the form ...
#jq
jq
# FOR FUTURE EDITORS: # To add chemical elements, modify the CHEMICAL_ELEMENTS function, # ensuring that the date is updated properly and that there is at least one # space between the element names after concatenation of the strings. # Do not include any of the "unnamed" chemical element names such as ununennium.   de...
Give a code snippet in #jq This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). The l...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game/Player
Pig the dice game/Player
Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strategies involved. Show play dur...
#AutoHotkey
AutoHotkey
#NoEnv SetBatchLines, -1 #SingleInstance, Force #Include Pig_the_dice_game_Optimal_Play.ahkl ; comment if you don't want to bother Play:=10000 ; this is enough to give 2 digits of accuracy in win ratio Wins0:=Wins1:=0 Player0(TurnSum, SumMe, SumOpp) { Return practical(TurnSum, SumMe, SumOpp) ; set first player functio...
Give a code snippet in #AutoHotkey Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Delphi
Delphi
function Random : Extended; function Random ( LimitPlusOne  : Integer ) : Integer; procedure Randomize;
Give a code snippet in #Delphi The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorit...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#VBScript
VBScript
  Function LeftTrim(s) Set regex = New RegExp With regex .Pattern = "^\s*" If .Test(s) Then LeftTrim = .Replace(s,"") Else LeftTrim = s End If End With End Function   Function RightTrim(s) Set regex = New RegExp With regex .Pattern = "\s*$" If .Test(s) Then RightTrim = .Replace(s,"") Else ...
Give a code snippet in #VBScript Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Forth
Forth
s" VARIABLE " pad swap move ." Variable name: " pad 9 + 80 accept pad swap 9 + evaluate
Give a code snippet in #Forth Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Simulate_input/Keyboard
Simulate input/Keyboard
Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
#VBScript
VBScript
Dim WshShell Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.SendKeys "{Down}{F2}" WScript.Sleep 1000 ' one-second delay WshShell.SendKeys "{Left}{Left}{BkSp}{BkSp}Some text here.~" ' ~ -> Enter
Give a code snippet in #VBScript Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Arturo
Arturo
; creation x: "this is a string" y: "this is another string" z: "this is a string"   ; comparison if x = z -> print "x is z"   ; assignment z: "now this is another string too"   ; copying reference y: z   ; copying value y: new z   ; check if empty if? empty? x -> print "empty" else -> print "not empty"   ; ap...
Give a code snippet in #Arturo Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings acco...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}   Randomize Dim randInt As Integer   For i As Integer = 1 To 5 randInt = Int(Rnd * 10) Print a(randInt) Next Sleep
Give a code snippet in #FreeBASIC Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Oz
Oz
%% concatenating 2 lists {Append [a b] [c d]} = [a b c d]   %% concatenating 2 tuples {Tuple.append t(1 2 3) u(4 5 6)} = u(1 2 3 4 5 6)
Give a code snippet in #Oz Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#AutoIt
AutoIt
  #include <Array.au3> $Array = ZigZag(5) _ArrayDisplay($Array)   Func ZigZag($int) Local $av_array[$int][$int] Local $x = 1, $y = 1 For $I = 0 To $int ^ 2 -1 $av_array[$x-1][$y-1] = $I If Mod(($x + $y), 2) = 0 Then ;Even if ($y < $int) Then $y += 1 Else $x += 2 EndIf if ($x > 1) Then $x -= 1...
Give a code snippet in #AutoIt Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to en...
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...
#Yabasic
Yabasic
i = 1   repeat print i i = i + 1 until i = 0 end
Give a code snippet in #Yabasic 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Pascal
Pascal
Program n_th;   function Suffix(N: NativeInt):AnsiString; var res: AnsiString; begin res:= 'th'; case N mod 10 of 1:IF N mod 100 <> 11 then res:= 'st'; 2:IF N mod 100 <> 12 then res:= 'nd'; 3:IF N mod 100 <> 13 then res:= 'rd'; else end; Suffix := res; end;   procedure Print_Images(l...
Give a code snippet in #Pascal Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Teacup_rim_text
Teacup rim text
On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three...
#Nim
Nim
import sequtils, sets, sugar   let words = collect(initHashSet, for word in "unixdict.txt".lines: {word})   proc rotate(s: var string) = let first = s[0] for i in 1..s.high: s[i - 1] = s[i] s[^1] = first   var result: seq[string] for word in "unixdict.txt".lines: if word.len >= 3: block checkWord: var...
Give a code snippet in #Nim On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still e...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Ruby
Ruby
def sierpinski_carpet(n) carpet = ["#"] n.times do carpet = carpet.collect {|x| x + x + x} + carpet.collect {|x| x + x.tr("#"," ") + x} + carpet.collect {|x| x + x + x} end carpet end   4.times{|i| puts "\nN=#{i}", sierpinski_carpet(i)}
Give a code snippet in #Ruby Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## ...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Wren
Wren
var lookAndSay = Fn.new { |s| var res = "" var digit = s[0] var count = 1 for (i in 1...s.count) { if (s[i] == digit) { count = count + 1 } else { res = res + "%(count)%(digit)" digit = s[i] count = 1 } } return res + "%(cou...
Give a code snippet in #Wren The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#Julia
Julia
using LightXML   dialog = [("April", "Bubbly: I'm > Tam and <= Emily"), ("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""), ("Emily", "Short & shrift")]   const xdoc = XMLDocument() const xroot = create_root(xdoc, "CharacterRemarks")   for (name, remarks) in dialog xs1 = n...
Give a code snippet in #Julia Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> el...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
wd = NotebookDirectory[]; DeleteFile[wd <> "input.txt"] DeleteFile["/" <> "input.txt"] DeleteDirectory[wd <> "docs"] DeleteDirectory["/" <> "docs"]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Icon_and_Unicon
Icon and Unicon
procedure main() write(q(1), " ", q(2), " ", q(3), " ", q(4), " ", q(5), " ", q(6), " ", q(7), " ", q(8)) end   procedure q(c) static udiag, ddiag, row   initial { udiag := list(15, 0) ddiag := list(15, 0) row := list(8, 0) }   every 0 = row[r := 1 to 8] = ddiag[r + c - 1] = ...
Give a code snippet in #Icon_and_Unicon Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour ...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#ALGOL_W
ALGOL W
begin  % strings are (fixed length) values in algol W. Assignment makes a copy  % string(10) a, copyOfA; a := "some text"; copyOfA := a;  % assignment to a will not change copyOfA  % a := "new value"; write( a, copyOfA ) end.
Give a code snippet in #ALGOL_W This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   int main() { @autoreleasepool { for(NSUInteger i=2008; i<2121; i++) { NSCalendarDate *d = [[NSCalendarDate alloc] initWithYear: i month: 12 day: 25 ...
Give a code snippet in #Objective-C A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years be...
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#Raku
Raku
use NativeCall; say $*VM.config<ptr_size>; my $bytes = nativecast(CArray[uint8], CArray[uint16].new(1)); say $bytes[0] ?? "little-endian" !! "big-endian";
Give a code snippet in #Raku Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Modula-2
Modula-2
MODULE PythagoreanMeans; FROM FormatString IMPORT FormatString; FROM LongMath IMPORT power; FROM LongStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE ArithmeticMean(numbers : ARRAY OF LONGREAL) : LONGREAL; VAR i,cnt : CARDINAL; mean : LONGREAL; BEGIN mean := 0.0; cnt ...
Give a code snippet in #Modula-2 Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Haskell
Haskell
data Obj = Obj { field :: Int, method :: Int -> Int }   -- smart constructor mkAdder :: Int -> Obj mkAdder x = Obj x (+x)   -- adding method from a type class instanse Show Obj where show o = "Obj " ++ show (field o)
Give a code snippet in #Haskell In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static o...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Phix
Phix
-- demo\rosetta\9billionnames.exw with javascript_semantics sequence cache = {{1}} function cumu(integer n) sequence r for l=length(cache) to n do r = {0} for x=1 to l do r = append(r,r[-1]+cache[l-x+1][min(x,l-x)+1]) end for cache = append(cache,r) end for retur...
Give a code snippet in #Phix This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Argile
Argile
use std, array, hash   let keys = @["hexadecimal" "decimal" "octal" "binary"] let values = @[0xa 11 014 0b1101] (: 10 11 12 13 :) let hash = new hash of int for each val int i from 0 to 3 hash[keys[i]] = values[i] del hash hash
Give a code snippet in #Argile Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order
Magic squares of singly even order
A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6,...
#FreeBASIC
FreeBASIC
' version 18-03-2016 ' compile with: fbc -s console ' singly even magic square 6, 10, 14, 18...   Sub Err_msg(msg As String) Print msg Beep : Sleep 5000, 1 : Exit Sub End Sub   Sub se_magicsq(n As UInteger, filename As String = "")   ' filename <> "" then save square in a file ' filename can contain dir...
Give a code snippet in #FreeBASIC A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ukkonen%E2%80%99s_suffix_tree_construction
Ukkonen’s suffix tree construction
Suffix Trees are very useful in numerous string processing and computational biology problems. The task is to create a function which implements Ukkonen’s algorithm to create a useful Suffix Tree as described: Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Using Arithmetic-geometric mean/Calculate Pi generate the first 1...
#Go
Go
package main   import ( "fmt" "math/big" "time" )   var maxChar = 128   type Node struct { children []*Node suffixLink *Node start int end *int suffixIndex int }   var ( text string root *Node lastNewNode *Node ac...
Give a code snippet in #Go Suffix Trees are very useful in numerous string processing and computational biology problems. The task is to create a function which implements Ukkonen’s algorithm to create a useful Suffix Tree as described: Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Using Arithmetic-geometric mean/Calcu...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Ring
Ring
  number = "1" for nr = 1 to 10 number = lookSay(number) see number + nl next   func lookSay n i = 0 j = 0 c="" o="" i = 1 while i <= len(n) c = substr(n,i,1) j = i + 1 while substr(n,j,1) = c j += 1 end o += string(j-i) + c ...
Give a code snippet in #Ring The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#Efene
Efene
@public run = fn () { lists.foreach(fn ((A, B, C)) { io.format("~s~n", [[A, B, C]]) }, lists.zip3("abc", "ABC", "123")) }  
Give a code snippet in #Efene Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this exam...
christopher/rosetta-code
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#Haskell
Haskell
import Control.Monad (forM_) import Data.Number.CReal (CReal, showCReal) import Text.Printf (printf)   ramfun :: CReal -> CReal ramfun x = exp (pi * sqrt x)   -- Ramanujan's constant. ramanujan :: CReal ramanujan = ramfun 163   -- The last four Heegner numbers. heegners :: [Int] heegners = [19, 43, 67, 163]   -- The ab...
Give a code snippet in #Haskell Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Arturo
Arturo
problem: true   if problem -> exit
Give a code snippet in #Arturo Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizer...
christopher/rosetta-code
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#Clojure
Clojure
var xs = Array.Empty(10) var ys = Array(1, 2, 3) var str = xs.ToString()   type Maybe = Some(x) or None() var x = Maybe.Some(42)
Give a code snippet in #Clojure Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixe...
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.
#Erlang
Erlang
    %% Multiplies two matrices. Usage example: %% $ matrix:multiply([[1,2,3],[4,5,6]], [[4,4],[0,0],[1,4]]) %% If the dimentions are incompatible, an error is thrown. %% %% The erl shell may encode the lists output as strings. In order to prevent such %% behaviour, BEFORE running matrix:multiply, run shell:strings(fals...
Give a code snippet in #Erlang 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/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs ...
#XPL0
XPL0
include c:\cxpl\codes;   proc PERMS(N); int N; \number of elements int I, K, S, T, P; [P:= Reserve((N+1)*4); for I:= 0 to N do P(I):= -I; \initialize facing left (also set P(0)=0) S:= 1; repeat Text(0, "Perm: [ "); for I:= 1 to N do [IntOut(0, abs(P(I))); ChOut(0, ...
Give a code snippet in #XPL0 Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Sh...
christopher/rosetta-code
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Delphi
Delphi
  program File_extension_is_in_extensions_list;   {$APPTYPE CONSOLE}   uses System.SysUtils;   const exts: TArray<string> = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; filenames: TArray<string> = ['MyData.a##', 'MyData.tar.Gz', 'MyData.gzip', 'MyData.7z.backup', 'MyData...', 'MyData', 'MyData_v1....
Give a code snippet in #Delphi File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of exten...
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#BBC_BASIC
BBC BASIC
DIM list$(6) list$() = "apple", "banana", "cherry", "date", "elderberry", "fig", "grape"   setA% = %1010101 PRINT "Set A: " FNlistset(list$(), setA%) setB% = %0111110 PRINT "Set B: " FNlistset(list$(), setB%) elementM% = %0000010 PRINT "Element M: " FNlistset(list$(), ele...
Give a code snippet in #BBC_BASIC Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: S...
christopher/rosetta-code
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Perl
Perl
use utf8; use strict; use warnings; use feature 'say'; use List::Util 'uniq';   sub prime_factors { my ($n, $d, @factors) = (shift, 1); while ($n > 1 and $d++) { $n /= $d, push @factors, $d until $n % $d; } @factors }   sub μ { my @p = prime_factors(shift); @p == uniq(@p) ? 0 == @p%2 ? 1...
Give a code snippet in #Perl The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum o...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#R
R
  library(gWidgets) options(guiToolkit="RGtk2") ## using gWidgtsRGtk2   w <- gwindow("Interaction")   g <- ggroup(cont=w, horizontal=FALSE) e <- gedit(0, cont=g, coerce.with=as.numeric) bg <- ggroup(cont=g)   inc_btn <- gbutton("increment", cont=bg) rdm_btn <- gbutton("random", cont=bg)   addHandlerChanged(e, handler=f...
Give a code snippet in #R Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   COMMENT REQUIRED BY "prelude_dijkstras_algorithm.a68" CO MODE ROUTELEN = ~; ROUTELEN route len infinity = max ~; PROC route len add = (VERTEX v, ROUTE r)ROUTELEN: route len OF v + route len OF r; # or MAX(v,r) # MODE VERTEXPAYLOAD = ~; PROC dijkstra fix value error = (STRING ms...
Give a code snippet in #ALGOL_68 This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves t...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have b...
#Go
Go
package main   import ( "github.com/gotk3/gotk3/gtk" "log" "time" )   func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } }   func main() { gtk.Init(nil)   window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.Se...
Give a code snippet in #Go Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of in...
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 ...
#Oforth
Oforth
func: sedol(s) [ 1, 3, 1, 7, 3, 9 ] s zipWith(#[ dup isDigit ifTrue: [ '0' - ] else: [ 'A' - 10 + ] * ]) sum 10 mod 10 swap - 10 mod StringBuffer new s << swap '0' + <<c ;
Give a code snippet in #Oforth 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 585284...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Ruby
Ruby
class Maze # Solve via breadth-first algorithm. # Each queue entry is a path, that is list of coordinates with the # last coordinate being the one that shall be visited next. def solve   # Clean up. reset_visiting_state   # Enqueue start position. @queue = [] enqueue_cell([], @start_x, @star...
Give a code snippet in #Ruby Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#MAXScript
MAXScript
  Range = [1,100] randomNumber = (random Range.x Range.y) as integer clearListener() while true do ( userVal = getKBValue prompt:("Enter a number between "+(range[1] as integer) as string+" and "+(range[2] as integer) as string+": ") if userVal == randomNumber do (format "\nWell guessed!\n"; exit with OK) case of (...
Give a code snippet in #MAXScript Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is:...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Maxima
Maxima
  (%i1) eqns: [ 2*w-x+5*y+z=-3, 3*w+2*x+2*y-6*z=-32, w+3*x+3*y-z=-47, 5*w-2*x-3*y+3*z=49]; (%o1) [z + 5 y - x + 2 w = - 3, (- 6 z) + 2 y + 2 x + 3 w = - 32, (- z) + 3 y + 3 x + w = - 47, 3 z - 3 y - 2 x + 5 w = 49] (%i2) A: augcoefmatrix (eqns, [w,x,y,z]); [ 2 - 1 5 ...
Give a code snippet in #Maxima linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+...
christopher/rosetta-code
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Crystal
Crystal
require "big"   def prime?(n) # P3 Prime Generator primality test return false unless (n | 1 == 3 if n < 5) || (n % 6) | 4 == 5 sqrt_n = Math.isqrt(n) # For Crystal < 1.2.0 use Math.sqrt(n).to_i pc = typeof(n).new(5) while pc <= sqrt_n return false if n % pc == 0 || n % (pc + 2) == 0 pc += 6 end tr...
Give a code snippet in #Crystal n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative power...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#C.23
C#
using System;   class Program { static void Main(string[] args) { int switchWins = 0; int stayWins = 0;   Random gen = new Random();   for(int plays = 0; plays < 1000000; plays++ ) { int[] doors = {0,0,0};//0 is a goat, 1 is a car   var winner = ge...
Give a code snippet in #C.23 Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the ...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#AutoIt
AutoIt
MsgBox(0,"Time", "Year: "&@YEAR&",Day: " &@MDAY& ",Hours: "& @HOUR & ", Minutes: "& @MIN &", Seconds: "& @SEC)
Give a code snippet in #AutoIt Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#Octave
Octave
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]; plot(x,y,"o"); pause;
Give a code snippet in #Octave Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
 !. to-str ++ to-num "100"
Give a code snippet in #D.C3.A9j.C3.A0_Vu Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#MATLAB_.2F_Octave
MATLAB / Octave
  [a,b]=rat(.75) [a,b]=rat(.518518) [a,b]=rat(.9054054)  
Give a code snippet in #MATLAB_.2F_Octave This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest t...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Ruby
Ruby
  def yesno begin system("stty raw -echo") str = STDIN.getc ensure system("stty -raw echo") end if str == "Y" return true elsif str == "N" return false else raise "Invalid character." end end  
Give a code snippet in #Ruby Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed,...
christopher/rosetta-code
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#Ruby
Ruby
def funnel(dxs, &rule) x, rxs = 0, [] for dx in dxs rxs << (x + dx) x = rule[x, dx] end rxs end   def mean(xs) xs.inject(:+) / xs.size end   def stddev(xs) m = mean(xs) Math.sqrt(xs.inject(0.0){|sum,x| sum + (x-m)**2} / xs.size) end   def experiment(label, dxs, dys, &rule) rxs, rys = funnel(dxs, &...
Give a code snippet in #Ruby W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Java
Java
import java.util.List; import java.util.ArrayList; import java.util.Arrays;   public class PermutationSort { public static void main(String[] args) { int[] a={3,2,1,8,9,4,6}; System.out.println("Unsorted: " + Arrays.toString(a)); a=pSort(a); System.out.println("Sorted: " + Arrays.toString(a)); } public sta...
Give a code snippet in #Java 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/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#zkl
zkl
fcn smithNumbers(N=0d10_000){ // -->(Smith numbers to N) [2..N].filter(fcn(n){ (pfs:=primeFactors(n)).len()>1 and n.split().sum(0)==primeFactors(n).apply("split").flatten().sum(0) }) }
Give a code snippet in #zkl Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are al...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#Objeck
Objeck
  class Append { function : Main(args : String[]) ~ Nil { x := "foo"; x->Append("bar"); x->PrintLine(); } }  
Give a code snippet in #Objeck Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#XPL0
XPL0
func IPow(A, B); \A^B int A, B, T, I; [T:= 1; for I:= 1 to B do T:= T*A; return T; ];   int Count, M, N, Sum, T, Dig; [Text(0, "0 "); Count:= 1; for M:= 1 to 9 do for N:= IPow(10, M-1) to IPow(10, M)-1 do [Sum:= 0; T:= N; while T do [T:= T/10; Dig:= rem(0); ...
Give a code snippet in #XPL0 A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#APL
APL
  ⍝ Based heavily on the J solution CATALAN←{¯1↓↑-/1 ¯1↓¨(⊂⎕IO+0 0)⍉¨0 2⌽¨⊂(⎕IO-⍨⍳N){+\⍣⍺⊢⍵}⍤0 1⊢1⍴⍨N←⍵+2}  
Give a code snippet in #APL Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that genera...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/2
Text processing/2
The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters...
#Racket
Racket
#lang racket (read-decimal-as-inexact #f) ;; files to read is a sequence, so it could be either a list or vector of files (define (text-processing/2 files-to-read) (define seen-datestamps (make-hash)) (define (datestamp-seen? ds) (hash-ref seen-datestamps ds #f)) (define (datestamp-seen! ds pos) (hash-set! seen-d...
Give a code snippet in #Racket The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Standard_ML
Standard ML
(TextIO.print "input a number of seconds please: "; let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in TextIO.print "Sleeping...\n"; OS.Process.sleep (Time.fromReal seconds); (* it takes a Time.time data structure as arg, but in my imp...
Give a code snippet in #Standard_ML Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main ...
christopher/rosetta-code