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/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... | #PARI.2FGP | PARI/GP | point.x=1;
point.y=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... | #Pascal | Pascal | 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... | #VBA | VBA | Sub copystring()
a = "Hello World!"
b = a
a = "I'm gone"
Debug.Print b
Debug.Print a
End Sub |
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... | #Vim_Script | Vim Script | let str1 = "original string"
let str2 = str1
let str1 = "new string"
echo "String 1:" str1
echo "String 2:" 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... | #Scala | Scala | import java.awt.{ Color, geom,Graphics2D ,Rectangle}
import scala.math.hypot
import scala.swing.{MainFrame,Panel,SimpleSwingApplication}
import scala.swing.Swing.pair2Dimension
import scala.util.Random
object CirculairConstrainedRandomPoints extends SimpleSwingApplication {
//min/max of display-x resp. y
val dx0,... |
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 ... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program condstr.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessTest1: .asciz "The test 1 is equal.\n"
szMessTest1N: .asciz "The test 1 is not equal.\n... |
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... | #ALGOL_68 | ALGOL 68 | # returns text commatized according to the rules of the task and the #
# period, location and separator paramters #
PROC commatize = ( STRING text, INT location, INT period, STRING separator )STRING:
IF STRING str := text[ AT 1 ];
# handle the options ... |
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... | #D | D | //
// The Rosetta Code Virtual Machine in D.
//
// This code was migrated from an implementation in ATS. I have tried
// to keep it possible to compare the two languages easily, although
// in some cases the demonstration of "low level" techniques in ATS
// (such as avoiding memory leaks that might require garbage
// c... |
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... | #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 make_node(oper, left, right, value) {
node_type [next_free_node_index] = oper
node_left [next_f... |
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
... | #D | D | import std.stdio, std.algorithm, std.container, std.datetime,
std.random, std.typetuple;
immutable int[] allOnes, sortedData, randomData;
static this() { // Initialize global Arrays.
immutable size_t arraySize = 10_000;
allOnes = new int[arraySize];
//allOnes[] = 1;
foreach (ref d; allOnes)... |
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... | #Perl | Perl | #!/usr/bin/perl
use strict; # interpreter.pl - execute a flatAST
use warnings; # http://www.rosettacode.org/wiki/Compiler/AST_interpreter
use integer;
my %variables;
tree()->run;
sub tree
{
my $line = <> // die "incomplete tree\n";
(local $_, my $arg) = $line =~ /^(\w+|;)\s+(.*)/ or die "bad input $line... |
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.2B.2B | C++ | #include <iostream>
#include <algorithm>
#include <string>
#include <list>
using namespace std;
bool cmp(const string& a, const string& b)
{
return b.length() < a.length(); // reverse sort!
}
void compareAndReportStringsLength(list<string> listOfStrings)
{
if (!listOfStrings.empty())
{
char Q ... |
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... | #Icon | Icon | #
# The Rosetta Code Tiny-Language Parser, in Icon.
#
# This implementation is based closely on the pseudocode and the C
# reference implementation.
#
# ximage from the IPL is useful for debugging. Use "xdump(x)" to
# pretty-print x.
#link ximage
record token_record (line_no, column_no, tok, tokval)
record token_ge... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define for_x for (int x = 0; x < w; x++)
#define for_y for (int y = 0; y < h; y++)
#define for_xy for_x for_y
void show(void *u, int w, int h)
{
int (*univ)[w] = u;
printf("\033[H");
for_y {
for_x printf(univ[y][x] ? "\033[07m \033[m" : " ");
printf... |
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... | #Perl | Perl | my @point = (3, 8); |
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... | #Phix | Phix | with javascript_semantics
enum x,y
type point(object p)
return sequence(p) and length(p)=y and atom(p[x]) and atom(p[y])
end type
point p = {175,3.375}
p[x] -= p[y]*20
puts(1,"point p is ")
?p
printf(1,"p[x]:%g, p[y]:%g\n",{p[x],p[y]})
p[x] = 0 -- fine
p[y] = "string" -- run-time error (not pwa/p2... |
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... | #Visual_Basic_.NET | Visual Basic .NET | 'Immutable Strings
Dim a = "Test string"
Dim b = a 'reference to same string
Dim c = New String(a.ToCharArray) 'new string, normally not used
'Mutable Strings
Dim x As New Text.StringBuilder("Test string")
Dim y = x 'reference
Dim z = New Text.StringBuilder(x.ToString) 'new string |
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... | #Wren | Wren | var s = "wren"
var t = s
System.print("Are 's' and 't' equal? %(s == t)") |
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... | #Sidef | Sidef | var points = [];
while (points.len < 100) {
var (x, y) = 2.of{31.rand.int - 15}...;
var r2 = (x**2 + y**2);
if ((r2 >= 100) && (r2 <= 225)) {
points.append([x, y]);
}
}
print <<'HEAD';
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox 0 0 400 400
200 200 translate 10 10 scale
0 setlinewidth
1 0 0 setrgbco... |
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 ... | #Arturo | Arturo | num: 2
if? num=2 [
print "yep, num is 2"
]
else [
print "something went wrong..."
] |
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... | #C.23 | C# |
static string[] inputs = {
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"\"-in Aus$+1411.8millions\"",
"===US$0017440 millions=== (in 2000 dollars)"
};
void Main()
{
inputs.Select(s => Commatize(s, 0, 3, ","))
... |
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... | #11l | 11l | L(strings_s) [‘AA AA AA AA’, ‘AA ACB BB CC’]
V strings = strings_s.split(‘ ’)
print(strings)
print(all(zip(strings, strings[1..]).map(a -> a[0] == a[1])))
print(all(zip(strings, strings[1..]).map(a -> a[0] < a[1])))
print() |
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"
| #11l | 11l | :start:
print(‘Program name: ’:argv[0])
print("Arguments:\n":argv[1..].join("\n")) |
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... | #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 ;
: >INT ( -- n) >SPACE 0
BEGIN PEEK DIGIT?
WHILE GETC ... |
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... | #C | C | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdint.h>
#include <ctype.h>
typedef unsigned char uchar;
typedef enum {
nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While,
nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd... |
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
... | #Erlang | Erlang |
-module( compare_sorting_algorithms ).
-export( [task/0] ).
task() ->
Ns = [100, 1000, 10000],
Lists = [{"ones", fun list_of_ones/1, Ns}, {"ranges", fun list_of_ranges/1, Ns}, {"reversed_ranges", fun list_of_reversed_ranges/1, Ns}, {"shuffleds", fun list_of_shuffleds/1, Ns}],
Sorts = [{bubble_sort, fun bubble_... |
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... | #Phix | Phix | --
-- demo\rosetta\Compiler\interp.exw
-- ================================
--
with javascript_semantics
include parse.e
sequence vars = {},
vals = {}
function var_idx(sequence inode)
if inode[1]!=tk_Identifier then ?9/0 end if
string ident = inode[2]
integer n = find(ident,vars)
if n=0 then
... |
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.23 | C# | using System;
using System.Collections.Generic;
namespace example
{
class Program
{
static void Main(string[] args)
{
var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(strings);
}
private static void... |
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... | #J | J | require'format/printf'
tkref=: tokenize 'End_of_input*/%+--<<=>>===!=!&&||print=print(if{else}while;,putc)a""0'
tkref,. (tknames)=: tknames=:;: {{)n
End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract Op_negate Op_less
Op_lessequal Op_greater Op_greaterequal Op_equal Op_notequal Op_not Op_and
Op_or Keywor... |
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... | #C.23 | C# |
using System;
using System.Text;
using System.Threading;
namespace ConwaysGameOfLife
{
// Plays Conway's Game of Life on the console with a random initial state.
class Program
{
// The delay in milliseconds between board updates.
private const int DELAY = 50;
// The cell colors... |
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... | #PHP | PHP | # Using pack/unpack
$point = pack("ii", 1, 2);
$u = unpack("ix/iy", $point);
echo $x;
echo $y;
list($x,$y) = unpack("ii", $point);
echo $x;
echo $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... | #PicoLisp | PicoLisp | (class +Point)
(dm T (X Y)
(=: x X)
(=: y Y) )
(setq P (new '(+Point) 3 4))
(show P) |
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... | #X86_Assembly | X86 Assembly |
section .data
string db "Hello World", 0
section .bss
string2 resb 12
section .text
global _main
_main:
mov ecx, 0
looping:
mov al, [string + ecx]
mov [string2 + ecx], al
inc ecx
cmp al, 0 ;copy until we find the terminating 0
je end
jmp looping
... |
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... | #X86-64_Assembly | X86-64 Assembly |
option casemap:none
option literals:on
printf proto :dword, :VARARG
exit proto :dword
.data
s db "Goodbye, World!",0
.data?
d db 20 dup (?)
dp dq ?
tb dd ?
.code
main proc
lea rsi, s ;; Put the address of var S into the source index(RSI)
xor rcx, rcx ... |
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... | #Standard_ML | Standard ML | open XWindows ;
open Motif ;
val plotWindow = fn coords => (* input list of int*int within 'dim' *)
let
val dim = {tw=325,th=325} ;
val shell = XtAppInitialise "" "demo" "top" [] [ XmNwidth (#tw dim), XmNheight (#th dim) ] ; (*... |
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 ... | #Astro | Astro | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c |
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... | #D | D | import std.stdio, std.regex, std.range;
auto commatize(in char[] txt, in uint start=0, in uint step=3,
in string ins=",") @safe
in {
assert(step > 0);
} body {
if (start > txt.length || step > txt.length)
return txt;
// First number may begin with digit or decimal point. Exponents ignore... |
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... | #360_Assembly | 360 Assembly | * Compare a list of strings 31/01/2017
COMPLIST CSECT
USING COMPLIST,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) ... |
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... | #Action.21 | Action! | DEFINE PTR="CARD"
BYTE FUNC AreEqual(PTR ARRAY a BYTE len)
INT i
FOR i=1 TO len-1
DO
IF SCompare(a(0),a(i))#0 THEN
RETURN (0)
FI
OD
RETURN (1)
BYTE FUNC IsAscendingOrder(PTR ARRAY a BYTE len)
INT i
FOR i=1 TO len-1
DO
IF SCompare(a(i-1),a(i))>=0 THEN
RETURN (0)
FI
OD
... |
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"
| #8080_Assembly | 8080 Assembly | putch: equ 2 ; CP/M syscall to print character
puts: equ 9 ; CP/M syscall to print $-terminated string
arglen: equ 80h ; Length of argument
argmt: equ 81h ; Argument string
fcb1: equ 5Ch ; FCBs
fcb2: equ 6Ch
org 100h
;;; Print all argument(s) as given
lxi d,cmdln ; Print 'Command line: '
mvi c,puts
call 5
lda arg... |
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"
| #8086_Assembly | 8086 Assembly | with Ada.Command_line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
procedure Print_Commands is
begin
-- The number of command line arguments is retrieved from the function Argument_Count
-- The actual arguments are retrieved from the function Argument
-- The program name is retrieved from the fu... |
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.)
| #11l | 11l | // Single line comment
\\ Also single line comment (continuation of the comment in previous line)
\[ This is
a multi line
comment ]
\{ And
this }
\( And
this )
\‘ And
this ’ |
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... | #Fortran | Fortran | module compiler_type_kinds
use, intrinsic :: iso_fortran_env, only: int32
use, intrinsic :: iso_fortran_env, only: int64
implicit none
private
! Synonyms.
integer, parameter, public :: size_kind = int64
integer, parameter, public :: length_kind = size_kind
integer, parameter, public :: nk = size_kin... |
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... | #COBOL | COBOL | >>SOURCE FORMAT IS FREE
identification division.
*> this code is dedicated to the public domain
*> (GnuCOBOL) 2.3-dev.0
program-id. generator.
environment division.
configuration section.
repository. function all intrinsic.
data division.
working-storage section.
01 program-name pic x(32) value spaces global.... |
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
... | #Go | Go | package main
import (
"log"
"math/rand"
"testing"
"time"
"github.com/gonum/plot"
"github.com/gonum/plot/plotter"
"github.com/gonum/plot/plotutil"
"github.com/gonum/plot/vg"
)
// Step 1, sort routines.
// These functions are copied without changes from the RC tasks Bubble Sort,
// 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... | #Python | Python | from __future__ import print_function
import sys, shlex, operator
nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \
nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \
nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)
all_syms... |
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 |... | #CFEngine | CFEngine |
bundle agent __main__
{
vars:
"strings" slist => { "abcd", "123456789", "abcdef", "1234567" };
"sorted[$(with)]"
string => "$(strings)",
with => string_length( "$(strings)" );
"sort_idx" slist => reverse( sort( getindices( "sorted" ), lex ) );
reports:
"'$(sorted[$(so... |
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 |... | #BASIC | BASIC | *** (1) TWO STRINGS ***
LONGER STRING (13)
SHORT STRING (12)
*** (2) MORE THAN 2 STRINGS***
SHE DOESN'T STUDY GERMAN ON MONDAY (34)
EVERY CHILD LIKES AN ICE CREAM (30)
THE COURSE STARTS NEXT SUNDAY (29)
DOES SHE LIVE IN PARIS? (23)
SHE SWIMS EVERY MORNING (23)
THE EARTH IS SPHERICAL (22)
WE SEE THEM EVERY WEEK (22)
H... |
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... | #Java | Java |
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class Parser {
private List<Token> source;
private Token token;
private int position;
static... |
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... | #C.2B.2B | C++ | #include <iostream>
#define HEIGHT 4
#define WIDTH 4
struct Shape {
public:
char xCoord;
char yCoord;
char height;
char width;
char **figure;
};
struct Glider : public Shape {
static const char GLIDER_SIZE = 3;
Glider( char x , char y );
~Glider();
};
struct Blinker : public Shape ... |
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... | #Pike | Pike |
class Point {
int x, y;
void create(int _x, int _y)
{
x = _x;
y = _y;
}
}
void main()
{
object point = Point(10, 20);
write("%d %d\n", point->x, point->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... | #PL.2FI | PL/I |
define structure
1 point,
2 x float,
2 y float;
|
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... | #XPL0 | XPL0 | proc StrCopy(A, B); \Copy string: A --> B
char A, B; \Strings: B must already have enough space "Reserved"
int I; \Beware if strings overlap
for I:= 0 to -1>>1-1 do
[B(I):= A(I);
if A(I) >= $80 then return
];
char S1, S2, S3(13);
[S1:= "Hello, world!"; \S1 now points to ... |
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... | #Z80_Assembly | Z80 Assembly | ld hl,MyString
ld (PointerVariable),hl
MyString: ;assembler equates this label to a memory location at compile time
byte "Hello",0
PointerVariable:
word 0 ;placeholder for the address of the above string, gets written to by the code above. |
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... | #Swift | Swift | let nPoints = 100
func generatePoint() -> (Int, Int) {
while true {
let x = Int.random(in: -15...16)
let y = Int.random(in: -15...16)
let r2 = x * x + y * y
if r2 >= 100 && r2 <= 225 {
return (x, y)
}
}
}
func filteringMethod() {
var rows = [[String]](repeating: Array(repeating: " ... |
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 ... | #AutoHotkey | AutoHotkey | x = 1
If x
MsgBox, x is %x%
Else If x > 1
MsgBox, x is %x%
Else
MsgBox, x is %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... | #Delphi | Delphi |
program Commatizing_numbers;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.RegularExpressions,
system.StrUtils;
const
PATTERN = '(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)';
TESTS: array[0..13] of string = ('123456789.123456789', '.123456789',
'57256.1D-4', 'pi=3.14159265358979323846264338327950288419... |
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... | #Ada | Ada | package String_Vec is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => String);
use type String_Vec.Vector; |
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... | #ALGOL_68 | ALGOL 68 | []STRING list1 = ("AA","BB","CC");
[]STRING list2 = ("AA","AA","AA");
[]STRING list3 = ("AA","CC","BB");
[]STRING list4 = ("AA","ACB","BB","CC");
[]STRING list5 = ("single_element");
[][]STRING all lists to test = (list1, list2, list3, list4, list5);
PROC equal = ([]STRING list) BOOL:
BEGIN
BOOL ok := TRUE... |
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... | #Ada | Ada | with Ada.Text_IO, Ada.Streams.Stream_IO, Ada.Strings.Unbounded, Ada.Command_Line,
Ada.Exceptions;
use Ada.Strings, Ada.Strings.Unbounded, Ada.Streams, Ada.Exceptions;
procedure Main is
package IO renames Ada.Text_IO;
package Lexer is
type Token is (Op_multiply, Op_divide, Op_mod, Op_add, Op_subtrac... |
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"
| #Ada | Ada | with Ada.Command_line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
procedure Print_Commands is
begin
-- The number of command line arguments is retrieved from the function Argument_Count
-- The actual arguments are retrieved from the function Argument
-- The program name is retrieved from the fu... |
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"
| #Aikido | Aikido |
foreach arg in args {
println ("arg: " + arg)
}
|
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.)
| #360_Assembly | 360 Assembly |
* An asterisk in column one denotes a comment line
* Comments may also follow any syntactically complete instruction:
LA 1,0 Comment
NOP Comment (after a NOP instruction)
* Comments after instructions with omitted operands require a comma ","
END , ... |
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.)
| #4D | 4D | `Comments in 4th Dimension begin with the accent character and extend to the end of the line (until 4D version 2004).
// This is a comment starting from 4D v11 and newer. Accent character is replaced by // |
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... | #Go | Go | package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
... |
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... | #Forth | Forth | CREATE BUF 0 ,
: 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 ;
: >Integer >SPACE 0
BEGIN PEEK DIGIT?
WHILE GETC [CHAR] 0 - SWAP 10 * + REPEAT ;
: SKIP ( xt --)
B... |
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
... | #Haskell | Haskell | import Data.Time.Clock
import Data.List
type Time = Integer
type Sorter a = [a] -> [a]
-- Simple timing function (in microseconds)
timed :: IO a -> IO (a, Time)
timed prog = do
t0 <- getCurrentTime
x <- prog
t1 <- x `seq` getCurrentTime
return (x, ceiling $ 1000000 * diffUTCTime t1 t0)
-- testing sorting ... |
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... | #RATFOR | RATFOR | ######################################################################
#
# The Rosetta Code AST interpreter in Ratfor 77.
#
#
# In FORTRAN 77 and therefore in Ratfor 77, there is no way to specify
# that a value should be put on a call stack. Therefore there is no
# way to implement recursive algorithms in Ratfor 77 (a... |
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 |... | #Fortran | Fortran |
program demo_sort_indexed
implicit none
call print_sorted_by_length( [character(len=20) :: "shorter","longer"] )
call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] )
call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','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... | #Julia | Julia | struct ASTnode
nodetype::Int
left::Union{Nothing, ASTnode}
right::Union{Nothing, ASTnode}
value::Union{Nothing, Int, String}
end
function syntaxanalyzer(inputfile)
tkEOI, tkMul, tkDiv, tkMod, tkAdd, tkSub, tkNegate, tkNot, tkLss, tkLeq, tkGtr, tkGeq,
tkEql, tkNeq, tkAssign, tkAnd, tkOr, tkIf, ... |
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... | #Chapel | Chapel |
config const gridHeight: int = 3;
config const gridWidth: int = 3;
enum State { dead = 0, alive = 1 };
class ConwaysGameofLife {
var gridDomain: domain(2);
var computeDomain: subdomain( gridDomain );
var grid: [gridDomain] int;
proc ConwaysGameofLife( height: int, width: int ) {
this.gridDomain = ... |
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... | #Plain_English | Plain English | A cartesian point is a record with an x coord and a y coord. |
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... | #Pop11 | Pop11 | uses objectclass;
define :class Point;
slot x = 0;
slot y = 0;
enddefine; |
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... | #Zig | Zig | const std = @import("std");
const debug = std.debug;
const mem = std.mem;
test "copy a string" {
const source = "A string.";
// Variable `dest1` will have the same type as `source`, which is
// `*const [9:0]u8`.
const dest1 = source;
// Variable `dest2`'s type is [9]u8.
//
// The dif... |
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... | #zkl | zkl | "abc".copy() // noop |
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... | #zonnon | zonnon |
module Main;
var
s,r: string;
c: array 60 of char;
begin
s := "plain string";r := s; writeln(s);
(* copy string to array of char *)
copy(s,c);c[0] := 'P';
(* copy array of char to string *)
copy(c,r);writeln(r);
end Main.
|
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... | #SystemVerilog | SystemVerilog | program main;
bit [39:0] bitmap [40];
class Point;
rand bit signed [4:0] x;
rand bit signed [4:0] y;
constraint on_circle_edge {
(10*10) <= (x*x + y*y);
(x*x + y*y) <= (15*15);
};
function void do_point();
randomize;
bitmap[x+20][y+20] = 1;
endfunction
endcl... |
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 ... | #AutoIt | AutoIt | If <expression> Then
statements
...
[ElseIf expression-n Then
[elseif statements ... ]]
...
[Else
[else statements]
...
EndIf
|
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... | #Factor | Factor | USING: accessors grouping io kernel math regexp sequences
splitting strings unicode ;
: numeric ( str -- new-str )
R/ [1-9][0-9]*/ first-match >string ;
: commas ( numeric-str period separator -- str )
[ reverse ] [ group ] [ reverse join reverse ] tri* ;
: (commatize) ( text from period separator -- str ... |
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... | #FreeBASIC | FreeBASIC | Sub commatize(s As String, sep As String = ",", start As Byte = 1, paso As Byte = 3)
Dim As Integer l = Len(s)
For i As Integer = start To l
If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then
For j As Integer =i+1 To l+1
If j>l Then
Fo... |
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... | #ALGOL_W | ALGOL W | % returns true if all elements of the string array a are equal, false otherwise %
% As Algol W procedures cannot determine the bounds of an array, the bounds %
% must be specified in lo and hi %
logical procedure allStringsEqual ( string(256) array a ( ... |
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... | #AppleScript | AppleScript | -- allEqual :: [String] -> Bool
on allEqual(xs)
_and(zipWith(my _equal, xs, rest of xs))
end allEqual
-- azSorted :: [String] -> Bool
on azSorted(xs)
_and(zipWith(my azBeforeOrSame, xs, rest of xs))
end azSorted
-- _equal :: a -> a -> Bool
on _equal(a, b)
a = b
end _equal
-- azBefore :: String -> Stri... |
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_68 | ALGOL 68 | BEGIN
# implement C-like getchar, where EOF and EOLn are "characters" (-1 and 10 resp.). #
INT eof = -1, eoln = 10;
BOOL eof flag := FALSE;
STRING buf := "";
INT col := 1;
INT line := 0;
on logical file end (stand in, (REF FILE f)BOOL: eof flag := TRUE);
PROC getchar = INT:
IF eof flag THEN e... |
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"
| #Aime | Aime | integer i;
i = 0;
while (i < argc()) {
o_text(argv(i));
o_byte('\n');
i += 1;
} |
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"
| #ALGOL_68 | ALGOL 68 | main:(
FOR i TO argc DO
printf(($"the argument #"g(-0)" is "gl$, i, argv(i)))
OD
) |
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.)
| #6502_Assembly | 6502 Assembly | nop ; comments begin with a semicolon |
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.)
| #68000_Assembly | 68000 Assembly | MOVEM.L D0-D7/A0-A6,-(SP) ;push all registers onto the stack |
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... | #Icon | Icon | # -*- Icon -*-
#
# The Rosetta Code virtual machine in Icon. Migrated from the
# ObjectIcon.
#
# See https://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
#
record VirtualMachine(code, global_data, strings, stack, pc)
global opcode_names
global opcode_values
global op_halt
global op_add
global op_sub
gl... |
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... | #Fortran | Fortran | module compiler_type_kinds
use, intrinsic :: iso_fortran_env, only: int32
use, intrinsic :: iso_fortran_env, only: int64
implicit none
private
! Synonyms.
integer, parameter, public :: size_kind = int64
integer, parameter, public :: length_kind = size_kind
integer, parameter, public :: nk = size_kin... |
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
... | #J | J |
NB. extracts from other rosetta code projects
ts=: 6!:2, 7!:2@]
radix =: 3 : 0
256 radix y
:
a=. #{. z =. x #.^:_1 y
e=. (-a) {."0 b =. i.x
x#.1{::(<:@[;([: ; (b, {"1) <@}./. e,]))&>/^:a [ z;~a-1
NB. , ([: ; (b, {:"1) <@(}:"1@:}.)/. e,])^:(#{.z) y,.z
)
bubble=: (([ (<. , >.) {.@]) , }.@])/^:_
insertion=:((>: # ]) , ... |
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... | #Scala | Scala |
package xyz.hyperreal.rosettacodeCompiler
import scala.collection.mutable
import scala.io.Source
object ASTInterpreter {
def fromStdin = fromSource(Source.stdin)
def fromString(src: String) = fromSource(Source.fromString(src))
def fromSource(s: Source) = {
val lines = s.getLines
def load: No... |
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 |... | #FutureBasic | FutureBasic | local fn MyArraySortFunction( obj1 as CFTypeRef, obj2 as CFTypeRef, context as ptr ) as NSComparisonResult
NSComparisonResult result = NSOrderedDescending
if len(obj1) >= len(obj2) then result = NSOrderedAscending
end fn = result
void local fn DoIt
CFStringRef string1 = @"abcd", string2 = @"abcdef", s
if le... |
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 |... | #Harbour | Harbour |
PROCEDURE Main()
LOCAL s1 := "The long string"
LOCAL s2 := "The short string"
LOCAL a := { s1, s2 }
LOCAL s3
? s3 := "Here is how you can print the longer string first using Harbour language"
?
? "-------------------------------------------"
PrintTheLongerFirst( a )
a := hb_ATokens( s3, " " )
? "----... |
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... | #M2000_Interpreter | M2000 Interpreter |
Module syntax_analyzer(b$){
enum tokens {
Op_add, Op_subtract, Op_not=5, Op_multiply=10, Op_divide, Op_mod,
Op_negate, Op_less, Op_lessequal, Op_greater, Op_greaterequal,
Op_equal, Op_notequal, Op_and, Op_or, Op_assign=100, Keyword_if=110,
Keyword_else, Keyword_while, Keyword_print, Keyword_putc, LeftParen... |
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... | #Clojure | Clojure | (defn moore-neighborhood [[x y]]
(for [dx [-1 0 1]
dy [-1 0 1]
:when (not (= [dx dy] [0 0]))]
[(+ x dx) (+ y dy)]))
(defn step [set-of-cells]
(set (for [[cell count] (frequencies (mapcat moore-neighborhood set-of-cells))
:when (or (= 3 count)
(and (= 2 count... |
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... | #PowerShell | PowerShell |
class Point {
[Int]$a
[Int]$b
Point() {
$this.a = 0
$this.b = 0
}
Point([Int]$a, [Int]$b) {
$this.a = $a
$this.b = $b
}
[Int]add() {return $this.a + $this.b}
[Int]mul() {return $this.a * $this.b}
}
$p1 = [Point]::new()
$p2 = [Point]::new(3,2)
$p1.add()
$p2.mul()
|
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... | #Prolog | Prolog | point(10, 20). |
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... | #Zoomscript | Zoomscript | var a
var b
a = "World"
b = a
a = "Hello"
print (a," ",b) |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET a$ = "Hello": REM a$ is the original string
20 LET b$ = a$: REM b$ is the 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... | #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
main:
s = "string to copy"
t = s
{s,"\n",t}println
exit(0)
|
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.