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/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...
#Ada
Ada
-- -- The Rosetta Code Virtual Machine, in Ada. -- -- It is assumed the platform on which this program is run -- has two's-complement integers. (Otherwise one could modify -- the vmint_to_vmsigned and vmsigned_to_vmint functions. But -- the chances your binary integers are not two's-complement -- seem pretty low.) --  ...
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...
#COBOL
COBOL
>>SOURCE FORMAT IS FREE identification division. *> this code is dedicated to the public domain *> (GnuCOBOL) 2.3-dev.0 program-id. astinterpreter. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 program-name pic x(32) value spaces glo...
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...
#ATS
ATS
(********************************************************************) (* Usage: parse [INPUTFILE [OUTPUTFILE]] If INPUTFILE or OUTPUTFILE is "-" or missing, then standard input or standard output is used, respectively. *)   #include "share/atspre_staload.hats" staload UN = "prelude/SATS/unsafe.sats"   #define NI...
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...
#AWK
AWK
  BEGIN { c=220; d=619; i=10000; printf("\033[2J"); # Clear screen while(i--) m[i]=0; while(d--) m[int(rand()*1000)]=1;   while(c--){ for(i=52; i<=949; i++){ d=m[i-1]+m[i+1]+m[i-51]+m[i-50]+m[i-49]+m[i+49]+m[i+50]+m[i+51]; n[i]=m[i]; if(m[i]==0 && d==3) n[i]=1; else if(m[i]==1 && d<2) n[i]=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...
#MAXScript
MAXScript
struct myPoint (x, y) newPoint = myPoint x:3 y:4
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...
#MiniScript
MiniScript
Point = {} Point.x = 0 Point.y = 0
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Smalltalk
Smalltalk
|s1 s2| "bind the var s1 to the object string on the right" s1 := 'i am a string'. "bind the var s2 to the same object..." s2 := s1. "bind s2 to a copy of the object bound to s1" s2 := (s1 copy).
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#SNOBOL4
SNOBOL4
  * copy a to b b = a = "test" output = a output = b * change the copy b "t" = "T" output = b end
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...
#Racket
Racket
#lang racket   (require plot plot/utils)   (plot (points (for*/lists (result) ([_ (in-naturals)] #:break (= 100 (length result)) [xy (in-value (v- (vector (random 31) (random 31)) #(15 15)))] #:when (<= 10 (vmag xy) 15...
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.
#Sidef
Sidef
var a = <Enjoy Rosetta Code>   a.map{|str| { Sys.sleep(1.rand) say str }.fork }.map{|thr| thr.wait }
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.
#Swift
Swift
import Foundation   let myList = ["Enjoy", "Rosetta", "Code"]   for word in myList { dispatch_async(dispatch_get_global_queue(0, 0)) { NSLog(word) } }   dispatch_main()
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.
#Standard_ML
Standard ML
structure TTd = Thread.Thread ; structure TTm = Thread.Mutex  ;   val threadedStringList = fn tasks:string list => let val mx = TTm.mutex () ; val taskstore = ref tasks ; fun makeFastRand () = Real.rem (Time.toReal (Time.now ()),1.0) val doTask = fn () => let val mytask : string ref ...
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 ...
#ALGOL_60
ALGOL 60
expression::= if conditional_expression then expression else expression K:=if X=Y then I else J
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...
#Aime
Aime
integer n, pc, sp; file f; text s; index code, Data; list l, stack, strings;   f.affix(argv(1));   f.list(l, 0);   n = atoi(l[-1]); while (n) { f.lead(s); strings.append(erase(s, -1, 0)); n -= 1; }   while (f.list(l, 0) ^ -1) { code.put(atoi(lf_x_text(l)), l); }   pc = sp = 0; while (1) { l = code[p...
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...
#Forth
Forth
CREATE BUF 0 , \ single-character look-ahead buffer : PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ; : GETC PEEK 0 BUF ! ; : SPACE? DUP BL = SWAP 9 14 WITHIN OR ; : >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ; : DIGIT? 48 58 WITHIN ; : GETINT >SPACE 0 BEGIN PEEK DIGIT? WHILE GETC [CHA...
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...
#AWK
AWK
  function Token_assign(tk, attr, attr_array, n, i) { n=split(attr, attr_array) for(i=1; i<=n; i++) Tokens[tk,i-1] = attr_array[i] }   #*** show error and exit function error(msg) { printf("(%s, %s) %s\n", err_line, err_col, msg) exit(1) }   function gettok( line, n, i) { getline line if (line...
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...
#Axe
Axe
Full   While getKey(0) End   ClrDraw .BLINKER Pxl-On(45,45) Pxl-On(46,45) Pxl-On(47,45)   .GLIDER Pxl-On(1,1) Pxl-On(2,2) Pxl-On(2,3) Pxl-On(3,1) Pxl-On(3,2)   Repeat getKey(0) DispGraph EVOLVE() RecallPic ClrDrawʳ End Return   Lbl EVOLVE For(Y,0,63) For(X,0,95) 0→N For(B,Y-1,Y+1) For(A,X-1,X+1) pxl-Tes...
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...
#Modula-2
Modula-2
TYPE Point = RECORD x, y : INTEGER END;
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...
#Modula-3
Modula-3
TYPE Point = RECORD x, y: INTEGER; END;
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Standard_ML
Standard ML
val src = "Hello"; val srcCopy = CharArray.array (size src, #"x"); (* 'x' is just dummy character *) CharArray.copyVec {src = src, dst = srcCopy, di = 0}; src = CharArray.vector srcCopy; (* evaluates to true *)
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Swift
Swift
var src = "Hello" var dst = src
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...
#Raku
Raku
my @range = -15..16;   my @points = gather for @range X @range -> ($x, $y) { take [$x,$y] if 10 <= sqrt($x*$x+$y*$y) <= 15 } my @samples = @points.roll(100); # or .pick(100) to get distinct points   # format and print my %matrix; for @range X @range -> ($x, $y) { %matrix{$y}{$x} = ' ' } %matrix{.[1]}{.[0]} = '*' fo...
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.
#Tcl
Tcl
after [expr int(1000*rand())] {puts "Enjoy"} after [expr int(1000*rand())] {puts "Rosetta"} after [expr int(1000*rand())] {puts "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.
#UnixPipes
UnixPipes
(echo "Enjoy" & echo "Rosetta"& echo "Code"&)
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#ALGOL_68
ALGOL 68
begin integer a, b, c;   a := 1; b := 2; c := 3;    % algol W has the traditional Algol if-the-else statement  %  % there is no "elseif" contraction  % if a = b then write( "a = b" ) else if a = c then write( "a = c" ) else w...
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...
#ALGOL_W
ALGOL W
begin % virtual machine interpreter %  % string literals % string(256) array stringValue ( 0 :: 256 ); integer array stringLength ( 0 :: 256 ); integer MAX_STRINGS;  % op codes % integer oFetch, oStore, oPush , oAdd, oSub, oMul, oDiv, oMod, oLt, oGt, oLe, oGe, ...
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...
#Fortran
Fortran
!!! !!! An implementation of the Rosetta Code interpreter task: !!! https://rosettacode.org/wiki/Compiler/AST_interpreter !!! !!! The implementation is based on the published pseudocode. !!!   module compiler_type_kinds use, intrinsic :: iso_fortran_env, only: int32 use, intrinsic :: iso_fortran_env, only: int64   ...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdbool.h> #include <ctype.h>   #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))   typedef enum { tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, tk_Geq, tk_Eql, tk_Neq, tk_Assig...
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...
#BASIC
BASIC
# Conway's_Game_of_Life   X = 59 : Y = 35 : H = 4   fastgraphics graphsize X*H,Y*H   dim c(X,Y) : dim cn(X,Y) : dim cl(X,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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   class RCompoundDataType method main(args = String[]) public static pp = Point(2, 4) say pp return   class RCompoundDataType.Point -- inner class "Point" properties indirect -- have NetRexx create getters & setters x = Int...
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...
#Nim
Nim
type Point = tuple[x, y: int]   var p: Point = (12, 13) var p2: Point = (x: 100, y: 200)
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Tcl
Tcl
set src "Rosetta Code" set dst $src
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#TI-83_BASIC
TI-83 BASIC
:"Rosetta Code"→Str1 :Str1→Str2
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...
#REXX
REXX
/*REXX program generates 100 random points in an annulus: 10 ≤ √(x²≤y²) ≤ 15 */ parse arg pts LO HI . /*obtain optional args from the C.L. */ if pts=='' then pts= 100 /*Not specified? Then use the default.*/ if LO=='' then LO= 10; LO2= LO**2...
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 ...
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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Threading   Module Module1 Public rnd As New Random   Sub Main() Dim t1 As New Thread(AddressOf Foo) Dim t2 As New Thread(AddressOf Foo) Dim t3 As New Thread(AddressOf Foo)   t1.Start("Enjoy") t2.Start("Rosetta") t3.Start("Code")   t1.Join() t...
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 ...
#ALGOL_W
ALGOL W
begin integer a, b, c;   a := 1; b := 2; c := 3;    % algol W has the traditional Algol if-the-else statement  %  % there is no "elseif" contraction  % if a = b then write( "a = b" ) else if a = c then write( "a = c" ) else w...
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#ATS
ATS
(* Usage: vm [INPUTFILE [OUTPUTFILE]] If INPUTFILE or OUTPUTFILE is "-" or missing, then standard input or standard output is used, respectively.   The Rosetta Code virtual machine task in ATS2 (also known as Postiats).   Some implementation notes:   * Values are stored as uint32, and it is checke...
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...
#Go
Go
package main   import ( "bufio" "fmt" "log" "os" "strconv" "strings" )   type NodeType int   const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod n...
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 |...
#Ada
Ada
with ada.command_line, ada.containers.indefinite_vectors, ada.text_io; procedure compare_lengths is package string_vector is new ada.containers.indefinite_vectors (index_type => Positive, element_type => String);   function "<" (left, right : String) return Boolean is begin return left'length > righ...
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...
#COBOL
COBOL
>>SOURCE FORMAT IS FREE identification division. *> this code is dedicated to the public domain *> (GnuCOBOL) 2.3-dev.0 *> for extra credit, generate this program directly from the EBNF program-id. parser. environment division. configuration section. repository. function all intrinsic. input-output section. fi...
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...
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion   if "%1"=="" ( call:_blinkerArray ) else ( call:_randomArray %* )   for /l %%i in (1,1,%iterations%) do ( call:_setStatus call:_display   for /l %%m in (1,1,%m%) do ( for /l %%n in (1,1,%m%) do ( call:_evolution %%m %%n ) ) )   :_blinkerArray for /l...
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...
#Oberon-2
Oberon-2
  MODULE Point; TYPE Object* = POINTER TO ObjectDesc; ObjectDesc* = RECORD x-,y-: INTEGER; END;   PROCEDURE (p: Object) Init(x,y: INTEGER); BEGIN p.x := x; p.y := y END Init;   PROCEDURE New*(x,y: INTEGER): Object; VAR p: Object; BEGIN NEW(p);p.Init(x,y);RETURN p; END New;   END Point.  
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...
#Objeck
Objeck
  class Point { @x : Int; @y : Int;   New() { @x := 0; @y := 0; }   New(x : Int, y : Int) { @x := x; @y := y; }   New(p : Point) { @x := p->GetX(); @y := p->GetY(); }   method : public : GetX() ~ Int { return @x; }   method : public : GetY() ~ Int { return @y;...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#TI-89_BASIC
TI-89 BASIC
:"Rosetta Code"→str1 :str1→str2
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Toka
Toka
" hello" is-data a a string.clone is-data b
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...
#Ring
Ring
  load "guilib.ring"   new qapp { win1 = new qwidget() { setwindowtitle("drawing using qpainter") setgeometry(100,100,500,500) label1 = new qlabel(win1) { setgeometry(10,10,400,400) settext(...
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.
#Vlang
Vlang
import time import rand import rand.pcg32 import rand.seed   fn main() { words := ['Enjoy', 'Rosetta', 'Code'] seed_u64 := u64(time.now().unix_time_milli()) q := chan string{} for i, w in words { go fn (q chan string, w string, seed_u64 u64) { mut rng := pcg32.PCG32RNG{} ...
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.
#Wren
Wren
import "random" for Random   var words = ["Enjoy", "Rosetta", "Code"] var rand = Random.new() for (h in 1..3) { var fibers = List.filled(3, null) for (i in 0..2) fibers[i] = Fiber.new { System.print(words[i]) } var called = List.filled(3, false) var j = 0 while (j < 3) { var k = rand.int(3) ...
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 ...
#AmbientTalk
AmbientTalk
  if: condition then: { // condition is true... } else: { // condition is false... }  
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...
#AWK
AWK
  function error(msg) { printf("%s\n", msg) exit(1) }   function bytes_to_int(bstr, i, sum) { sum = 0 for (i=word_size-1; i>=0; i--) { sum *= 256 sum += code[bstr+i] } return sum }   function emit_byte(x) { code[next_free_code_index++] = x }   function emit_word(x, i) { for (i=0; ...
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...
#J
J
outbuf=: '' emit=:{{ outbuf=: outbuf,y if.LF e. outbuf do. ndx=. outbuf i:LF echo ndx{.outbuf outbuf=: }.ndx}.outbuf end. }}   load_ast=: {{ 'node_types node_values'=: 2{.|:(({.,&<&<}.@}.)~ i.&' ');._2 y 1{::0 load_ast '' : node_type=. x{::node_types if. node_type-:,';' do. x;a: return.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 |...
#ALGOL_68
ALGOL 68
BEGIN # compare string lengths # # returns the length of s using the builtin UPB and LWB operators # OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s; # prints s and its length # PROC print string = ( STRING s )VOID: print( ( """", s, """ has length: ", whole( LENGTH s, 0 ), " bytes.", newlin...
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 |...
#APL
APL
  sv ← 'defg' 'hijklm' 'abc' 'abcd' ⍉(⍴¨sv[⍒sv]),[0.5]sv[⍒sv] 6 hijklm 4 defg 4 abcd 3 abc  
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...
#Common_Lisp
Common Lisp
#!/bin/sh #|-*- mode:lisp -*-|# #| exec ros -Q -- $0 "$@" |# (progn ;;init forms (ros:ensure-asdf) #+quicklisp(ql:quickload '() :silent t))   (defpackage :ros.script.parse.3859374047 (:use :cl)) (in-package :ros.script.parse.3859374047)   ;;; ;;; The Rosetta Code Tiny-Language Parser, in Common Lisp. ;;;   (requi...
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...
#Befunge
Befunge
00p10p20p30p&>40p&>50p60p>$#v~>:55+-vv+`1:%3:+*g04p03< >3/"P"%\56v>p\56*8*/8+:v v5\`\"~"::-*3p06!:!-+67:_^#!<*<!g06!<>1+70g*\:3/"P"%v^ ^::+*g04%<*0v`1:%3\gp08< >6*`*#v_55+-#v_p10g1+10p>^pg08g07+gp08:+8/*8*65\p07:<^ >/10g-50g^87>+1+:01p/8/v >%#74#<-!!70p 00g::1+00p:20g\-:0`*+20p10g::30g\-:0`*+^ ^2+2+g03*<*:v+g06p09:%2< ...
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...
#OCaml
OCaml
type tree = Empty | Leaf of int | Node of tree * tree   let t1 = Node (Leaf 1, Node (Leaf 2, Leaf 3))
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...
#Oforth
Oforth
Object Class new: Point(x, y)
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Transd
Transd
#lang transd   MainModule : { _start: (λ (with s "Hello!" s1 "" s2 "" (= s1 s) // duplication of 's' content (rebind s2 s) // another reference to 's' (= s "Good bye!") (lout s) (lout s1) (lout s2) ) ) }
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Trith
Trith
"Hello" dup
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...
#Ruby
Ruby
points = (1..100).map do # choose a random radius and angle angle = rand * 2.0 * Math::PI rad = rand * 5.0 + 10.0 # convert back from polar to cartesian coordinates [rad * Math::cos(angle), rad * Math::sin(angle)].map(&:round) end   (-15..15).each do |row| puts (-15..15).map { |col| points.include?([row, ...
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.
#XPL0
XPL0
int Key, Process; [Key:= SharedMem(4); \allocate 4 bytes of memory common to all processes Process:= Fork(2); \start 2 child processes case Process of 0: [Lock(Key); Text(0, "Enjoy"); CrLf(0); Unlock(Key)]; \parent process 1: [Lock(Key); Text(0, "Rosetta"); CrLf(0); Unlock(Key)]; \child process ...
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.
#zkl
zkl
fcn{println("Enjoy")}.launch(); // thread fcn{println("Rosetta")}.strand(); // co-op thread fcn{println("Code")}.future(); // another thread type
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 ...
#AmigaE
AmigaE
IF condition -> if condition is true... ELSEIF condition2 -> else if condition2 is true... ELSE -> if all other conditions are not true... ENDIF
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <stdint.h> #include <ctype.h>   #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))   #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _p = 0; \ in...
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...
#Java
Java
  import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap;   class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> ...
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 |...
#Arturo
Arturo
sortByLength: function [strs][ map sort.descending.by:'v map strs 'str -> #[s: str, v: size str] 'z -> z\s ]   A: "I am string" B: "I am string too"   sA: size A sB: size B   if? sA < sB -> print ["string ->" A "(" sA ") is smaller than string ->" B "(" sB ")"] else [ if? sA > sB -> ...
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 |...
#Asymptote
Asymptote
string A, B, t = '\t';   void comp(string A, string B) { if (length(A) >= length(B)) { write(A+t, length(A)); write(B+t, length(B)); } else { write(B+t, length(B)); write(A+t, length(A)); } }   comp("abcd", "123456789");
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...
#Forth
Forth
CREATE BUF 0 , \ single-character look-ahead buffer : PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ; : GETC PEEK 0 BUF ! ; : SPACE? DUP BL = SWAP 9 14 WITHIN OR ; : >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ; : DIGIT? 48 58 WITHIN ; : GETINT >SPACE 0 BEGIN PEEK DIGIT? WHILE GETC [CHA...
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...
#Brainf.2A.2A.2A
Brainf***
width = 3 height = 3 rounds = 3   universe = [[0 1 0] [0 1 0] [0 1 0]]   next = height.of({width.of(0)})   cell = { x, y | true? x < width && { x >= 0 && { y >= 0 && { y < height }}} { universe[y][x] } { 0 } }   neighbors = { x, y | cell(x - 1, y - 1) + cell(x, y - 1) + cell(x ...
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...
#ooRexx
ooRexx
  p = .point~new(3,4) say "x =" p~x say "y =" p~y   ::class point ::method init expose x y use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates   ::attribute x ::attribute 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...
#OpenEdge.2FProgress
OpenEdge/Progress
DEF TEMP-TABLE point FIELD X AS INT FIELD Y AS INT .
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT str="Hello" dst=str
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#UNIX_Shell
UNIX Shell
foo="Hello" bar=$foo # This is a copy of the string
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...
#Run_BASIC
Run BASIC
w = 320 h = 320 dim canvas(w,h) for pts = 1 to 1000 x = (rnd(1) * 31) - 15 y = (rnd(1) * 31) - 15 r = x * x + y * y if (r > 100) and (r < 225) then x = int(x * 10 + w/2) y = int(y * 10 + h/2) canvas(x,y) = 1 end if next pts   ' ----------------------------- ' display the graphic ' ------------...
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 ...
#Apex
Apex
if (s == 'Hello World') { foo(); } else if (s == 'Bye World') { bar(); } else { deusEx(); }
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...
#COBOL
COBOL
>>SOURCE FORMAT IS FREE identification division. *> this code is dedicated to the public domain *> (GnuCOBOL) 2.3-dev.0 program-id. vminterpreter. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select input-file assign using input-name ...
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...
#ALGOL_68
ALGOL 68
# RC Compiler code generator # COMMENT this writes a .NET IL assembler source to standard output. If the output is stored in a file called "rcsample.il", it could be compiled the command: ilasm /opt /out:rcsample.exe rcsample.il (Note ilasm may not be in the PATH by default(   Note: The gene...
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 ...
#AutoHotkey
AutoHotkey
; BUGGY - FIX   #Persistent #SingleInstance OFF SetBatchLines, -1 SortMethods := "Bogo,Bubble,Cocktail,Counting,Gnome,Insertion,Merge,Permutation,Quick,Selection,Shell,BuiltIn" Gui, Add, Edit, vInput, numbers,separated,by,commas,without,spaces,afterwards Loop, PARSE, SortMethods, `, Gui, Add, CheckBox, v%A_LoopField%,...
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...
#Julia
Julia
struct Anode node_type::String left::Union{Nothing, Anode} right::Union{Nothing, Anode} value::Union{Nothing, String} end   make_leaf(t, v) = Anode(t, nothing, nothing, v) make_node(t, l, r) = Anode(t, l, r, nothing)   const OP2 = Dict("Multiply" => "*", "Divide" => "/", "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 |...
#AutoHotkey
AutoHotkey
list := ["abcd","123456789","abcdef","1234567"]   sorted := [] for i, s in list sorted[0-StrLen(s), s] := s for l, obj in sorted { i := A_Index for s, v in obj { if (i = 1) result .= """" s """ has length " 0-l " and is the longest string.`n" else if (i < sorted.Count()) ...
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 |...
#AWK
AWK
  # syntax: GAWK -f COMPARE_LENGTH_OF_TWO_STRINGS.AWK BEGIN { main("abcd","123456789") main("longer","short") main("hello","world") exit(0) } function main(Sa,Sb, La,Lb) { La = length(Sa) Lb = length(Sb) if (La > Lb) { printf("a>b\n%3d %s\n%3d %s\n\n",La,Sa,Lb,Sb) } else if (L...
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...
#Fortran
Fortran
!!! !!! An implementation of the Rosetta Code parser task: !!! https://rosettacode.org/wiki/Compiler/syntax_analyzer !!! !!! The implementation is based on the published pseudocode. !!!   module compiler_type_kinds use, intrinsic :: iso_fortran_env, only: int32 use, intrinsic :: iso_fortran_env, only: int64   imp...
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...
#Brat
Brat
width = 3 height = 3 rounds = 3   universe = [[0 1 0] [0 1 0] [0 1 0]]   next = height.of({width.of(0)})   cell = { x, y | true? x < width && { x >= 0 && { y >= 0 && { y < height }}} { universe[y][x] } { 0 } }   neighbors = { x, y | cell(x - 1, y - 1) + cell(x, y - 1) + cell(x ...
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...
#OxygenBasic
OxygenBasic
  'SHORT FORM type point float x,y   'FULL FORM type point float x float y end type   point p   'WITH DEFAULT VALUES type point float x = 1.0 float y = 1.0 end type   point p = {} 'assigns the set of default values     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...
#Oz
Oz
P = point(x:1 y:2)
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Ursa
Ursa
decl string a b set a "hello" set b a
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#V
V
"hello" dup
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...
#Rust
Rust
extern crate rand;   use rand::Rng;   const POINTS_N: usize = 100;   fn generate_point<R: Rng>(rng: &mut R) -> (i32, i32) { loop { let x = rng.gen_range(-15, 16); // exclusive let y = rng.gen_range(-15, 16);   let r2 = x * x + y * y; if r2 >= 100 && r2 <= 225 { return (x,...
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 ...
#AppleScript
AppleScript
if myVar is "ok" then return true   set i to 0 if i is 0 then return "zero" else if i mod 2 is 0 then return "even" else return "odd" end if
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...
#11l
11l
F commatize(s, period = 3, sep = ‘,’) V m = re:‘(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)’.search(s) I !m R s   V match = m.group() V splits = match.split(‘.’)   V ip = splits[0] I ip.len > period V inserted = 0 L(i) ((ip.len - 1) % period + 1 .< ip.len).step(period) ip = ip[0 .<...
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...
#Common_Lisp
Common Lisp
#!/bin/sh #|-*- mode:lisp -*-|# #| exec ros -Q -- $0 "$@" |# (progn ;;init forms (ros:ensure-asdf) #+quicklisp(ql:quickload '() :silent t) )   (defpackage :ros.script.vm.3858678051 (:use :cl)) (in-package :ros.script.vm.3858678051)   ;;; ;;; The Rosetta Code Virtual Machine, in Common Lisp. ;;; ;;; Notes: ;;; ;...
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...
#ALGOL_W
ALGOL W
begin % code generator %  % parse tree nodes % record node( integer type  ; reference(node) left, right  ; integer iValue % nString/nIndentifier number or nInteger value % ); integer nIdentifier, nString, nInteger, nSequence, nIf, nPrtc, nPrts ...
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 ...
#BBC_BASIC
BBC BASIC
HIMEM = PAGE + 2000000 INSTALL @lib$+"SORTLIB" INSTALL @lib$+"TIMERLIB" Sort% = FN_sortinit(0,0) Timer% = FN_ontimer(1000, PROCtimer, 1)   PRINT "Array size:", 1000, 10000, 100000 @% = &2020A   FOR patt% = 1 TO 4 CASE patt% OF WHEN 1: PRINT '"Data set to...
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 ...
#C
C
#ifndef _CSEQUENCE_H #define _CSEQUENCE_H #include <stdlib.h>   void setfillconst(double c); void fillwithconst(double *v, int n); void fillwithrrange(double *v, int n); void shuffledrange(double *v, int n); #endif
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...
#Nim
Nim
import os, strutils, streams, tables   import ast_parser   type   ValueKind = enum valNil, valInt, valString   # Representation of a value. Value = object case kind: ValueKind of valNil: nil of valInt: intVal: int of valString: stringVal: string   # Range of binary operators. BinaryOperator = ...
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 |...
#BQN
BQN
Compare ← >·(⍒⊑¨)⊸⊏≠⊸⋈¨   •Show Compare ⟨"hello", "person"⟩ •Show Compare ⟨"abcd", "123456789", "abcdef", "1234567"⟩
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 |...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   int cmp(const int* a, const int* b) { return *b - *a; // reverse sort! }   void compareAndReportStringsLength(const char* strings[], const int n) { if (n > 0) { char* has_length = "has length"; char* predicate_max = "and is the lon...
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...
#Go
Go
package main   import ( "bufio" "fmt" "log" "os" "strconv" "strings" )   type TokenType int   const ( tkEOI TokenType = iota tkMul tkDiv tkMod tkAdd tkSub tkNegate tkNot tkLss tkLeq tkGtr tkGeq tkEql tkNeq tkAssign tkAnd tkOr ...
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...
#BQN
BQN
Life←{ r←¯1(⌽⎉1)¯1⌽(2+≢𝕩)↑𝕩 s←∨´ (1∾<r) ∧ 3‿4 = <+´⥊ ¯1‿0‿1 (⌽⎉1)⌜ ¯1‿0‿1 ⌽⌜ <r 1(↓⎉1) ¯1(↓⎉1) 1↓ ¯1↓s }   blinker←>⟨0‿0‿0,1‿1‿1,0‿0‿0⟩ (<".#") ⊏¨˜ Life⍟(↕3) blinker