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/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...
#Lua
Lua
function gcd(a,b) if b ~= 0 then return gcd(b, a % b) else return math.abs(a) end end   function demo(a,b) print("GCD of " .. a .. " and " .. b .. " is " .. gcd(a, b)) end   demo(100, 5) demo(5, 100) demo(7, 23)
Give a code snippet in #Lua 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 c...
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...
#Lasso
Lasso
File_Write: '/dev/lp0', 'Hello world', -FileOverWrite;
Give a code snippet in #Lasso 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...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Maple
Maple
play24 := module() export ModuleApply; local cheating; cheating := proc(input, digits) local i, j, stringDigits; use StringTools in stringDigits := Implode([seq(convert(i, string), i in digits)]); for i in digits do for j in digits do if Search(cat(convert(i, string), j), input) > 0 then ret...
Give a code snippet in #Maple The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four di...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#ERRE
ERRE
  PROGRAM SIERPINSKY   !$INCLUDE="PC.LIB"   BEGIN ORDER%=8 SIZE%=2^ORDER% SCREEN(9) GR_WINDOW(0,0,520,520) FOR Y%=0 TO SIZE%-1 DO FOR X%=0 TO SIZE%-1 DO IF (X% AND Y%)=0 THEN PSET(X%*2,Y%*2,2) END IF END FOR END FOR GET(K$) END PROGRAM  
