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...
#Vlang
Vlang
fn gcd(xx int, yy int) int { mut x, mut y := xx, yy for y != 0 { x, y = y, x%y } return x }   fn main() { println(gcd(33, 77)) println(gcd(49865, 69811)) }  
Give a code snippet in #Vlang Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#BASIC
BASIC
' Arthimetic/Integer DECLARE a%, b% INPUT "Enter integer A: ", a% INPUT "Enter integer B: ", b% PRINT   PRINT a%, " + ", b%, " is ", a% + b% PRINT a%, " - ", b%, " is ", a% - b% PRINT a%, " * ", b%, " is ", a% * b% PRINT a%, " / ", b%, " is ", a% / b%, ", trucation toward zero" PRINT "MOD(", a%, ", ", b...
Give a code snippet in #BASIC 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/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#Scala
Scala
var Δ = 1 val π = 3.141592 val 你好 = "hello" Δ += 1 println(Δ)
Give a code snippet in #Scala Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#JavaScript
JavaScript
var sec_old = 0; function update_clock() { var t = new Date(); var arms = [t.getHours(), t.getMinutes(), t.getSeconds()]; if (arms[2] == sec_old) return; sec_old = arms[2];   var c = document.getElementById('clock'); var ctx = c.getContext('2d'); ctx.fillStyle = "rgb(0,200,200)"; ctx.fillRect(0, 0, c.width, c.h...
Give a code snippet in #JavaScript Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Toka
Toka
needs shell getpid is-data PID [ fork getpid PID = [ ." Child PID: " . cr ] [ ." In child\n" ] ifTrueFalse ] invoke
Give a code snippet in #Toka Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Scala
Scala
import scala.util.Try   object Menu extends App { val choice = menu(list)   def menu(menuList: Seq[String]): String = { if (menuList.isEmpty) "" else { val n = menuList.size   def getChoice: Try[Int] = { println("\n M E N U\n") menuList.zipWithIndex.map { case (text, index) => s"${...
Give a code snippet in #Scala Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the stri...
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#11l
11l
V ndigits = 0 V q = BigInt(1) V r = BigInt(0) V t = q V k = q V n = BigInt(3) V l = n   V first = 1B L ndigits < 1'000 I 4 * q + r - t < n * t print(n, end' ‘’) ndigits++ I ndigits % 70 == 0 print() I first first = 0B print(‘.’, end' ‘’) V nr = 10 * (r - n * t...
Give a code snippet in #11l Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequen...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Mercury
Mercury
:- module addsub.   :- interface. :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module int, list, string.   main(!IO) :- command_line_arguments(Args, !IO), filter_map(to_int, Args, CleanArgs), (length(CleanArgs, 2) -> X = det_index1(CleanArgs,1), Y ...
Give a code snippet in #Mercury Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#AppleScript
AppleScript
(* Only non-accented English letters are altered here. *)   on caesarDecipher(txt, |key|) return caesarEncipher(txt, -|key|) end caesarDecipher   on caesarEncipher(txt, |key|) set codePoints to id of txt set keyPlus25 to |key| mod 26 + 25 repeat with thisCode in codePoints tell thisCode mod 32 ...
Give a code snippet in #AppleScript Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrappin...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#EasyLang
EasyLang
for i range 5 for j range i write "*" . print "" .
Give a code snippet in #EasyLang “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract stru...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#OxygenBasic
OxygenBasic
  extern lib "kernel32.dll"   'http://msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx   typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME, *PSYSTEMTIME;   void GetSystemTime(S...
Give a code snippet in #OxygenBasic This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Lst = {3, 4, 5, 6} ->{3, 4, 5, 6}   PrependTo[ Lst, 2] ->{2, 3, 4, 5, 6} PrependTo[ Lst, 1] ->{1, 2, 3, 4, 5, 6}   Lst ->{1, 2, 3, 4, 5, 6}   Insert[ Lst, X, 4] ->{1, 2, 3, X, 4, 5, 6}
Give a code snippet in #Mathematica_.2F_Wolfram_Language This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a co...
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 ...
#Java
Java
import static java.lang.Math.*; import java.util.Arrays; import java.util.function.BiFunction;   public class DemingsFunnel {   public static void main(String[] args) { double[] dxs = { -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, ...
Give a code snippet in #Java 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/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...
#R
R
diversityStats <- function(trueValue, estimates) { collectivePrediction <- mean(estimates) data.frame("True Value" = trueValue, as.list(setNames(estimates, paste("Guess", seq_along(estimates)))), #Guesses, each with a title and column. "Average Error" = mean((trueValue - estimates)^2), ...
Give a code snippet in #R 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 as...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Ada
Ada
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO;   procedure Test_List_Index is Not_In : exception;   type List is array (Positive range <>) of Unbounded_String;   function Index (Haystack : List; Needle : String) return Positive is begin for Index ...
Give a code snippet in #Ada Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
GUI/Maximum window dimensions
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations an...
#BBC_BASIC
BBC BASIC
SPI_GETWORKAREA = 48 DIM rc{l%,t%,r%,b%} SYS "SystemParametersInfo", SPI_GETWORKAREA, 0, rc{}, 0 PRINT "Maximum width = " ; rc.r% - rc.l% PRINT "Maximum height = " ; rc.b% - rc.t%
Give a code snippet in #BBC_BASIC The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any ad...
christopher/rosetta-code
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your p...
#Ada
Ada
with Ada.Text_IO;   with CryptAda.Digests.Message_Digests.SHA_256; with CryptAda.Digests.Hashes; with CryptAda.Pragmatics;   procedure Brute_Force is use CryptAda.Digests.Message_Digests; use CryptAda.Digests.Hashes; use CryptAda.Digests; use CryptAda.Pragmatics;   Wanted_Sums : constant array (1 .. 3) o...
Give a code snippet in #Ada Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a...
#Raku
Raku
sub intersection ($L11, $L12, $L21, $L22) { my ($Δ1x, $Δ1y) = $L11 »-« $L12; my ($Δ2x, $Δ2y) = $L21 »-« $L22; my $n1 = $L11[0] * $L12[1] - $L11[1] * $L12[0]; my $n2 = $L21[0] * $L22[1] - $L21[1] * $L22[0]; my $n3 = 1 / ($Δ1x * $Δ2y - $Δ2x * $Δ1y); (($n1 * $Δ2x - $n2 * $Δ1x) * $n3, ($n1 * $Δ2y - ...
Give a code snippet in #Raku The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displ...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#Rust
Rust
use std::default::Default; use std::ops::AddAssign;   use itertools::Itertools; use reqwest::get;   #[derive(Default, Debug)] struct Feature<T> { pub cie: T, pub xie: T, pub cei: T, pub xei: T, }   impl AddAssign<Feature<bool>> for Feature<u64> { fn add_assign(&mut self, rhs: Feature<bool>) { ...
Give a code snippet in #Rust The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associativ...
#Ol
Ol
  (define a1 { 'name "Rocket Skates" 'price 12.75 'color "yellow" })   (define a2 { 'price 15.25 'color "red" 'year 1974 })   (print "a1: " a1) (print "a2: " a2)   (define (collide a b) b) ; will use new key value (print "merged a1 a2: " (ff-union collide a1 a2))  
Give a code snippet in #Ol Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge...
christopher/rosetta-code
http://rosettacode.org/wiki/Honeycombs
Honeycombs
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position...
#Haskell
Haskell
import Data.Char (toUpper) import Data.Function (on) import Data.List (zipWith4) import System.Exit import System.Random   -- External libraries. import Graphics.Gloss import Graphics.Gloss.Data.Vector import Graphics.Gloss.Geometry import Graphics.Gloss.Interface.IO.Game import System.Random.Shuffle   -- A record of a...
Give a code snippet in #Haskell The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#AutoHotkey
AutoHotkey
str = 12345 MsgBox % str += 1
Give a code snippet in #AutoHotkey Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Standard_ML
Standard ML
(* Pairing heap - http://en.wikipedia.org/wiki/Pairing_heap *) functor PairingHeap(type t val cmp : t * t -> order) = struct datatype 'a heap = Empty | Heap of 'a * 'a heap list;   (* merge, O(1) * Merges two heaps *) fun merge (Empty, h) = h | merge (h, Empty) = h ...
Give a code snippet in #Standard_ML 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 | Qu...
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)
#Clojure
Clojure
(defn leap-year? [y] (and (zero? (mod y 4)) (or (pos? (mod y 100)) (zero? (mod y 400)))))
Give a code snippet in #Clojure 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/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Lang5
Lang5
'foo.txt slurp
Give a code snippet in #Lang5 Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#UNIX_Shell
UNIX Shell
if echo 'Looking for file' # This is the evaluation block test -e foobar.fil # The exit code from this statement determines whether the branch runs then echo 'The file exists' # This is the optional branch echo 'I am going to delete it' rm foobar.fil fi
Give a code snippet in #UNIX_Shell Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. The original article was at P...
#PARI.2FGP
PARI/GP
sample(f,a,b)=for(i=1,4, my(n1=random(b-a)+a,n2=random(b-a)+a); [n1,n2]=[max(n1,n2),min(n1,n2)]; print(n1", "n2": "f(n1,n2))) permExact(m,n)=factorback([m-n+1..m]); combExact=binomial; permApprox(m,n)=exp(lngamma(m+1)-lngamma(m-n+1)); combApprox(m,n)=exp(lngamma(m+1)-lngamma(n+1)-lngamma(m-n+1));   sample(permExact, 1,...
Give a code snippet in #PARI.2FGP This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikip...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#PicoLisp
PicoLisp
(de mdr-mp (N) "Returns the solutions in a list, i.e., '(MDR MP)" (let MP 0 (while (< 1 (length N)) (setq N (apply * (mapcar format (chop N)))) (inc 'MP) ) (list N MP) ) )       # Get the MDR/MP of these nums. (setq Test-nums '(123321 7739 893 899998))   (let Fmt (6 5 5) (tab Fmt ...
Give a code snippet in #PicoLisp The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#PHP
PHP
<?php $a = 5 #...input or change $a here assert($a == 42) # when $a is not 42, take appropriate actions, # which is set by assert_options() ?>
Give a code snippet in #PHP Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
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...
#Java
Java
import static java.lang.Math.*;   public class RayCasting {   static boolean intersects(int[] A, int[] B, double[] P) { if (A[1] > B[1]) return intersects(B, A, P);   if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001;   if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0...
Give a code snippet in #Java 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func integer: modInverse (in integer: a, in integer: b) is return ord(modInverse(bigInteger conv a, bigInteger conv b));   const proc: main is func local const array integer: n is [] (3, 5, 7); const array integer: a is [] (2, 3, 2); var integer:...
Give a code snippet in #Seed7 Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displays...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#OCaml
OCaml
open Sem   let () = let oflags = [Unix.O_CREAT; Unix.O_EXCL] in let sem = sem_open "MyUniqueName" ~oflags () in (* here the real code of the app *) Unix.sleep 20; (* end of the app *) sem_unlink "MyUniqueName"; sem_close sem
Give a code snippet in #OCaml This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Run_BASIC
Run BASIC
  result = stepUp()   Function stepUp() While Not(stepp()) result = stepUp() Wend End Function   Function stepp() stepp = int((Rnd(1) * 2)) print "Robot stepped "+word$("up down",stepp+1) End Function  
Give a code snippet in #Run_BASIC From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Batch_File
Batch File
  @echo off :: {CTRL + C} to exit the batch file :: Send incrementing decimal values to the :to_Oct function set loop=0 :loop1 call:to_Oct %loop% set /a loop+=1 goto loop1 :: Convert the decimal values parsed [%1] to octal and output them on a new line :to_Oct set todivide=%1 set "fulloct="   :loop2 set tomod=%todivi...
Give a code snippet in #Batch_File Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reach...
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 ...
#Kotlin
Kotlin
// version 1.1.51   interface Thingable { fun thing(): String? }   class Delegate(val responds: Boolean) : Thingable { override fun thing() = if (responds) "delegate implementation" else null }   class Delegator(d: Delegate) : Thingable by d { fun operation() = thing() ?: "default implementation" }   fun ma...
Give a code snippet in #Kotlin 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#AWK
AWK
$ awk 'BEGIN{for(i=0;i<6;i++){c=1;r=c;for(j=0;j<i;j++){c*=(i-j)/(j+1);r=r" "c};print r}}'
Give a code snippet in #AWK Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1...
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....
#Phix
Phix
with javascript_semantics function sum_digits(integer n, base=10) integer res = 0 while n do res += remainder(n,base) n = floor(n/base) end while return res end function function smith(integer n) sequence p = prime_factors(n,true,-1) if length(p)=1 then return false end if ...
Give a code snippet in #Phix 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#BQN
BQN
Factors ← (1+↕)⊸(⊣/˜0=|)   •Show Factors 12345 •Show Factors 729
Give a code snippet in #BQN 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 Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Pascal
Pascal
package Playing_Card_Deck;   use strict;   @Playing_Card_Deck::suits = qw [Diamonds Clubs Hearts Spades]; @Playing_Card_Deck::pips = qw [Two Three Four Five Six Seven Eight Nine Ten Jack King Queen Ace]; # I choose to fully qualify these names rather than declare them # with "our" to keep them from escaping i...
Give a code snippet in #Pascal Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current ...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, base...
#Scala
Scala
object SimpleDatabase extends App { type Entry = Array[String] def asTSV(e: Entry) = e mkString "\t" def fromTSV(s: String) = s split "\t" val header = asTSV(Array("TIMESTAMP", "DESCRIPTION", "CATEGORY", "OTHER"))   def read(filename: String) = try { scala.io.Source.fromFile(filename).getLines.drop(1).map...
Give a code snippet in #Scala Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#SQL
SQL
  SELECT to_char(sysdate,'YYYY-MM-DD') date_fmt_1 FROM dual;   SELECT to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 FROM dual;  
Give a code snippet in #SQL This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#PL.2FI
PL/I
(stringrange, stringsize): Gray_code: procedure options (main); /* 15 November 2013 */ declare (bin(0:31), g(0:31), b2(0:31)) bit (5); declare (c, carry) bit (1); declare (i, j) fixed binary (7);   bin(0) = '00000'b; do i = 0 to 31; if i > 0 then do; carry = '1'b; ...
Give a code snippet in #PL.2FI Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#C.2B.2B
C++
#include <iostream>   int main() { std::cerr << "Goodbye, World!\n"; }
Give a code snippet in #C.2B.2B Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard ou...
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...
#Objective-C
Objective-C
NSLog(@"%@", @"alphaBETA".uppercaseString); NSLog(@"%@", @"alphaBETA".lowercaseString);   NSLog(@"%@", @"foO BAr".capitalizedString); // "Foo Bar"
Give a code snippet in #Objective-C 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Bracmat
Bracmat
( ( resolution = (x=) (y=) (new=.!arg:(?(its.x),?(its.y))) ) & new$(resolution,640,480):?VGA & new$(resolution,1920,1080):?1080p & out$("VGA: horizontal " !(VGA..x) " vertical " !(VGA..y)));
Give a code snippet in #Bracmat In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the c...
christopher/rosetta-code
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion
Angles (geometric), normalization and conversion
This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 360 degrees, also shown as 360º ...
#Ruby
Ruby
module Angles BASES = {"d" => 360, "g" => 400, "m" => 6400, "r" => Math::PI*2 ,"h" => 24 }   def self.method_missing(meth, angle) from, to = BASES.values_at(*meth.to_s.split("2")) raise NoMethodError, meth if (from.nil? or to.nil?) mod = (angle.to_f * to / from) % to angle < 0 ? mod - to : mod end...
Give a code snippet in #Ruby This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 36...
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...
#Julia
Julia
function nimgame() tcount = 12 takenum = 0 while true while true permitted = collect(1:min(3,tcount)) println("$tcount tokens remain.\nHow many do you take ($permitted)? ") takenum = parse(Int, strip(readline(stdin))) if takenum in permitted ...
Give a code snippet in #Julia Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Nums   var cumStdDev = Fiber.new { |a| for (i in 0...a.count) { var b = a[0..i] System.print("Values  : %(b)") Fiber.yield(Nums.popStdDev(b)) } }   var a = [2, 4, 4, 4, 5, 5, 7, 9] while (true) { var sd = cumStdDev.call(a) if (cumStdDev.i...
Give a code snippet in #Wren 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 functi...
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 |...
#F.C5.8Drmul.C3.A6
Fōrmulæ
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 #F.C5.8Drmul.C3.A6 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...
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 ...
#Go
Go
package main   import ( "fmt" "sort" )   type rankable interface { Len() int RankEqual(int, int) bool }   func StandardRank(d rankable) []float64 { r := make([]float64, d.Len()) var k int for i := range r { if i == 0 || !d.RankEqual(i, i-1) { k = i + 1 } r[i] = float64(k) } return r }   func ModifiedR...
Give a code snippet in #Go 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func string: commatize (in bigInteger: bigNum) is func result var string: stri is ""; local var integer: index is 0; begin stri := str(bigNum); for index range length(stri) - 3 downto 1 step 3 do stri := stri[.. index] & "," & stri[su...
Give a code snippet in #Seed7 Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
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 ...
#Run_BASIC
Run BASIC
sqliteconnect #mem, ":memory:" ' create in memory db mem$ = "CREATE TABLE people(num integer, name text,city text)" #mem execute(mem$) data "1","George","Redding","2","Fred","Oregon","3","Ben","Seneca","4","Steve","Fargo","5","Frank","Houston"   for i = 1 to 5 ...
Give a code snippet in #Run_BASIC Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
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...
#Bracmat
Bracmat
(gcd=a b.!arg:(?a.?b)&!b*den$(!a*!b^-1)^-1);
Give a code snippet in #Bracmat 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/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#MAXScript
MAXScript
fn selectionSort arr = ( local min = undefined for i in 1 to arr.count do ( min = i for j in i+1 to arr.count do ( if arr[j] < arr[min] then ( min = j ) ) swap arr[i] arr[min] ) arr )   data = selectionSort #...
Give a code snippet in #MAXScript Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Clojure
Clojure
(defn van-eck ([] (van-eck 0 0 {})) ([val n seen] (lazy-seq (cons val (let [next (- n (get seen val n))] (van-eck next (inc n) (assoc seen val n)))))))   (println "First 10 terms:" (take 10 (van-eck))) (println "Terms 991 to 1000 terms:" (take 1...
Give a code snippet in #Clojure The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occur...
christopher/rosetta-code
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. 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) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#C.2B.2B
C++
// // C++ implementation of Tarjan's strongly connected components algorithm // See https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm // #include <algorithm> #include <iostream> #include <list> #include <string> #include <vector>   struct noncopyable { noncopyable() {} noncopyable...
Give a code snippet in #C.2B.2B This page uses content from Wikipedia. The original article was at Graph. 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) Tarjan's algorithm is an algorithm in grap...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#Visual_Basic_.NET
Visual Basic .NET
Option Compare Binary Option Explicit On Option Infer On Option Strict On   Imports System.Text.RegularExpressions   #Const USE_REGEX = False   Module Program ' Supports both local and remote files Const WORDLIST_URI = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"     ' The support factor of a word ...
Give a code snippet in #Visual_Basic_.NET The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible...
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 ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "console.s7i"; include "keybd.s7i";   const integer: boardLength is 4; const integer: boardSize is boardLength * boardLength; const integer: target is 2048;   const type: stateType is new struct var integer: fieldsOccupied is 0; var integer: largestNumber is 0; var inte...
Give a code snippet in #Seed7 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/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#PHP
PHP
  <?php function time2ang($tim) { if (!is_string($tim)) return $tim; $parts = explode(':',$tim); if (count($parts)!=3) return $tim; $sec = ($parts[0]*3600)+($parts[1]*60)+$parts[2]; $ang = 360.0 * ($sec/86400.0); return $ang; } function ang2time($ang) { if (!is_nu...
Give a code snippet in #PHP Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Visual_Basic
Visual Basic
Sub AlignCols(Lines, Optional Align As AlignmentConstants, Optional Sep$ = "$", Optional Sp% = 1) Dim i&, j&, D&, L&, R&: ReDim W(UBound(Lines)): ReDim C&(0)   For j = 0 To UBound(W) W(j) = Split(Lines(j), Sep) If UBound(W(j)) > UBound(C) Then ReDim Preserve C(UBound(W(j))) For i = 0 To UBound(W(j)): If L...
Give a code snippet in #Visual_Basic Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be eit...
christopher/rosetta-code
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#Set_lang
Set lang
set ! 32 set ! 32 set ! 46 set ! 45 set ! 126 set ! 34 set ! 34 set ! 126 set ! 45 set ! 46 set ! 10 set ! 46 set ! 39 set ! 40 set ! 95 set ! 41 set ! 32 set ! 32 set ! 32 set ! 32 set ! 32 set ! 39 set ! 46 set ! 10 set ! 124 set ! 61 set ! 61 set ! 61 set ! 61 set ! 61 set ! 61 set ! 61 set ! 61 set ! 61 set ! 61 se...
Give a code snippet in #Set_lang Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#REXX
REXX
/*REXX program displays a power set; items may be anything (but can't have blanks).*/ parse arg S /*allow the user specify optional set. */ if S='' then S= 'one two three four' /*Not specified? Then use the default.*/ @= '{}' ...
Give a code snippet in #REXX A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given ...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Arturo
Arturo
a: {print ["The result is:" 2+3]} do a   userCode: input "Give me some code: " do userCode
Give a code snippet in #Arturo Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applic...
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.
#XPL0
XPL0
code IntOut=11; IntOut(0, 10*9*8*7*6*5*4*3*2);  
Give a code snippet in #XPL0 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/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurren...
#Delphi
Delphi
  program Magic_8_ball;   {$APPTYPE CONSOLE}   uses System.SysUtils, windows;   // https://stackoverflow.com/questions/29794559/delphi-console-xe7-clearscreen procedure ClearScreen; var stdout: THandle; csbi: TConsoleScreenBufferInfo; ConsoleSize: DWORD; NumWritten: DWORD; Origin: TCoord; begin stdout :...
Give a code snippet in #Delphi Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinform...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#Sidef
Sidef
func hashJoin(table1, index1, table2, index2) { var a = [] var h = Hash()   # hash phase table1.each { |s| h{s[index1]} := [] << s }   # join phase table2.each { |r| a += h{r[index2]}.map{[_,r]} }   return a }   var t1 = [[27, "Jonah"], [18, "Alan"], ...
Give a code snippet in #Sidef An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join"...
christopher/rosetta-code
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Factor
Factor
USING: grouping grouping.extras math math.combinatorics math.functions math.primes math.ranges prettyprint sequences sequences.extras ;   9 1 [a,b] all-subsets [ reverse 0 [ 10^ * + ] reduce-index ] [ prime? ] map-filter 10 "" pad-groups 10 group simple-table.
Give a code snippet in #Factor Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
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.
#zkl
zkl
File.info("input.txt").println(); File.info("/input.txt").println();
Give a code snippet in #zkl 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/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#LiveCode
LiveCode
answer the hostName
Give a code snippet in #LiveCode Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#Wren
Wren
import "/fmt" for Fmt   var max = 12 var sp = [] var count = List.filled(max, 0) var pos = 0   var factSum = Fn.new { |n| var s = 0 var x = 0 var f = 1 while (x < n) { x = x + 1 f = f * x s = s + f } return s }   var r // recursive r = Fn.new { |n| if (n == 0) return...
Give a code snippet in #Wren A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use...
christopher/rosetta-code
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Nim
Nim
import os, osproc, strformat, strscans   # Retrieve video modes. let p = startProcess("xrandr", "", ["-q"], nil, {poUsePath}) var currWidth, currHeight = 0 # Current video mode. var width, height = 0 # Some other video mode. for line in p.lines: echo line # Find current display mode, marked by an asteri...
Give a code snippet in #Nim The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_dates
Palindrome dates
Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a program which calculates and shows th...
#Phix
Phix
with javascript_semantics include builtins\timedate.e sequence res = {} for d=2021 to 9999 do string s = sprintf("%4d",d), t = reverse(s) s &= "-"&t[1..2]&"-"&t[3..4] sequence td = parse_date_string(s, {"YYYY-MM-DD"}) if timedate(td) then res = append(res,s) end if end for printf(1,"Count of...
Give a code snippet in #Phix Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a program...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() }   function push(n) { q[length(q)+1] = n return n }   func...
Give a code snippet in #AWK Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the ord...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#M2000_Interpreter
M2000 Interpreter
  \\ ANSI Print Asc("a") Print Chr$(Asc("a")) \\ Utf16-Le Print ChrCode("a") Print ChrCode$(ChrCode("a"))   \\ (,) is an empty array.   Function Codes(a$) { If Len(A$)=0 then =(,) : Exit Buffer Mem as byte*Len(a$) \\ Str$(string) return one byte character Return Mem, 0:=Str$(a$) ...
Give a code snippet in #M2000_Interpreter Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Uni...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Julia
Julia
f() = g() g() = println.(stacktrace())   f()
Give a code snippet in #Julia Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the pl...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#F.23
F#
let jdn (year, month, day) = let a = (14 - month) / 12 let y = year + 4800 - a let m = month + 12 * a - 3 day + (153*m+2)/5 + 365*y + y/4 - y/100 + y/400 - 32045   let date_from_jdn jdn = let j = jdn + 32044 let g = j / 146097 let dg = j % 146097 let c = (dg / 36524 + 1) * 3 / 4 let ...
Give a code snippet in #F.23 Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   [6]STRING rows := []STRING( "Character,Speech", "The multitude,The messiah! Show us the messiah!", "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>", "The multitude,Who are you?", "Brians mother,I'm his ...
Give a code snippet in #ALGOL_68 Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Sidef
Sidef
var f = FIFO(); say f.empty; # true f.push('foo'); f.push('bar', 'baz'); say f.pop; # foo say f.empty; # false   var g = FIFO('xxx', 'yyy'); say g.pop; # xxx say f.pop; # bar
Give a code snippet in #Sidef Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of que...
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 ...
#360_Assembly
360 Assembly
* Combinations 26/05/2016 COMBINE CSECT USING COMBINE,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " ...
Give a code snippet in #360_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Phix
Phix
include pGUI.e IupOpen() IupMessage("Bye","Goodbye, World!") IupClose()
Give a code snippet in #Phix Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ...
#C.2B.2B
C++
#include <chrono> #include <iostream> #include <format> #include <semaphore> #include <thread>   using namespace std::literals;   void Worker(std::counting_semaphore<>& semaphore, int id) { semaphore.acquire(); std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); // response message ...
Give a code snippet in #C.2B.2B The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire,...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#ActionScript
ActionScript
function arabic2roman(num:Number):String { var lookup:Object = {M:1000, CM:900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1}; var roman:String = "", i:String; for (i in lookup) { while (num >= lookup[i]) { roman += i; num -= lookup[i]; } } return roman; } trace("1990 in roman is ...
Give a code snippet in #ActionScript Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#Emacs_Lisp
Emacs Lisp
#!/usr/bin/emacs --script ;; ;; The Rosetta Code lexical analyzer in GNU Emacs Lisp. ;; ;; Migrated from the ATS. However, Emacs Lisp is not friendly to the ;; functional style of the ATS implementation; therefore the ;; differences are vast. ;; ;; (A Scheme migration could easily, on the other hand, have been ;; almos...
Give a code snippet in #Emacs_Lisp Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer,...
christopher/rosetta-code
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#C.23
C#
using System; using BI = System.Numerics.BigInteger; using static System.Console;   class Program {   static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }     static string dump(int digs, bool show = false...
Give a code snippet in #C.23 The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case...
#D
D
import std.stdio, std.range, std.algorithm, std.typecons;   auto eulersSumOfPowers() { enum maxN = 250; auto pow5 = iota(size_t(maxN)).map!(i => ulong(i) ^^ 5).array.assumeSorted;   foreach (immutable x0; 1 .. maxN) foreach (immutable x1; 1 .. x0) foreach (immutable x2; 1 .. x1) ...
Give a code snippet in #D There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#EchoLisp
EchoLisp
  (define distinct-divisors (compose make-set prime-factors))   ;; euler totient : Φ : n / product(p_i) * product (p_i - 1) ;; # of divisors <= n   (define (Φ n) (let ((pdiv (distinct-divisors n))) (/ (* n (for/product ((p pdiv)) (1- p))) (for/product ((p pdiv)) p))))   ;; farey-sequence length |Fn| = 1 + sigma...
Give a code snippet in #EchoLisp The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Fortran
Fortran
module triples implicit none   integer :: max_peri, prim, total integer :: u(9,3) = reshape((/ 1, -2, 2, 2, -1, 2, 2, -2, 3, & 1, 2, 2, 2, 1, 2, 2, 2, 3, & -1, 2, 2, -2, 1, 2, -2, 2, 3 /), & (/ 9, 3 /))   co...
Give a code snippet in #Fortran A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\di...
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...
#Robotic
Robotic
  input string "Enter a number:" set "in" to "('ABS('input')')" if "in" <= 1 then "one" set "result" to 1   : "factorial" set "result" to "('result' * 'in')" dec "in" by 1 if "in" > 1 then "factorial" * "('result')" end   : "one" * "1" end  
Give a code snippet in #Robotic 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Textonyms
Textonyms
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -...
#Haskell
Haskell
import Data.Char (toUpper) import Data.Function (on) import Data.List (groupBy, sortBy) import Data.Maybe (fromMaybe, isJust, isNothing)   toKey :: Char -> Maybe Char toKey ch | ch < 'A' = Nothing | ch < 'D' = Just '2' | ch < 'G' = Just '3' | ch < 'J' = Just '4' | ch < 'M' = Just '5' | ch < 'P' = Just '6' ...
Give a code snippet in #Haskell When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO ...
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.
#VBA
VBA
Private Sub Enjoy() Debug.Print "Enjoy" End Sub Private Sub Rosetta() Debug.Print "Rosetta" End Sub Private Sub Code() Debug.Print "Code" End Sub Public Sub concurrent() when = Now + TimeValue("00:00:01") Application.OnTime when, "Enjoy" Application.OnTime when, "Rosetta" Application.OnTime ...
Give a code snippet in #VBA 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 lan...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#PureBasic
PureBasic
Procedure pascaltriangle( n.i)   For i= 0 To n c = 1 For k=0 To i Print(Str( c)+" ") c = c * (i-k)/(k+1); Next ;k PrintN(" "); nächste zeile Next ;i   EndProcedure   OpenConsole() Parameter.i = Val(ProgramParameter(0)) pascaltriangle(Parameter); Input()
Give a code snippet in #PureBasic Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is ei...
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...
#BASIC256
BASIC256
  Dim x(9) x = {0.654682, 0.409382, 0.891663, 0.716629, 0.477721, 0.925092, 0.624291, 0.211332, 0.293786, 0.839186} Dim y(9) y = {0.925557, 0.619391, 0.888594, 0.996200, 0.946355, 0.818220, 0.142924, 0.221507, 0.691701, 0.728260}   minDist = 1^30 For i = 0 To 8 For j = i+1 To 9 dist = (x[i] - x[j])^2 + (y[i] - y[j])...
Give a code snippet in #BASIC256 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/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Factor
Factor
USING: accessors L-system ui ;   : peano ( L-system -- L-system ) L-parser-dialect >>commands [ 90 >>angle ] >>turtle-values "L" >>axiom { { "L" "LFRFL-F-RFLFR+F+LFRFL" } { "R" "RFLFR+F+LFRFL-F-RFLFR" } } >>rules ;   [ <L-system> peano "Peano curve" open-window ] with-ui
Give a code snippet in #Factor Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth%27s_power_tree
Knuth's power tree
(Knuth's power tree is used for computing   xn   efficiently.) Task Compute and show the list of Knuth's power tree integers necessary for the computation of:   xn   for any real   x   and any non-negative integer   n. Then, using those integers, calculate and show the exact values of (at least) the integer po...
#11l
11l
V p = [1 = 0] V lvl = [[1]]   F path(n) I !n R [Int]() L n !C :p [Int] q L(x) :lvl[0] L(y) path(x) I !(x + y C :p)  :p[x + y] = x q.append(x + y)  :lvl[0] = q   R path(:p[n]) [+] [n]   F tree_pow(x, n) T Ty = T(x) V (r, p) = ([0 = T...
Give a code snippet in #11l (Knuth's power tree is used for computing   xn   efficiently.) Task Compute and show the list of Knuth's power tree integers necessary for the computation of:   xn   for any real   x   and any non-negative integer   n. Then, using those integers, calculate and show the exact values...
christopher/rosetta-code
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#M2000_Interpreter
M2000 Interpreter
  Function KnightTour$(StartW=1, StartH=1){ def boolean swapH, swapV=True if startW<=4 then swapH=true: StartW=8+1-StartW if startH>4 then swapV=False: StartH=8+1-StartH Let final=8*8, last=final-1, HighValue=final+1 Dim Board(1 to 8, 1 to 8), Moves(1 to 8, 1 to 8)=HighValue f=stack:=1,2,3,4,5,6...
Give a code snippet in #M2000_Interpreter Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour ...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Maple
Maple
  1/42 mod 2017;  
Give a code snippet in #Maple From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\...
christopher/rosetta-code
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp...
#Plain_English
Plain English
To run: Start up. Show some example Cistercian numbers. Wait for the escape key. Shut down.   To show some example Cistercian numbers: Put the screen's left plus 1 inch into the context's spot's x. Clear the screen to the lightest gray color. Use the black color. Use the fat pen. Draw 0. Draw 1. Draw 20. Draw 300. Draw...
Give a code snippet in #Plain_English Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by its...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#Oz
Oz
declare fun {IsPangram Xs} {List.sub {List.number &a &z 1} {Sort {Map Xs Char.toLower} Value.'<'}} end in {Show {IsPangram "The quick brown fox jumps over the lazy dog."}}
Give a code snippet in #Oz Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write ...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Quackery
Quackery
[ iff [ say "true" ] else [ say "false"] ] is echobool ( b --> )   [ 2dup and say "A and B is " echobool cr over or say "A or B is " echobool cr not say "not A is " echobool cr ] is task ( A B --> )
Give a code snippet in #Quackery Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#Python
Python
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))   >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, Tru...
Give a code snippet in #Python Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when d...
christopher/rosetta-code