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
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Tcl
Tcl
package require Tcl 8.5   # Generate random point at specified distance from the centre proc getPoint {range from to} { set r2 [expr {$range / 2}] set f2 [expr {$from ** 2}] set t2 [expr {$to ** 2}] while 1 { set x [expr {int($range * rand())}] set y [expr {int($range * rand())}] set d2 [expr {($x-$r...
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Avail
Avail
If year = 1999 then [Print: "Party!";];   If someNumber > 5 then [Print: "Too high!";] else [Print: "Adequate amount.";];   If breed = "Abyssinian" then [score := 150;] else if breed = "Birman" then [score := 70;] else [score := 45;];   Unless char = ¢X then [Print: "character was not an x";];
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Go
Go
package main   import ( "fmt" "regexp" "strings" )   var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`)   func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }   func comm...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Arturo
Arturo
allEqual?: function [lst] -> 1 = size unique lst ascending?: function [lst] -> lst = sort lst   lists: [ ["abc" "abc" "abc"] ["abc" "abd" "abc"] ["abc" "abd" "abe"] ["abc" "abe" "abd"] ]   loop lists 'l [ print ["list:" l] print ["allEqual?" allEqual? l] print ["ascending?" ascending? l "\n"...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#AWK
AWK
  # syntax: GAWK -f COMPARE_A_LIST_OF_STRINGS.AWK BEGIN { main("AA,BB,CC") main("AA,AA,AA") main("AA,CC,BB") main("AA,ACB,BB,CC") main("single_element") exit(0) } function main(list, arr,i,n,test1,test2) { test1 = 1 # elements are identical test2 = 1 # elements are in ascending order ...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#11l
11l
F quibble(words) R S words.len 0 ‘{}’ 1 ‘{’words[0]‘}’ E ‘{’words[0.<(len)-1].join(‘, ’)‘ and ’words.last‘}’   print(quibble([‘’] * 0)) print(quibble([‘ABC’])) print(quibble([‘ABC’, ‘DEF’])) print(quibble([‘ABC’, ‘DEF’, ‘G’, ‘H’]))
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#11l
11l
F combsReps(lst, k) T Ty = T(lst[0]) I k == 0 R [[Ty]()] I lst.empty R [[Ty]]() R combsReps(lst, k - 1).map(x -> @lst[0] [+] x) [+] combsReps(lst[1..], k)   print(combsReps([‘iced’, ‘jam’, ‘plain’], 2)) print(combsReps(Array(1..10), 3).len)
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...
#11l
11l
F perm(=n, p) BigInt r = 1 V k = n - p L n > k r *= n-- R r   F comb(n, =k) V r = perm(n, k) L k > 0 r I/= k-- R r   L(i) 1..11 print(‘P(12,’i‘) = ’perm(12, i)) L(i) (10.<60).step(10) print(‘C(60,’i‘) = ’comb(60, i))
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...
#ALGOL_W
ALGOL W
begin  %lexical analyser %  % Algol W strings are limited to 256 characters in length so we limit source lines %  % and tokens to 256 characters %   integer lineNumber, columnNumber; string(256) line; string(256) tkValue; integer tkType, tkLine, tkColumn, tkLength, tkIntegerValue; l...
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Amazing_Hopper
Amazing Hopper
  #defn main(_V_,_N_) #RAND, main:, V#RNDV=1,_V_={#VOID}, \ _N_=0,totalarg,mov(_N_), \ LOOPGETARG_#RNDV:, {[ V#RNDV ]},push(_V_),++V#RNDV,\ {_N_,V#RNDV},jle(LOOPGETARG_#RNDV),clear(V#RNDV)  
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#AppleScript
AppleScript
  #!/usr/bin/env osascript -- Print first argument on run argv return (item 1 of argv) end run  
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#8086_Assembly
8086 Assembly
MOV AX, 4C00h ; go back to DOS INT 21h ; BIOS interrupt 21 base 16
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* comments multi lines   end comments */   // comment end of ligne  
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#J
J
(opcodes)=: opcodes=: ;:{{)n fetch store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt }}-.LF   unpack=: {{ lines=. <;._2 y 'ds0 ds s0 s'=.;:0{::lines assert.'Datasize:Strings:'-:ds0,s0 vars=: (".ds)#0 strings=: rplc&('\\';'\';'\n';LF)L:0 '"'-.L:0~(1+i.".s){lines obj...
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#Go
Go
package main   import ( "bufio" "encoding/binary" "fmt" "log" "os" "strconv" "strings" )   type NodeType int   const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
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 ...
#JavaScript
JavaScript
  function swap(a, i, j){ var t = a[i] a[i] = a[j] a[j] = t }   // Heap Sort   function heap_sort(a){ var n = a.length   function heapify(i){ var t = a[i] while (true){ var l = 2 * i + 1, r = l + 1 var m = r < n ? (a[l] > a[r] ? l : r) : (l < n ? l : i) ...
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) de...
#Scheme
Scheme
  (import (scheme base) (scheme file) (scheme process-context) (scheme write) (only (srfi 13) string-delete string-index string-trim))   ;; Mappings from operation symbols to internal procedures. ;; We define operations appropriate to virtual machine: ;; e.g. division must return an int,...
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Haskell
Haskell
task s1 s2 = do let strs = if length s1 > length s2 then [s1, s2] else [s2, s1] mapM_ (\s -> putStrLn $ show (length s) ++ "\t" ++ show s) strs
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#J
J
NB. solution NB. `Haruno-umi Hinemosu-Notari Notarikana' NB. Spring ocean ; Swaying gently ; All day long. ,/ _2 }.\ ": (;~ #)&> <@(7&u:);._2 '春の海 ひねもすのたり のたりかな ' │3│春の海 │ │7│ひねもすのたり│ │5│のたりかな │ NB. # y is the tally of items (penultimate dimension) in the ar...
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#Nim
Nim
import ast_lexer   type NodeKind* = enum nIdentifier = "Identifier" nString = "String" nInteger = "Integer" nSequence = "Sequence" nIf = "If" nPrtc = "Prtc" nPrts = "Prts" ...
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#COBOL
COBOL
identification division. program-id. game-of-life-program. data division. working-storage section. 01 grid. 05 cell-table. 10 row occurs 5 times. 15 cell pic x value space occurs 5 times. 05 next-gen-cell-table. 10 next-gen-row occurs 5 times. 15 next-gen-cell pic x occu...
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#PureBasic
PureBasic
Structure MyPoint x.i y.i EndStructure
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Python
Python
X, Y = 0, 1 p = (3, 4) p = [3, 4]   print p[X]
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "random" for Random   class Game { static init() { Window.title = "Constrained random points on a circle" var width = 800 var height = 800 Window.resize(width, height) Canvas.resize(width, height) var...
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#AWK
AWK
if(i<0) i=0; else i=42
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Haskell
Haskell
#!/usr/bin/env runhaskell   import Control.Monad (forM_) import Data.Char (isDigit) import Data.List (intercalate) import Data.Maybe (fromMaybe)   {- I use the suffix "2" in identifiers in place of the more conventional prime (single quote character), because Rosetta Code's syntax highlighter still doesn't handle prime...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#BQN
BQN
AllEq ← ⍋≡⍒ Asc ← ¬∘AllEq∧∧≡⊢   •Show AllEq ⟨"AA", "AA", "AA", "AA"⟩ •Show Asc ⟨"AA", "AA", "AA", "AA"⟩   •Show AllEq ⟨"AA", "ACB", "BB", "CC"⟩ •Show Asc ⟨"AA", "ACB", "BB", "CC"⟩
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Bracmat
Bracmat
(test1=first.~(!arg:%@?first ? (%@:~!first) ?)) & (test2=x.~(!arg:? %@?x (%@:~>!x) ?))
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#360_Assembly
360 Assembly
* Comma quibbling 13/03/2017 COMMAQUI CSECT USING COMMAQUI,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Given a list of strings in HL, and a pointer in DE, write ;; the resulting string starting at DE. quibble: mvi a,'{' ; Write the first {, stax d inx d ; And increment the pointer push h ; Keep start of list call s...
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#360_Assembly
360 Assembly
* Combinations with repetitions - 16/04/2019 COMBREP CSECT USING COMBREP,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ...
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Action.21
Action!
PROC PrintComb(BYTE ARRAY c BYTE len) BYTE i,ind   FOR i=0 TO len-1 DO IF i>0 THEN Put('+) FI ind=c(i) IF ind=0 THEN Print("iced") ELSEIF ind=1 THEN Print("jam") ELSE Print("plain") FI OD PutE() RETURN   BYTE FUNC NotDecreasing(BYTE ARRAY c BYTE len) BYTE i   IF l...
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...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   COMMENT REQUIRED by "prelude_combinations_and_permutations.a68" CO MODE CPINT = #LONG# ~; MODE CPOUT = #LONG# ~; # the answer, can be REAL # MODE CPREAL = ~; # the answer, can be REAL # PROC cp fix value error = (#REF# CPARGS args)BOOL: ~; #PROVIDES:# # OP C = (CP~,CP~)CP~: ~ # # OP ...
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...
#ATS
ATS
(********************************************************************) (* Usage: lex [INPUTFILE [OUTPUTFILE]] If INPUTFILE or OUTPUTFILE is "-" or missing, then standard input or standard output is used, respectively. *)   #define ATS_DYNLOADFLAG 0   #include "share/atspre_staload.hats" staload UN = "prelude/SATS...
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program commandLine.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szCarriageReturn: .asciz "\n" ...
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#ACL2
ACL2
; Single line comment #| Multi-line comment |#
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Action.21
Action!
;This is a comment   PROC Main() ;This is a comment as well RETURN
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Julia
Julia
mutable struct VM32 code::Vector{UInt8} stack::Vector{Int32} data::Vector{Int32} strings::Vector{String} offsets::Vector{Int32} lastargs::Vector{Int32} ip::Int32 VM32() = new(Vector{UInt8}(), Vector{Int32}(), Vector{Int32}(), Vector{String}(), Vector{Int32}(), Vector{Int...
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#J
J
require'format/printf'   (opcodes)=: opcodes=: ;:{{)n fetch store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt }}-.LF   (ndDisp)=: ndDisp=:;:{{)n Sequence Multiply Divide Mod Add Subtract Negate Less LessEqual Greater GreaterEqual Equal NotEqual Not And Or Prts Assign Prti x ...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
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 ...
#Julia
Julia
  function comparesorts(tosort) a = shuffle(["i", "m", "q"]) iavg = mavg = qavg = 0.0 for c in a if c == "i" iavg = sum(i -> @elapsed(sort(tosort, alg=InsertionSort)), 1:100) / 100.0 elseif c == "m" mavg = sum(i -> @elapsed(sort(tosort, alg=MergeSort)), 1:100) / 100.0...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
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 ...
#Kotlin
Kotlin
// Version 1.2.31   import java.util.Random import kotlin.system.measureNanoTime   typealias Sorter = (IntArray) -> Unit   val rand = Random()   fun onesSeq(n: Int) = IntArray(n) { 1 }   fun ascendingSeq(n: Int) = shuffledSeq(n).sorted().toIntArray()   fun shuffledSeq(n: Int) = IntArray(n) { 1 + rand.nextInt(10 * n) } ...
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) de...
#Wren
Wren
import "/dynamic" for Enum, Struct, Tuple import "/fmt" for Conv import "/ioutil" for FileUtil   var nodes = [ "Ident", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Mul", "Div", "Mod", "Add", "Sub"...
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Java
Java
package stringlensort;   import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator;   public class ReportStringLengths {   public static void main(String[] args) { String[] list = {"abcd", "123456789", "abcdef", "1234567"}; String[] strings = args.length > 0 ? args : list;   ...
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#ObjectIcon
ObjectIcon
# -*- ObjectIcon -*- # # The Rosetta Code Tiny-Language Parser, in Object Icon. # # This implementation is based closely on the pseudocode and the C # reference implementation. #   import io   record token_record (line_no, column_no, tok, tokval) record token_getter (nxt, curr)   procedure main (args) local inpf_name...
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Common_Lisp
Common Lisp
(defun next-life (array &optional results) (let* ((dimensions (array-dimensions array)) (results (or results (make-array dimensions :element-type 'bit)))) (destructuring-bind (rows columns) dimensions (labels ((entry (row col) "Return array(row,col) for valid (row,col) else 0." ...
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#QB64
QB64
Type Point x As Double y As Double End Type   Dim p As Point p.x = 15.42 p.y = 2.412   Print p.x; p.y
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Quackery
Quackery
  [ ' [ 0 0 ] ] is point ( --> [ )   [ 0 ] is x ( --> n )   [ 1 ] is y ( --> n )   point dup x peek echo cr 99 swap y poke y peek echo cr
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int X, Y, C, R2; [SetVid($13); \set 320x200x8 graphics mode C:= 0; \initialize point counter repeat X:= Ran(31)-15; \range -15..+15 Y:= Ran(31)-15; R2:= X*X + Y*Y; if R2>=10*10 & R2<=15*15 then [Po...
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Axe
Axe
If 1 YEP() End
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#J
J
require'regex' commatize=:3 :0"1 L:1 0 (i.0) commatize y : NB. deal with all those rules about options opts=. boxopen x char=. (#~ ' '&=@{.@(0&#)@>) opts num=. ;opts-.char delim=. 0 {:: char,<',' 'begin period'=. _1 0+2{.num,(#num)}.1 3 NB. initialize prefix=. begin {.y text=. begin }. y NB. process '...
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Java
Java
import java.io.File; import java.util.*; import java.util.regex.*;   public class CommatizingNumbers {   public static void main(String[] args) throws Exception { commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " ");   commatize("The aut...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#C
C
#include <stdbool.h> #include <string.h>   static bool strings_are_equal(const char **strings, size_t nstrings) { for (size_t i = 1; i < nstrings; i++) if (strcmp(strings[0], strings[i]) != 0) return false; return true; }   static bool strings_are_in_ascending_order(const char **strings, siz...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#C.23
C#
public static (bool lexicallyEqual, bool strictlyAscending) CompareAListOfStrings(List<string> strings) => strings.Count < 2 ? (true, true) : ( strings.Distinct().Count() < 2, Enumerable.Range(1, strings.Count - 1).All(i => string.Compare(strings[i-1], strings[i]) < 0) );
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Action.21
Action!
DEFINE PTR="CARD"   PROC Append(CHAR ARRAY text,suffix) BYTE POINTER srcPtr,dstPtr BYTE len   len=suffix(0) IF text(0)+len>255 THEN len=255-text(0) FI IF len THEN srcPtr=suffix+1 dstPtr=text+text(0)+1 MoveBlock(dstPtr,srcPtr,len) text(0)==+suffix(0) FI RETURN   PROC Quibble(PTR ARRAY i...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Ada
Ada
with Ada.Text_IO, Ada.Command_Line; use Ada.Command_Line;   procedure Comma_Quibble is   begin case Argument_Count is when 0 => Ada.Text_IO.Put_Line("{}"); when 1 => Ada.Text_IO.Put_Line("{" & Argument(1) & "}"); when others => Ada.Text_IO.Put("{"); for I in 1 .. Argument_Count-2 loop Ada...
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Ada
Ada
with Ada.Text_IO; procedure Combinations is   generic type Set is (<>); function Combinations (Count  : Positive; Output : Boolean := False) return Natural;   function Combinations (Count  : Positive; Output : Boolean := False) return Natural is package Set_...
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...
#Bracmat
Bracmat
( ( C = n k coef .  !arg:(?n,?k) & (!n+-1*!k:<!k:?k|) & 1:?coef & whl ' ( !k:>0 & !coef*!n*!k^-1:?coef & !k+-1:?k & !n+-1:?n ) & !coef ) & ( P = n k result .  !arg:(?n,?k) & !n+-1*!k:?k & 1:?result & whl ...
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...
#C
C
#include <gmp.h>   void perm(mpz_t out, int n, int k) { mpz_set_ui(out, 1); k = n - k; while (n > k) mpz_mul_ui(out, out, n--); }   void comb(mpz_t out, int n, int k) { perm(out, n, k); while (k) mpz_divexact_ui(out, out, k--); }   int main(void) { mpz_t x; mpz_init(x);   perm(x, 1000, 969); gmp_printf("P(1000...
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...
#AWK
AWK
  BEGIN { all_syms["tk_EOI" ] = "End_of_input" all_syms["tk_Mul" ] = "Op_multiply" all_syms["tk_Div" ] = "Op_divide" all_syms["tk_Mod" ] = "Op_mod" all_syms["tk_Add" ] = "Op_add" all_syms["tk_Sub" ] = "Op_subtract" all_syms["tk_Negate" ] = "Op_negate" all_syms["tk_Not" ] = "Op_not" ...
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Arturo
Arturo
loop arg 'a [ print a ]
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#AutoHotkey
AutoHotkey
Loop %0% ; number of parameters params .= %A_Index% . A_Space If params != MsgBox, %0% parameters were passed:`n`n %params% Else Run, %A_AhkPath% "%A_ScriptFullPath%" -c "\"alpha beta\"" -h "\"gamma\""
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#ActionScript
ActionScript
-- All Ada comments begin with "--" and extend to the end of the line
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Ada
Ada
-- All Ada comments begin with "--" and extend to the end of the line
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#M2000_Interpreter
M2000 Interpreter
  Module Virtual_Machine_Interpreter (a$){ \\ function to extract string, replacing escape codes. Function GetString$(a$) { s=instr(a$, chr$(34)) m=rinstr(a$,chr$(34))-s if m>1 then \\ process escape codes =format$(mid$(a$, s+1, m-1)) else ="" end if } \\ module to print a string to console using...
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#Java
Java
package codegenerator;   import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner;   public class CodeGenerator { final static int WORDSIZE = 4;   static byte[] code = {};   static Map<String, No...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[BubbleSort,ShellSort] BubbleSort[in_List]:=Module[{x=in,l=Length[in],swapped},swapped=True; While[swapped,swapped=False; Do[If[x[[i]]>x[[i+1]],x[[{i,i+1}]]//=Reverse; swapped=True;],{i,l-1}];]; x] ShellSort[lst_]:=Module[{list=lst,incr,temp,i,j},incr=Round[Length[list]/2]; While[incr>0,For[i=incr+1,i<=Leng...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
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 ...
#Nim
Nim
import algorithm import random import sequtils import times     #################################################################################################### # Data.   proc oneSeq(n: int): seq[int] = repeat(1, n)   #-------------------------------------------------------------------------------------------------...
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) de...
#Zig
Zig
  const std = @import("std");   pub const ASTInterpreterError = error{OutOfMemory};   pub const ASTInterpreter = struct { output: std.ArrayList(u8), globals: std.StringHashMap(NodeValue),   const Self = @This();   pub fn init(allocator: std.mem.Allocator) Self { return ASTInterpreter{ ...
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#JavaScript
JavaScript
/** * Compare and report strings lengths. * * @param {Element} input - a TextArea DOM element with input * @param {Element} output - a TextArea DOM element for output */ function compareStringsLength(input, output) {   // Safe defaults. // output.value = ""; let output_lines = [];   // Split input into ...
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#Perl
Perl
#!/usr/bin/perl   use strict; # parse.pl - inputs lex, outputs flattened ast use warnings; # http://www.rosettacode.org/wiki/Compiler/syntax_analyzer   my $h = qr/\G\s*\d+\s+\d+\s+/; # header of each line   sub error { die "*** Expected @_ at " . (/\G(.*\n)/ ? $1 =~ s/^\s*(\d+)\s+(\d+)\s+/line $1 character $2 got ...
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#D
D
import std.stdio, std.string, std.algorithm, std.array, std.conv;   struct GameOfLife { enum Cell : char { dead = ' ', alive = '#' } Cell[][] grid, newGrid;   this(in int x, in int y) pure nothrow @safe { grid = new typeof(grid)(y + 2, x + 2); newGrid = new typeof(grid)(y + 2, x + 2); }   void opIndex...
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#R
R
mypoint <- list(x=3.4, y=6.7) # $x # [1] 3.4 # $y # [1] 6.7 mypoint$x # 3.4   list(a=1:10, b="abc", c=runif(10), d=list(e=1L, f=TRUE)) # $a # [1] 1 2 3 4 5 6 7 8 9 10 # $b # [1] "abc" # $c # [1] 0.64862897 0.73669435 0.11138945 0.10408015 0.46843836 0.32351247 # [7] 0.20528914 0.78512472 0.06139691 0.7693...
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Racket
Racket
  #lang racket (struct point (x y))  
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#zkl
zkl
xy:=(0).walker(*).tweak(fcn{ // generate infinite random pairs (lazy) x:=(-15).random(16); y:=(-15).random(16); if(not (100<=(x*x + y*y)<=225)) Void.Skip else T(x,y) });   const N=31; // [-15..15] includes 0 array:=(" ,"*N*N).split(",").copy(); // bunch of spaces (list)   xy.walk(100).apply2(fcn([(x,y)],array...
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Babel
Babel
  "foo" "bar" 3 4 > sel <<  
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Julia
Julia
input = [ ["pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 5], [raw"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "."], [raw"-in Aus$+1411.8millions"], [raw"===US$0017440 millions=== (in 2000 dollars)"], ["123.e8000 is pretty big."], ["The l...
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the prog...
#Kotlin
Kotlin
// version 1.1.4-3   val r = Regex("""(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)""")   fun String.commatize(startIndex: Int = 0, period: Int = 3, sep: String = ","): String { if ((startIndex !in 0 until this.length) || period < 1 || sep == "") return this val m = r.find(this, startIndex) if (m == null) return thi...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#C.2B.2B
C++
#include <algorithm> #include <string>   // Bug: calling operator++ on an empty collection invokes undefined behavior. std::all_of( ++(strings.begin()), strings.end(), [&](std::string a){ return a == strings.front(); } ) // All equal   std::is_sorted( strings.begin(), strings.end(), [](std...
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Clojure
Clojure
    ;; Checks if all items in strings list are equal (returns true if list is empty) (every? (fn [[a nexta]] (= a nexta)) (map vector strings (rest strings))))   ;; Checks strings list is in ascending order (returns true if list is empty) (every? (fn [[a nexta]] (<= (compare a nexta) 0)) (map vector strings (rest strin...
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#ALGOL_68
ALGOL 68
# returns a string ( assumed to be of space-separated words ) with the words # # separated by ", ", except for the last which is separated from the rest by # # " and ". The list is enclosed by braces # PROC to list = ( STRING words ) STRING: BEGIN # count the number of ...
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#AppleScript
AppleScript
--------------- COMBINATIONS WITH REPETITION -------------   -- combinationsWithRepetition :: Int -> [a] -> [kTuple a] on combinationsWithRepetition(k, xs) -- A list of lists, representing -- sets of cardinality k, with -- members drawn from xs.   script combinationsBySize script f ...
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...
#C.2B.2B
C++
#include <boost/multiprecision/gmp.hpp> #include <iostream>   using namespace boost::multiprecision;   mpz_int p(uint n, uint p) { mpz_int r = 1; mpz_int k = n - p; while (n > k) r *= n--; return r; }   mpz_int c(uint n, uint k) { mpz_int r = p(n, k); while (k) r /= k--; retu...
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...
#Common_Lisp
Common Lisp
(defun combinations (n k) (cond ((or (< n k) (< k 0) (< n 0)) 0) ((= k 0) 1) (t (do* ((i 1 (1+ i)) (m n (1- m)) (a m (* a m)) (b i (* b i))) ((= i k) (/ a b))))))   (defun permutations (n k) (cond ((or (< n k) (< k 0) (< n 0)) 0) ((= k 0) 1) (t (do* ((i 1 (1+ i)) (m n (1- m)) (a m (* a m)...
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...
#C
C
#include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <ctype.h> #include <string.h> #include <errno.h> #include <stdbool.h> #include <limits.h>   #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))   #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _...
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { print "There are " ARGC "command line parameters" for(l=1; l<ARGC; l++) { print "Argument " l " is " ARGV[l] } }
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Babel
Babel
babel -i Larry Mo Curly
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Agena
Agena
# single line comment   #/ multi-line comment - ends with the "/ followed by #" terminator on the next line /#   /* multi-line comment - C-style - ends with the "* followed by /" terminator on the next line */
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#ALGOL_60
ALGOL 60
  'COMMENT' this is a first comment; 'COMMENT' ****** this is a second comment ****** ;  
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Mercury
Mercury
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% %%% The Rosetta Code Virtual Machine, in Mercury. %%% %%% (This particular machine is arbitrarily chosen to be big-endian.) %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   :- module vm.   :- interface. :- import_modu...
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#Julia
Julia
import Base.show   mutable struct Asm32 offset::Int32 code::String arg::Int32 targ::Int32 end Asm32(code, arg = 0) = Asm32(0, code, arg, 0)   show(io::IO, a::Asm32) = print(io, lpad("$(a.offset)", 6), lpad(a.code, 8), a.targ > 0 ? (lpad("($(a.arg))", 8) * lpad("$(a.targ)", 4)) : (a.code in ["sto...
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
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 ...
#Phix
Phix
-- demo\rosetta\Compare_sorting_algorithms.exw constant XQS = 01 -- (set to 1 to exclude quick_sort and shell_sort from ones) include pGUI.e Ihandle dlg, tabs, plot Ihandles plots function quick_sort2(sequence x) integer n = length(x) if n<2 then return x -- already sorted (trivial case) e...
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) de...
#zkl
zkl
const{ var _n=-1; var[proxy]N=fcn{ _n+=1 }; } // enumerator const FETCH=N, STORE=N, PUSH=N, ADD=N, SUB=N, MUL=N, DIV=N, MOD=N, LT=N, GT=N, LE=N, GE=N, EQ=N, NE=N, AND=N, OR=N, NEG=N, NOT=N, JMP=N, JZ=N, PRTC=N, PRTS=N, PRTI=N, HALT=N; const nd_String=N, nd_Sequence=N, nd_If...
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Julia
Julia
s = "niño" println("Position Char Bytes\n==============================") for (i, c) in enumerate(s) println("$i $c $(sizeof(c))") end  
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#jq
jq
  def s1: "longer"; def s2: "shorter😀";   [s1,s2] | sort_by(length) | reverse[] | "\"\(.)\" has length (codepoints) \(length) and utf8 byte length \(utf8bytelength)."    
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#Phix
Phix
-- -- demo\rosetta\Compiler\parse.e -- ============================= -- -- The reusable part of parse.exw -- with javascript_semantics include lex.e sequence tok procedure errd(sequence msg, sequence args={}) {tok_line,tok_col} = tok error(msg,args) end procedure global sequence toks integer next_tok = 1 f...
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Dart
Dart
/** * States of a cell. A cell is either [ALIVE] or [DEAD]. * The state contains its [symbol] for printing. */ class State { const State(this.symbol);   static final ALIVE = const State('#'); static final DEAD = const State(' ');   final String symbol; }   /** * The "business rule" of the game. Depending on the...
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Raku
Raku
my @point = 3, 8;   my Int @point = 3, 8; # or constrain to integer elements
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#REXX
REXX
x= -4.9 y= 1.7   point=x y
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 FOR i=1 TO 1000 20 LET x=RND*31-16 30 LET y=RND*31-16 40 LET r=SQR (x*x+y*y) 50 IF (r>=10) AND (r<=15) THEN PLOT 127+x*2,88+y*2 60 NEXT i
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#BASIC
BASIC
10 LET A%=1: REM A HAS A VALUE OF TRUE 20 IF A% THEN PRINT "A IS TRUE" 30 WE CAN OF COURSE USE EXPRESSIONS 40 IF A%<>0 THEN PRINT "A IS TRUE" 50 IF NOT(A%) THEN PRINT "A IS FALSE" 60 REM SOME VERSIONS OF BASIC PROVIDE AN ELSE KEYWORD 70 IF A% THEN PRINT "A IS TRUE" ELSE PRINT "A IS FALSE"