Give a code snippet in #ERRE Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Pascal
Pascal
Program TrigonometricFuntions(output);   uses math;   var radians, degree: double;   begin radians := pi / 4.0; degree := 45; // Pascal works in radians. Necessary degree-radian conversions are shown. writeln (sin(radians),' ', sin(degree/180*pi)); writeln (cos(radians),' ', cos(degree/180*pi)); w...
Give a code snippet in #Pascal Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that eval...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#MATLAB_.2F_Octave
MATLAB / Octave
x = [2,4,4,4,5,5,7,9]; n = length (x);   m = mean (x); x2 = mean (x .* x); dev= sqrt (x2 - m * m) dev = 2
Give a code snippet in #MATLAB_.2F_Octave Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed f...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Kotlin
Kotlin
class Combinations(val m: Int, val n: Int) { private val combination = IntArray(m)   init { generate(0) }   private fun generate(k: Int) { if (k >= m) { for (i in 0 until m) print("${combination[i]} ") println() } else { for (j in 0 unt...
Give a code snippet in #Kotlin Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Axe
Axe
RECURSE(1) Lbl RECURSE .Optionally, limit the number of times the argument is printed Disp r₁▶Dec,i RECURSE(r₁+1)
Give a code snippet in #Axe Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Racket
Racket
  #!/usr/bin/env racket #lang racket   (define from-string #f) (define to-string #f)   (command-line #:once-each [("-f") from "Text to remove" (set! from-string from)] [("-t") to "Text to put instead" (set! to-string to)] #:args files (unless from-string (error "No `from' string specified")) (unless to-string (...
Give a code snippet in #Racket Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Gambas
Gambas
Public Sub Form_Open() Dim sIn As String = InputBox("Enter 2 integers seperated by a comma") Dim iFirst, iSecond As Integer   iFirst = Val(Split(sIn)[0]) iSecond = Val(Split(sIn)[1])   If iFirst < iSecond Then Print iFirst & " is smaller than " & iSecond & gb.NewLine If iFirst > iSecond Then Print iFirst & " is greater...
Give a code snippet in #Gambas 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/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Elixir
Elixir
defmodule Standard_deviation do def add_sample( pid, n ), do: send( pid, {:add, n} )   def create, do: spawn_link( fn -> loop( [] ) end )   def destroy( pid ), do: send( pid, :stop )   def get( pid ) do send( pid, {:get, self()} ) receive do { :get, value, _pid } -> value end end   def tas...
Give a code snippet in #Elixir Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the func...
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...
#zkl
zkl
(123456789).gcd(987654321) //-->9
Give a code snippet in #zkl 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 c...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#XPL0
XPL0
code CrLf=9, IntOut=11;   func Not(A); int A; return not A;   func And(A, B); int A, B; return A and B;   func Or(A, B); int A, B; return A or B;   func Xor(A, B); int A, B; return Or(And(A, Not(B)), And(Not(A), B));   proc HalfAdd(A, B, S, C); int A, B, S, C; [S(0):= Xor(A, B); C(0):= And(A, B); ];   proc FullAdd(A, ...
Give a code snippet in #XPL0 Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made u...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Haskell
Haskell
import System.Environment (getArgs)   main = getArgs >>= (\[a, b, c] -> do contents <- fmap lines $ readFile a let b1 = read b :: Int c1 = read c :: Int putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents] )
Give a code snippet in #Haskell Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to r...
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 ...
#Euphoria
Euphoria
  --Day of the week task from Rosetta Code wiki --User:Lnettnay   --In what years between 2008 and 2121 will the 25th of December be a Sunday   include std/datetime.e   datetime dt   for year = 2008 to 2121 do dt = new(year, 12, 25) if weeks_day(dt) = 1 then -- Sunday = 1 ? year ...
Give a code snippet in #Euphoria 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 betwe...
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#Phix
Phix
without js include builtins\cffi.e constant AF_UNSPEC = 0, -- AF_INET = 2, -- AF_INET6 = 23, -- SOCK_STREAM = 1, SOCK_DGRAM = 2, -- IPPROTO_TCP = 6, NI_MAXHOST = 1025, NI_NUMERICHOST = iff(platform()=LINUX?1:2) constant tWAD = """ typedef struct WSAData { WORD ...
Give a code snippet in #Phix DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#C.23
C#
using System;   namespace LCS { class Program { static void Main(string[] args) { string word1 = "thisisatest"; string word2 = "testing123testing";   Console.WriteLine(lcsBack(word1, word2)); Console.ReadKey(); }   public static str...
Give a code snippet in #C.23 Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be string...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Ursa
Ursa
# # user input #   # in ursa, the type of data expected must be specified decl string str decl int i   out "input a string: " console set str (in string console) out "input an int: " console set i (in int console)   out "you entered " str " and " i endl console
Give a code snippet in #Ursa User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!. = !prompt "Enter my code: " concat( swap !decode!utf-8 !encode!quoted dup swap ) "!. = !prompt \qEnter my code: \q concat( swap !decode!utf-8 !encode!quoted dup swap ) "
Give a code snippet in #D.C3.A9j.C3.A0_Vu Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its i...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#ATS
ATS
(* Usage: vm [INPUTFILE [OUTPUTFILE]] If INPUTFILE or OUTPUTFILE is "-" or missing, then standard input or standard output is used, respectively.   The Rosetta Code virtual machine task in ATS2 (also known as Postiats).   Some implementation notes:   * Values are stored as uint32, and it is checke...
Give a code snippet in #ATS A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#OCaml
OCaml
let rec agm a g tol = if tol > abs_float (a -. g) then a else agm (0.5*.(a+.g)) (sqrt (a*.g)) tol   let _ = Printf.printf "%.16f\n" (agm 1.0 (sqrt 0.5) 1e-15)
Give a code snippet in #OCaml This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function t...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program problemABC64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantes...
Give a code snippet in #AArch64_Assembly ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A compl...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Racket
Racket
((λ (x) `(,x ',x)) '(λ (x) `(,x ',x)))
Give a code snippet in #Racket A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the numb...
#Haskell
Haskell
{-# language LambdaCase #-} import Data.List import Control.Monad   newtype Dice = Dice [Int]   instance Show Dice where show (Dice s) = "(" ++ unwords (show <$> s) ++ ")"   instance Eq Dice where d1 == d2 = d1 `compare` d2 == EQ   instance Ord Dice where Dice d1 `compare` Dice d2 = (add $ compare <$> d1 <*> d2)...
Give a code snippet in #Haskell Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 def...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Nim
Nim
import random, strutils, strformat, sequtils randomize()   const Digits = "123456789" DigitSet = {Digits[0]..Digits[^1]} Size = 4   proc sample(s: string; n: Positive): string = ## Return a random sample of "n" characters extracted from string "s". var s = s s.shuffle() result = s[0..<n]   proc plural(n: ...
Give a code snippet in #Nim Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the gu...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Fortran
Fortran
IsNaN(x)
Give a code snippet in #Fortran
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Oforth
Oforth
"Hello world!" .
Give a code snippet in #Oforth Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#FreeBASIC
FreeBASIC
'Fibonacci extended 'Freebasic version 24 Windows Dim Shared ADDQmod(0 To 19) As Ubyte Dim Shared ADDbool(0 To 19) As Ubyte   For z As Integer=0 To 19 ADDQmod(z)=(z Mod 10+48) ADDbool(z)=(-(10<=z)) Next z   Function plusINT(NUM1 As String,NUM2 As String) As String Dim As Byte flag #macro finish() ...
Give a code snippet in #FreeBASIC The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions...
christopher/rosetta-code
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#XPL0
XPL0
proc FillArea(X, Y, C0, C); \Replace area colored C0 with color C int X, Y, \starting coordinate for flood fill algorithm C0, C; \initial color, and color to replace it with def S=8000; \size of queue (must be an even number) int Q(S), \queue (FIFO) F, E; \fill and empty indexes  ...
Give a code snippet in #XPL0 A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) ...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Haskell
Haskell
import Graphics.UI.Gtk import Control.Monad   main = do initGUI   window <- windowNew set window [windowTitle := "Graphical user input", containerBorderWidth := 10]   vb <- vBoxNew False 0 containerAdd window vb   hb1 <- hBoxNew False 0 boxPackStart vb hb1 PackNatural 0 hb2 <- hBoxNew False 0 boxPackS...
Give a code snippet in #Haskell In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Julia
Julia
  using Polynomials   p = Poly([-42,0,-12,1]) q = Poly([-3,1])   d, r = divrem(p,q)   println(p, " divided by ", q, " is ", d, " with remainder ", r, ".")  
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long...
christopher/rosetta-code
http://rosettacode.org/wiki/Compile-time_calculation
Compile-time calculation
Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#OCaml
OCaml
let days_to_seconds n = let conv = 24 * 60 * 60 in (n * conv) ;;
Give a code snippet in #OCaml Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Component_Pascal
Component Pascal
  MODULE LeapYear; IMPORT StdLog, Strings, Args;   PROCEDURE IsLeapYear(year: INTEGER): BOOLEAN; BEGIN IF year MOD 4 # 0 THEN RETURN FALSE ELSE IF year MOD 100 = 0 THEN IF year MOD 400 = 0 THEN RETURN TRUE ELSE RETURN FALSE END ELSE RETURN TRUE END END END IsLeapYear;   PROCEDURE Do*; VAR p: Arg...
Give a code snippet in #Component_Pascal Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Fortran
Fortran
program bottlestest   implicit none   integer :: i   character(len=*), parameter :: bwall = " on the wall", & bottles = "bottles of beer", & bottle = "bottle of beer", & take = "Take one down, pass it aroun...
Give a code snippet in #Fortran Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Java
Java
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants;   public class Bresenham {   public static void main(String[] args) { SwingUtilities.invokeLater(Bresenham:...
Give a code snippet in #Java Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Cuban_primes
Cuban primes
The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.   primes of the form:   n3 - ...
#Groovy
Groovy
class CubanPrimes { private static int MAX = 1_400_000 private static boolean[] primes = new boolean[MAX]   static void main(String[] args) { preCompute() cubanPrime(200, true) for (int i = 1; i <= 5; i++) { int max = (int) Math.pow(10, i) printf("%,d-th cuban...
Give a code snippet in #Groovy The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#ALGOL_W
ALGOL W
% returns true if ccNumber passes the Luhn test, false otherwise % % as Algol W has fixed length strings, the length of the number  % % must be specified in ccLength  % logical procedure LuhnTest ( string(32) value ccNumber  ; integer value ccLength ...
Give a code snippet in #ALGOL_W The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order ...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Standard_ML
Standard ML
open XWindows ; open Motif ;   val countWindow = fn () =>   let val ctr = ref 0; val shell = XtAppInitialise "" "demo" "top" [] [XmNwidth 300, XmNheight 150 ] ; val main = XmCreateMainWindow shell "main" [XmNmappedWhenManaged true ] ; val frame = XmCreateForm main "frame" ...
Give a code snippet in #Standard_ML Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
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 ...
#Elixir
Elixir
defmodule Ranking do def methods(data) do IO.puts "stand.\tmod.\tdense\tord.\tfract." Enum.group_by(data, fn {score,_name} -> score end) |> Enum.map(fn {score,pairs} -> names = Enum.map(pairs, fn {_,name} -> name end) |> Enum.reverse {score, names} end) |> Enum.sort_by(fn {sco...
Give a code snippet in #Elixir Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#SequenceL
SequenceL
main := josephus(41, 3);   josephus(n, k) := josephusHelper(n, k, 1, 0);   josephusHelper(n, k, i, r) := r when i > n else josephusHelper(n, k, i + 1, (r + k) mod i);
Give a code snippet in #SequenceL Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[RepUnit, CircularPrimeQ] RepUnit[n_] := (10^n - 1)/9 CircularPrimeQ[n_Integer] := Module[{id = IntegerDigits[n], nums, t}, AllTrue[ Range[Length[id]] , Function[{z}, t = FromDigits[RotateLeft[id, z]]; If[t < n, False , PrimeQ[t] ] ] ] ] Select[Range[200000], Circ...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also...
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#Frink
Frink
isSemiprime[n] := { factors = factor[n] sum = 0 for [num, power] = factors sum = sum + power   return sum == 2 }
Give a code snippet in #Frink Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was cho...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are...
#C
C
#include <stdio.h> #include <stdlib.h>   char *names[4][3] = { { "red", "green", "purple" }, { "oval", "squiggle", "diamond" }, { "one", "two", "three" }, { "solid", "open", "striped" } };   int set[81][81];   void init_sets(void) { int i, j, t, a, b; for (i = 0; i < 81; i++) { for (j = 0; j < 81; j++) { for...
Give a code snippet in #C Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#Fortran
Fortran
  PROGRAM SUBLEQ0 !Simulates a One-Instruction computer, with Subtract and Branch if <= 0. INTEGER LOTS,LOAD !Document some bounds. PARAMETER (LOTS = 36, LOAD = 31) !Sufficient for the example. INTEGER IAR, MEM(0:LOTS) !The basic storage of a computer. IAR could be in memory too. INTEGER...
Give a code snippet in #Fortran Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Sidef
Sidef
var hash = Hash.new( key1 => 'value1', key2 => 'value2', )   # Iterate over key-value pairs hash.each { |key, value| say "#{key}: #{value}"; }   # Iterate only over keys hash.keys.each { |key| say key; }   # Iterate only over values hash.values.each { |value| say value; }
Give a code snippet in #Sidef Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Com...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Liberty_BASIC
Liberty BASIC
print "Goodbye, World!";  
Give a code snippet in #Liberty_BASIC Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello wor...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#Crystal
Crystal
tokens = 12   until tokens <= 0 puts "There are #{tokens} tokens remaining.\nHow many tokens do you take?" until (input = (gets || "").to_i?) && (1..3).includes? input puts "Enter an integer between 1 and 3." end puts "Player takes #{input} tokens.\nComputer takes #{4-input} tokens." tokens ...
Give a code snippet in #Crystal Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player take...
christopher/rosetta-code
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Swift
Swift
import Foundation   protocol Thingable { // prior to Swift 1.2, needs to be declared @objc func thing() -> String }   class Delegator { weak var delegate: AnyObject? func operation() -> String { if let f = self.delegate?.thing { return f() } else { return "default implementation" } } }  ...
Give a code snippet in #Swift A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also w...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Ol
Ol
  (import (otus random!))  
Give a code snippet in #Ol Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#CoffeeScript
CoffeeScript
entropy = (s) -> freq = (s) -> result = {} for ch in s.split "" result[ch] ?= 0 result[ch]++ return result   frq = freq s n = s.length ((frq[f]/n for f of frq).reduce ((e, p) -> e - p * Math.log(p)), 0) * Math.LOG2E   console.log "The entropy of the string...
Give a code snippet in #CoffeeScript Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for bi...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Elena
Elena
import extensions;   public program() { var s := "12345"; s := (s.toInt() + 1).toString();   console.printLine(s) }
Give a code snippet in #Elena Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Diversity_prediction_theorem
Diversity prediction theorem
The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that assumes independence of the i...
#JavaScript
JavaScript
'use strict';   function sum(array) { return array.reduce(function (a, b) { return a + b; }); }   function square(x) { return x * x; }   function mean(array) { return sum(array) / array.length; }   function averageSquareDiff(a, predictions) { return mean(predictions.map(function (x) { ...
Give a code snippet in #JavaScript The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Red
Red
Red[]   clicks: 0   view [ t: text "There have been no clicks yet" return button "click me" [ clicks: clicks + 1 t/data: rejoin ["clicks: " clicks] ] ]
Give a code snippet in #Red Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Visual_Basic
Visual Basic
Sub Main MsgBox Command$ End Sub
Give a code snippet in #Visual_Basic Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Draco
Draco
proc nonrec main() void: byte i; for i from 1 upto 100 do if i % 15 = 0 then writeln("FizzBuzz") elif i % 5 = 0 then writeln("Buzz") elif i % 3 = 0 then writeln("Fizz") else writeln(i) fi od corp
Give a code snippet in #Draco Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Forth
Forth
: fsum**2 ( addr n -- f ) 0e dup 0= if 2drop exit then floats bounds do i f@ fdup f* f+ 1 floats +loop ;   create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f, test 6 fsum**2 f. \ 133.
Give a code snippet in #Forth Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Rust
Rust
  use std::io::{self, BufRead};   fn op(x: f32) -> Option<f32> { let y = x.abs().sqrt() + 5.0 * x * x * x; if y < 400.0 { Some(y) } else { None } }   fn main() { println!("Please enter 11 numbers (one number per line)"); let stdin = io::stdin();   let xs = stdin .lock...
Give a code snippet in #Rust The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
IntegerHalving[x_]:=Floor[x/2] IntegerDoubling[x_]:=x*2; OddInteger OddQ Ethiopian[x_, y_] := Total[Select[NestWhileList[{IntegerHalving[#[[1]]],IntegerDoubling[#[[2]]]}&, {x,y}, (#[[1]]>1&)], OddQ[#[[1]]]&]][[2]]   Ethiopian[17, 34]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, disca...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Fortran
Fortran
MODULE BRAIN !It will suffer. INTEGER MSG,KBD CONTAINS !A twisted interpreter. SUBROUTINE RUN(PROG,STORE) !Code and data are separate! CHARACTER*(*) PROG !So, this is the code. CHARACTER*(1) STORE(:) !And this a work area. CHARACTER*1 C !The code of the moment. ...
Give a code snippet in #Fortran Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly impl...
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...
#C.2B.2B
C++
#include <iostream> #include <numeric>   int main() { std::cout << "The greatest common divisor of 12 and 18 is " << std::gcd(12, 18) << " !\n"; }
Give a code snippet in #C.2B.2B 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   greate...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Phix
Phix
function quibble(sequence words) if length(words)>=2 then words[-2..-1] = {words[-2]&" and "&words[-1]} end if return "{"&join(words,", ")&"}" end function constant tests = {{}, {"ABC"}, {"ABC","DEF"}, {"ABC","DEF","G","H"}} for i=1 to length...
Give a code snippet in #Phix Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An inp...
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.
#SQL
SQL
CREATE TABLE a (x INTEGER, y INTEGER, e REAL); CREATE TABLE b (x INTEGER, y INTEGER, e REAL);   -- test data -- A is a 2x2 matrix INSERT INTO a VALUES(0,0,1); INSERT INTO a VALUES(1,0,2); INSERT INTO a VALUES(0,1,3); INSERT INTO a VALUES(1,1,4);   -- B is a 2x3 matrix INSERT INTO b VALUES(0,0,-3); INSERT INTO b VALUES(...
Give a code snippet in #SQL 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/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Rust
Rust
fn double(a: i32) -> i32 { 2*a }   fn halve(a: i32) -> i32 { a/2 }   fn is_even(a: i32) -> bool { a % 2 == 0 }   fn ethiopian_multiplication(mut x: i32, mut y: i32) -> i32 { let mut sum = 0;   while x >= 1 { print!("{} \t {}", x, y); match is_even(x) { true => println!("...
Give a code snippet in #Rust Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#jq
jq
def count(s): reduce s as $i (0;.+1);   def swap($i;$j): .[$i] as $x | .[$i] = .[$j] | .[$j] = $x;   # Input: an array # Output: a best shuffle def bestShuffleArray: . as $s | reduce range(0; length) as $i (.; . as $t | (first(range(0; length) | select( $i != . and ...
Give a code snippet in #jq Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   import Data.ByteString.Char8 () import Data.Conduit ( ($$), yield ) import Data.Conduit.Network ( ServerSettings(..), runTCPServer )   main :: IO () main = runTCPServer (ServerSettings 8080 "127.0.0.1") $ const (yield response $$) where response = "HTTP/1.0 200 OK\nContent-Length:...
Give a code snippet in #Haskell The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. No...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#Euphoria
Euphoria
function cocktail_sort(sequence s) integer swapped, d object temp sequence fromto fromto = {1,length(s)-1} swapped = 1 d = 1 while swapped do swapped = 0 for i = fromto[(1-d)/2+1] to fromto[(1+d)/2+1] by d do if compare(s[i],s[i+1])>0 then temp = s...
Give a code snippet in #Euphoria Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Visual_Basic_.NET
Visual Basic .NET
Dim local As New IO.FileInfo("input.txt") Console.WriteLine(local.Length)   Dim root As New IO.FileInfo("\input.txt") Console.WriteLine(root.Length)
Give a code snippet in #Visual_Basic_.NET Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#Lasso
Lasso
// Taken from the Lasso entry in Palindrome page define isPalindrome(text::string) => {   local(_text = string(#text)) // need to make copy to get rid of reference issues   #_text -> replace(regexp(`(?:$|\W)+`), -ignorecase)   local(reversed = string(#_text)) #reversed -> reverse   return #_text == ...
Give a code snippet in #Lasso Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#8086_Assembly
8086 Assembly
MAXPRM: equ 5000 ; Change this value for more primes cpu 8086 bits 16 org 100h section .text erato: mov cx,MAXPRM ; Initialize array (set all items to prime) mov bp,cx ; Keep a copy in BP mov di,sieve mov al,1 rep stosb ;;; Sieve mov bx,sieve ; Set base register to array inc cx ; CX=1 (CH=0, CL=1); CX was ...
Give a code snippet in #8086_Assembly This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosth...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Positional_read
Terminal control/Positional read
Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, r...
#XPL0
XPL0
include c:\cxpl\stdlib; int C; [Cursor(3, 6); \move cursor to column 3, row 6 (top left = 0,0) \Call BIOS interrupt routine to read character (& attribute) at cursor position C:= CallInt($10, $0800, 0) & $00FF; \mask off attribute, leaving the character ]
Give a code snippet in #XPL0 Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display r...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Delphi
Delphi
  program Best_shuffle;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Generics.Collections;   type TShuffledString = record private original: string; Shuffled: TStringBuilder; ignoredChars: Integer; procedure DetectIgnores; procedure Shuffle; procedure Swap(pos1, pos2: Integer); ...
Give a code snippet in #Delphi Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time...
christopher/rosetta-code
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#EasyLang
EasyLang
xp = 10 yp = 40 linewidth 2 move xp yp while angle > -720 x = xp + cos angle * 80 y = yp + sin -angle * 80 line x y f[] &= x f[] &= y xp = x yp = y angle -= 144 . color 900 polygon f[]
Give a code snippet in #EasyLang A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or tok...
christopher/rosetta-code
http://rosettacode.org/wiki/Numeric_error_propagation
Numeric error propagation
If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   σf = σa If   f = a ± b   then...
#Icon_and_Unicon
Icon and Unicon
record num(val,err)   procedure main(a) x1 := num(100.0, 1.1) y1 := num(50.0, 1.2) x2 := num(200.0, 2.2) y2 := num(100.0, 2.3) d := pow(add(pow(sub(x1,x2),2),pow(sub(y1,y2),2)),0.5) write("d = [",d.val,", ",d.err,"]") end   procedure add(a,b) return (numeric(a)+numeric(b)) | num(...
Give a code snippet in #Icon_and_Unicon If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± ...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Visual_Basic
Visual Basic
Option Explicit   Function IsLongYear(ByVal Year As Integer) As Boolean Select Case vbThursday Case VBA.DatePart("w", VBA.DateSerial(Year, 1, 1)), _ VBA.DatePart("w", VBA.DateSerial(Year, 12, 31)) IsLongYear = True End Select End Function   Sub Main() 'test Dim l As Long For l = 1990 To 2021 Sele...
Give a code snippet in #Visual_Basic Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity...
#VBScript
VBScript
-2^2=(-2)^2=4 2^3^2=(2^3)^2=64
Give a code snippet in #VBScript This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#C.23
C#
using System; using System.Drawing; using System.Drawing.Imaging; using System.Threading; using System.Windows.Forms;   /// <summary> /// Generates bitmap of Mandelbrot Set and display it on the form. /// </summary> public class MandelbrotSetForm : Form { const double MaxValueExtent = 2.0; Thread thread;   ...
Give a code snippet in #C.23 Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#11l
11l
V crc_table = [0] * 256 L(i) 256 UInt32 rem = i L 8 I rem [&] 1 != 0 rem >>= 1 rem (+)= EDB8'8320 E rem >>= 1 crc_table[i] = rem   F crc32(buf, =crc = UInt32(0)) crc = (-)crc L(k) buf crc = (crc >> 8) (+) :crc_table[(crc [&] F'F) (+) k.code] R (-)crc   prin...
Give a code snippet in #11l Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the i...
christopher/rosetta-code
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#Phix
Phix
function dice5() return rand(5) end function function dice7() while true do integer r = dice5()*5+dice5()-3 -- ( ie 3..27, but ) if r<24 then return floor(r/3) end if -- (only 3..23 useful) end while end function
Give a code snippet in #Phix Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Set_lang
Set lang
> Comments start where a > (greater than symbol) starts set a 0 > Comments may start after a Set command
Give a code snippet in #Set_lang Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#AutoIt
AutoIt
  #cs Everything between the cs and and the ce is commented. Commented code is not used by the computer. #ce ;individual lines after a semicolon are commented.  
Give a code snippet in #AutoIt Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#Commodore_BASIC
Commodore BASIC
10 rem mad lib for rosetta code 15 dim bf$(100),wd$(50),tg$(50):tb=49152 20 print chr$(147);chr$(14);"Mad Lib Processor":print 25 gosub 1000 30 gosub 100:gosub 250:gosub 300:gosub 400 40 print:print:print "Again? ";:gosub 500:print k$ 45 if k$<>"y" then end 50 goto 20 100 tg=1:for i=1 to bp:n$="":mo=0 105 t$=bf$(i) 110...
Give a code snippet in #Commodore_BASIC This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template w...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#J
J
s=: 'Hello,How,Are,You,Today' ] t=: <;._1 ',',s +-----+---+---+---+-----+ |Hello|How|Are|You|Today| +-----+---+---+---+-----+  ; t,&.>'.' Hello.How.Are.You.Today.   '.' (I.','=s)}s NB. two steps combined Hello.How.Are.You.Today
Give a code snippet in #J Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks relate...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#REXX
REXX
/*REXX program helps the user find solutions to the game of 24.   ╔═════════════════════════════════════════════════════════════════════════════╗ ║ Argument is either of these forms: (blank) ║⌂ ║ ssss ║⌂ ║ ...
Give a code snippet in #REXX The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four dig...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Nim
Nim
import terminal   echo if stdin.isatty: "stdin is a terminal" else: "stdin is not a terminal"
Give a code snippet in #Nim Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Untouchable_numbers
Untouchable numbers
Definitions   Untouchable numbers   are also known as   nonaliquot numbers.   An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)   The   sum of all the proper divisors   is also known as   the   aliquot sum.   A...
#Wren
Wren
import "/math" for Int, Nums import "/seq" for Lst import "/fmt" for Fmt   var sieve = Fn.new { |n| n = n + 1 var s = List.filled(n+1, false) for (i in 0..n) { var sum = Nums.sum(Int.properDivisors(i)) if (sum <= n) s[sum] = true } return s }   var limit = 1e5 var c = Int.primeSieve...
Give a code snippet in #Wren Definitions   Untouchable numbers   are also known as   nonaliquot numbers.   An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)   The   sum of all the proper divisors   is also know...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#AutoHotkey
AutoHotkey
Loop 15 out .= "`n" Catalan(A_Index) Msgbox % clipboard := SubStr(out, 2) catalan( n ) { ; By [VxE]. Returns ((2n)! / ((n + 1)! * n!)) if 0 <= N <= 22 (higher than 22 results in overflow) If ( n < 3 ) ; values less than 3 are handled specially Return n < 0 ? "" : n = 0 ? 1 : n   i := 1 ; initialize the accumulato...
Give a code snippet in #AutoHotkey Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n ! ...
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Icon_and_Unicon
Icon and Unicon
  import gui $include "guih.icn"   # some constants to define the display and pendulum $define HEIGHT 400 $define WIDTH 500 $define STRING_LENGTH 200 $define HOME_X 250 $define HOME_Y 21 $define SIZE 30 $define START_ANGLE 80   class WindowApp : Dialog ()   # draw the pendulum on given context_window, at position (x,...
Give a code snippet in #Icon_and_Unicon One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pend...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#zkl
zkl
// A triangle is three pairs of points: ( (x,y), (x,y), (x,y) )   fcn det2D(triangle){ p1,p2,p3 := triangle; p1[0]*(p2[1] - p3[1]) + p2[0]*(p3[1] - p1[1]) + p3[0]*(p1[1] - p2[1]); } fcn checkTriWinding(triangle,allowReversed){ //-->triangle, maybe new detTri:=det2D(triangle); if(detTri<0.0){ if(allowR...
Give a code snippet in #zkl Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)   ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#DWScript
DWScript
PrintLn(UpperCase('alphaBETA')); PrintLn(LowerCase('alphaBETA'));
Give a code snippet in #DWScript Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is no...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two p...
#Smalltalk
Smalltalk
import Foundation   struct Point { var x: Double var y: Double   func distance(to p: Point) -> Double { let x = pow(p.x - self.x, 2) let y = pow(p.y - self.y, 2)   return (x + y).squareRoot() } }   extension Collection where Element == Point { func closestPair() -> (Point, Point)? { let (xP, x...
Give a code snippet in #Smalltalk This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Sparkling
Sparkling
var fnlist = {}; for var i = 0; i < 10; i++ { fnlist[i] = function() { return i * i; }; }   print(fnlist[3]()); // prints 9 print(fnlist[5]()); // prints 25
Give a code snippet in #Sparkling Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Intersecting_number_wheels
Intersecting number wheels
A number wheel has: A name which is an uppercase letter. A set of ordered values which are either numbers or names. A number is generated/yielded from a named wheel by: 1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"...
#Julia
Julia
const d1 = Dict("A" => [["1", "2", "3"], 1]) const d2 = Dict("A" => [["1", "B", "2"], 1], "B" => [["3", "4"], 1]) const d3 = Dict("A" => [["1", "D", "D"], 1], "D" => [["6", "7", "8"], 1]) const d4 = Dict("A" => [["1", "B", "C"], 1], "B" => [["3", "4"], 1], "C" => [["5", "B"], 1])   function getvalue!(wheelname, all...
Give a code snippet in #Julia A number wheel has: A name which is an uppercase letter. A set of ordered values which are either numbers or names. A number is generated/yielded from a named wheel by: 1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to th...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#TorqueScript
TorqueScript
  new GuiControl(GuiName) { profile = "GuiDefaultProfile"; horizSizing = "right"; vertSizing = "bottom"; position = "0 0"; extent = "640 480"; minExtent = "8 2"; enabled = 1; visible = 1; clipToParent = 1;   new GuiWindowCtrl() { profile = "GuiWindowProfile"; horizSizing = "right"; vertSizing = "bottom...
Give a code snippet in #TorqueScript Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#CLU
CLU
sum_digits = proc (n, base: int) returns (int) sum: int := 0 while n > 0 do sum := sum + n // base n := n / base end return (sum) end sum_digits   digital_root = proc (n, base: int) returns (int, int) persistence: int := 0 while n >= base do persistence := persistence + 1...
Give a code snippet in #CLU The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , 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...
#Clojure
Clojure
(defn hickerson "Hickerson number, calculated with BigDecimals and manually-entered high-precision value for ln(2)." [n] (let [n! (apply *' (range 1M (inc n)))] (.divide n! (*' 2 (.pow 0.693147180559945309417232121458M (inc n))) 30 BigDecimal/ROUND_HALF_UP)))   (defn almost-integer? "Tests...
Give a code snippet in #Clojure 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 {\displaysty...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#GW-BASIC
GW-BASIC
10 HEAP = 12 20 WHILE HEAP>0 30 TAKE = 0 40 PRINT "There are ";HEAP;" tokens left." 50 WHILE TAKE < 1 OR TAKE > 3 OR TAKE > HEAP 60 INPUT "How many would you like to take? ", TAKE 70 IF TAKE = HEAP THEN GOTO 140 80 WEND 90 PRINT "I will take ";4-TAKE;" tokens." 100 HEAP = HEAP - 4 110 WEND 120 PRINT "I got the last tok...
Give a code snippet in #GW-BASIC Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player tak...
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Delphi
Delphi
for i range 100 drawer[] &= i sampler[] &= i . subr shuffle_drawer for i = len drawer[] downto 2 r = random i swap drawer[r] drawer[i - 1] . . subr play_random call shuffle_drawer found = 1 prisoner = 0 while prisoner < 100 and found = 1 found = 0 i = 0 while i < 50 and found = 0 ...
Give a code snippet in #Delphi The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start ...
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#FBSL
FBSL
#INCLUDE <Include\Windows.inc>   FBSLSETTEXT(ME, "Pendulum") FBSL.SETTIMER(ME, 1000, 10) RESIZE(ME, 0, 0, 300, 200) CENTER(ME) SHOW(ME)   BEGIN EVENTS SELECT CASE CBMSG CASE WM_TIMER ' Request redraw InvalidateRect(ME, NULL, FALSE) RETURN 0 CASE WM_PAINT Swing() CASE WM_CLOSE FBSL.KILLTIMER(ME, 10...
Give a code snippet in #FBSL One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and an...
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...
#SETL
SETL
$ Recursive proc fact(n); if (n < 2) then return 1; else return n * fact(n - 1); end if; end proc;   $ Iterative proc factorial(n); v := 1; for i in {2..n} loop v *:= i; end loop; return v; end proc;
Give a code snippet in #SETL Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_integerness
Test integerness
Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit] Given a rational, real, or co...
#D
D
import std.complex; import std.math; import std.meta; import std.stdio; import std.traits;   void main() { print(25.000000); print(24.999999); print(24.999999, 0.00001); print(25.000100); print(-2.1e120); print(-5e-2); print(real.nan); print(real.infinity); print(5.0+0.0i); print...
Give a code snippet in #D Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit] Gi...
christopher/rosetta-code