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/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #zkl | zkl | fcn egyptianDivmod(dividend,divisor){
table:=[0..].pump(List, 'wrap(n){ // (2^n,divisor*2^n)
r:=T( p:=(2).pow(n), s:=divisor*p); (s<=dividend) and r or Void.Stop });
accumulator:=0;
foreach p2,d in (table.reverse()){
if(dividend>=d){ accumulator+=p2; dividend-=d; }
}
return(accumulator,divid... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Numerics
Imports System.Text
Module Module1
Function Gcd(a As BigInteger, b As BigInteger) As BigInteger
If b = 0 Then
If a < 0 Then
Return -a
Else
Return a
End If
Else
Return Gcd(b, a Mod b)
E... |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
func Halve(N); \Return half of N
int N;
return N>>1;
func Double(N); \Return N doubled
int N;
return N<<1;
func IsEven(N); \Return 'true' if N is an even number
int N;
return (N&1)=0;
func EthiopianMul(A, B); \Multiply A times B ... |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #Zig | Zig |
const stdout = @import("std").io.getStdOut().outStream();
pub fn factorial(comptime Num: type, n: i8) ?Num {
return if (@typeInfo(Num) != .Int)
@compileError("factorial called with num-integral type: " ++ @typeName(Num))
else if (n < 0)
null
else calc: {
var i: i8 = 1;
va... |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #Tcl | Tcl | # How to handle an incoming new connection
proc acceptEcho {chan host port} {
puts "opened connection from $host:$port"
fconfigure $chan -blocking 0 -buffering line -translation crlf
fileevent $chan readable [list echo $chan $host $port]
}
# How to handle an incoming message on a connection
proc echo {cha... |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #PostScript | PostScript | %!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400
/ed { exch def } def
/roty { dup sin /s ed cos /c ed [[c 0 s neg] [0 1 0] [s 0 c]] } def
/rotz { dup sin /s ed cos /c ed [[c s neg 0] [s c 0] [0 0 1]] } def
/dot { /a ed /b ed
a 0 get b 0 get mul
a 1 get b 1 get mul
a 2 get b 2 get mul
add add } def
/mmul { /v ed [exch ... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Sidef | Sidef | var m1 = [[3,1,4],[1,5,9]]
var m2 = [[2,7,1],[8,2,2]]
say ":: Matrix-matrix operations"
say (m1 ~W+ m2)
say (m1 ~W- m2)
say (m1 ~W* m2)
say (m1 ~W/ m2)
say (m1 ~W// m2)
say (m1 ~W** m2)
say (m1 ~W% m2)
say "\n:: Matrix-scalar operations"
say (m1 ~S+ 42)
say (m1 ~S- 42)
say (m1 ~S/ 42)
say (m1 ~S** 10)
# ...... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Asymptote | Asymptote | DIM SHARED angle AS DOUBLE
SUB turn (degrees AS DOUBLE)
angle = angle + degrees*3.14159265/180
END SUB
SUB forward (length AS DOUBLE)
LINE - STEP (COS(angle)*length, SIN(angle)*length), 7
END SUB
SUB dragon (length AS DOUBLE, split AS INTEGER, d AS DOUBLE)
IF split=0 THEN
forward length
EL... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Common_Lisp | Common Lisp | ;; * Loading the cairo bindings
(eval-when (:compile-toplevel :load-toplevel)
(ql:quickload '("cl-cairo2" "cl-cairo2-xlib")))
;; * The package definition
(defpackage :sphere
(:use :common-lisp :cl-cairo2))
(in-package :sphere)
(defparameter *context* nil)
(defparameter *size* 400)
(defparameter *middle* (/ *siz... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Perl | Perl | my %node_model = (
data => 'something',
prev => undef,
next => undef,
);
sub insert
{
my ($anchor, $newlink) = @_;
$newlink->{next} = $anchor->{next};
$newlink->{prev} = $anchor;
$newlink->{next}->{prev} = $newlink;
$anchor->{next} = $newlink;
}
# crea... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Phix | Phix | enum NEXT,PREV,DATA
constant empty_dll = {{1,1}}
sequence dll = deep_copy(empty_dll)
procedure insert_after(object data, integer pos=1)
integer prv = dll[pos][PREV]
dll = append(dll,{pos,prv,data})
if prv!=0 then
dll[prv][NEXT] = length(dll)
end if
dll[pos][PREV] = length(dll)
end procedur... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#define PI 3.14159265
const char * shades = " .:-*ca&#%@";
/* distance of (x, y) from line segment (0, 0)->(x0, y0) */
double dist(double x, double y, double x0, double y0) {
double l = (x * x0 + y * y0) / (x0 * x0 + y... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Lua | Lua | --------------
-- TRAVERSAL:
--------------
List.iterateForward = function(self)
local function iter(self, node)
if node then return node.next else return self.head end
end
return iter, self, nil
end
List.iterateReverse = function(self)
local function iter(self, node)
if node then return node.prev else ... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Liberty_BASIC | Liberty BASIC |
struct block,nxt as ulong,prev as ulong,nm as char[20],age as long'Our structure of the blocks in our list.
global hHeap
global hFirst
global hLast
global blockCount
global blockSize
blockSize=len(block.struct)
call Init
if hHeap=0 then
print "Error occured! Could not create heap, exiting..."
... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | CreateDataStructure["DoublyLinkedList"] |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Modula-2 | Modula-2 | TYPE
Link = POINTER TO LinkRcd;
LinkRcd = RECORD
Prev, Next: Link;
Data: INTEGER
END; |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Nim | Nim | type
Node[T] = ref TNode[T]
TNode[T] = object
next, prev: Node[T]
data: T |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Oberon-2 | Oberon-2 |
MODULE Box;
TYPE
Object* = POINTER TO ObjectDesc;
ObjectDesc* = (* ABSTRACT *) RECORD
END;
(* ... *)
END Box.
MODULE Collections;
TYPE
Node* = POINTER TO NodeDesc;
NodeDesc* = (* ABSTRACT *) RECORD
prev-,next-: Node;
value-: Box.Object;
END;
(* ... *)
END Collectio... |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #Haskell | Haskell | import Data.List (sort)
import System.Random (randomRIO)
import System.IO.Unsafe (unsafePerformIO)
data Color = Red | White | Blue deriving (Show, Eq, Ord, Enum)
dutch :: [Color] -> [Color]
dutch = sort
isDutch :: [Color] -> Bool
isDutch x = x == dutch x
randomBalls :: Int -> [Color]
randomBalls 0 = []
randomBa... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #FreeBASIC | FreeBASIC | #include once "GL/gl.bi"
#include once "GL/glu.bi"
dim rquad as single
screen 18, 16, , 2
glViewport 0, 0, 640, 480 '' Reset The Current Viewport
glMatrixMode GL_PROJECTION '' Select The Projection Matrix
glLoadIdentity '' Reset The Projecti... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Stata | Stata | display "Name?" _request(s)
scalar $s=10
display $s |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Tcl | Tcl | puts "Enter a variable name:"
gets stdin varname
set $varname 42
puts "I have set variable $varname to [set $varname]" |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #TI-89_BASIC | TI-89 BASIC | Local varName,value
InputStr "Variable name", varName
Prompt value
value → #varName |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Ring | Ring | # Project : Draw a pixel
load "guilib.ring"
new qapp {
win1 = new qwidget() {
setwindowtitle("Drawing Pixels")
setgeometry(100,100,320,240)
label1 = new qlabel(win1) {
setgeometry(10,10,300,200)
... |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Robotic | Robotic |
. "Set the sprite's reference character located at the"
. "upper-left corner of the board (char 0)"
set "SPR0_REFX" to 0
set "SPR0_REFY" to 0
. "Offset that reference by 256, leading to the first character"
. "in the extended character set"
set "SPR0_OFFSET" to 256
. "Set the width and height of the sprite"
set "... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #Wren | Wren | import "/big" for BigInt, BigRat
var toEgyptianHelper // recursive
toEgyptianHelper = Fn.new { |n, d, fracs|
if (n == BigInt.zero) return
var divRem = d.divMod(n)
var div = divRem[0]
if (divRem[1] > BigInt.zero) div = div.inc
fracs.add(BigRat.new(BigInt.one, div))
var n2 = (-d) % n
if (n2 ... |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #zkl | zkl | fcn ethiopianMultiply(l,r){ // l is a non-negative integer
halve :=fcn(n){ n/2 };
double :=fcn(n){ n+n };
lr:=List(T(l,r)); // ( (l,r) .. (1,r*n) )
while(l>1){ lr.write( T(l=halve(l),r=double(r)) ) }
lr.filter(fcn([(l,r)]){ (not l.isEven) }); // strike out even left rows
.reduce(fcn(sum,[(l,r)]){ sum... |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #zkl | zkl | fcn fact(n){[2..n].reduce('*,1)}
fcn factTail(n,N=1) { // tail recursion
if (n == 0) return(N);
return(self.fcn(n-1,n*N));
} |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #X86_Assembly | X86 Assembly |
; x86_64 Linux NASM
global _start
%define af_inet 2
%define sock_stream 1
%define default_proto 0
%define sol_sock 1
%define reuse_addr 2
%define reuse_port 15
%define server_port 9001
%define addr_any 0
%define family_offset 0
%define port_offset 2
%define addr_offset 4
%define unused_offset 8
%define addr_len... |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #Wren | Wren | /* echo_server.wren */
var MAX_ENQUEUED = 20
var BUF_LEN = 256
var PORT_STR = "12321"
var AF_UNSPEC = 0
var SOCK_STREAM = 1
var AI_PASSIVE = 1
foreign class AddrInfo {
foreign static getAddrInfo(name, service, req, pai)
construct new() {}
foreign family
foreign family=(f)
foreign sockT... |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Processing | Processing | void setup() {
size(500, 500, P3D);
}
void draw() {
background(0);
// position
translate(width/2, height/2, -width/2);
// optional fill and lighting colors
noStroke();
strokeWeight(4);
fill(192, 255, 192);
pointLight(255, 255, 255, 0, -500, 500);
// rotation driven by built-in timer
rotateY(millis... |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Python | Python | from visual import *
scene.title = "VPython: Draw a rotating cube"
scene.range = 2
scene.autocenter = True
print "Drag with right mousebutton to rotate view."
print "Drag up+down with middle mousebutton to zoom."
deg45 = math.radians(45.0) # 0.785398163397
cube = box() # using defaults, see http://www.vpyth... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Standard_ML | Standard ML | structure Matrix = struct
local
open Array2
fun mapscalar f (x, scalar) =
tabulate RowMajor (nRows x, nCols x, fn (i,j) => f(sub(x,i,j),scalar))
fun map2 f (x, y) =
tabulate RowMajor (nRows x, nCols x, fn (i,j) => f(sub(x,i,j),sub(y,i,j)))
in
infix splus sminus stimes
val op splus = mapscalar Int.+
val o... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Stata | Stata | mata
a = rnormal(5,5,0,1)
b = 2
a:+b
a:-b
a:*b
a:/b
a:^b
a = rnormal(5,5,0,1)
b = rnormal(5,1,0,1)
a:+b
a:-b
a:*b
a:/b
a:^b
end |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #AutoHotkey | AutoHotkey | DIM SHARED angle AS DOUBLE
SUB turn (degrees AS DOUBLE)
angle = angle + degrees*3.14159265/180
END SUB
SUB forward (length AS DOUBLE)
LINE - STEP (COS(angle)*length, SIN(angle)*length), 7
END SUB
SUB dragon (length AS DOUBLE, split AS INTEGER, d AS DOUBLE)
IF split=0 THEN
forward length
EL... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #ContextFree | ContextFree |
startshape SPHERE
shape SPHERE {
CIRCLE[]
SPHERE[x 0.1% y 0.1%s 0.99 0.99 b 0.05]
}
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #PicoLisp | PicoLisp | # Insert an element X at position Pos
(de 2insert (X Pos DLst)
(let (Lst (nth (car DLst) (dec (* 2 Pos))) New (cons X (cadr Lst) Lst))
(if (cadr Lst)
(con (cdr @) New)
(set DLst New) )
(if (cdr Lst)
(set @ New)
(con DLst New) ) ) )
(setq *DL (2list 'A 'B)) # Bu... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #PL.2FI | PL/I |
define structure
1 Node,
2 value fixed decimal,
2 back_pointer handle(Node),
2 fwd_pointer handle(Node);
/* Given that 'Current" points at some node in the linked list : */
P = NEW (: Node :); /* Create a node. */
get (P => value);
P => fwd_pointer = Current => fwd_pointer;
... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Pop11 | Pop11 | define insert_double(list, element);
lvars tmp;
if list == [] then
;;; Insertion into empty list, return element
element
else
next(list) -> tmp;
list -> prev(element);
tmp -> next(element);
element -> next(list);
if tmp /= [] then
element -> prev(tmp)
en... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #PureBasic | PureBasic | Structure node
*prev.node
*next.node
value.c ;use character type for elements in this example
EndStructure
Procedure insertAfter(element.c, *c.node)
;insert new node *n after node *c and set it's value to element
Protected *n.node = AllocateMemory(SizeOf(node))
If *n
*n\value = element
*n\prev = *... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #C.23 | C# | using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class Clock : Form
{
static readonly float degrees06 = (float)Math.PI / 30;
static readonly float degrees30 = degrees06 * 5;
static readonly float degrees90 = degrees30 * 3;
readonly int margin = 2... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Nim | Nim | type
List[T] = object
head, tail: Node[T]
Node[T] = ref TNode[T]
TNode[T] = object
next, prev: Node[T]
data: T
proc initList[T](): List[T] = discard
proc newNode[T](data: T): Node[T] =
new(result)
result.data = data
proc prepend[T](l: var List[T], n: Node[T]) =
n.next = l.head
if l.h... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Oberon-2 | Oberon-2 |
MODULE Collections;
IMPORT Box;
TYPE
Action = PROCEDURE (o: Box.Object);
PROCEDURE (dll: DLList) GoForth*(do: Action);
VAR
iter: Node;
BEGIN
iter := dll.first;
WHILE iter # NIL DO
do(iter.value);
iter := iter.next
END
END GoForth;
PROCEDURE (dll: DLList) GoBack*(do: Action);
VAR
i... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Objeck | Objeck | class ListNode {
@value : Base;
@next : ListNode;
@previous: ListNode;
New(value : Base) {
@value := value;
}
method : public : Set(value : Base) ~ Nil {
@value := value;
}
method : public : Get() ~ Base {
return @value;
}
method : public : SetNext(next : Collection.ListNode) ~ ... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #OCaml | OCaml | type 'a dlink = {
mutable data: 'a;
mutable next: 'a dlink option;
mutable prev: 'a dlink option;
}
let dlink_of_list li =
let f prev_dlink x =
let dlink = {
data = x;
prev = None;
next = prev_dlink }
in
begin match prev_dlink with
| None -> ()
| Some prev_dlink ->
... |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #Icon_and_Unicon | Icon and Unicon | procedure main(a)
n := integer(!a) | 20
every (nr|nw|nb) := ?n-1
sIn := repl("r",nw)||repl("w",nb)||repl("b",nr)
write(sRand := bestShuffle(sIn))
write(sOut := map(csort(map(sRand,"rwb","123")),"123","rwb"))
if sIn ~== sOut then write("Eh? Not in correct order!")
end
procedure bestShuffle(s) ... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Frink | Frink | res = 254 / in
s = 1/2 inch res
v = callJava["frink.graphics.VoxelArray", "cube", [-s, s, -s, s, -s, s, true]]
v.projectX[undef].show["X"]
v.projectY[undef].show["Y"]
v.projectZ[undef].show["Z"]
filename = "cube.stl"
print["Writing $filename..."]
w = new Writer[filename]
w.println[v.toSTLFormat["cube", 1/(res mm... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
ASK "Enter variablename": name=""
ASK "Enter value": value=""
TRACE +@name
@name=$value
PRINT @name
|
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #UNIX_Shell | UNIX Shell | read name
declare $name=42
echo "${name}=${!name}" |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Wren | Wren | import "io" for Stdin, Stdout
var userVars = {}
System.print("Enter three variables:")
for (i in 0..2) {
System.write("\n name : ")
Stdout.flush()
var name = Stdin.readLine()
System.write(" value: ")
Stdout.flush()
var value = Num.fromString(Stdin.readLine())
userVars[name] = value
}
S... |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Ruby | Ruby | require 'gtk3'
Width, Height = 320, 240
PosX, PosY = 100, 100
window = Gtk::Window.new
window.set_default_size(Width, Height)
window.title = 'Draw a pixel'
window.signal_connect(:draw) do |widget, context|
context.set_antialias(Cairo::Antialias::NONE)
# paint out bg with white
# context.set_source_rgb(1.0, ... |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Rust | Rust | extern crate piston_window;
extern crate image;
use piston_window::*;
fn main() {
let (width, height) = (320, 240);
let mut window: PistonWindow =
WindowSettings::new("Red Pixel", [width, height])
.exit_on_esc(true).build().unwrap();
// Since we cant manipulate pixels directly, we ne... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #zkl | zkl | # Just compute the denominator terms, as the numerators are always 1
fcn egyptian(num,denom){
result,t := List(),Void;
t,num=num.divr(denom); // reduce fraction
if(t) result.append(T(t)); // signal t isn't a denominator
while(num){
# Compute ceil($denom/$num) without floating point inaccuracy
... |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #Z80_Assembly | Z80 Assembly | org &8000
ld hl,17
call Halve_Until_1
push bc
ld hl,34
call Double_Until_1
pop bc
call SumOddEntries
;returns Ethiopian product in IX.
call NewLine
call Primm
byte "0x",0
push ix
pop hl
ld a,H
call ShowHex
;Output should be in decimal but hex is easier.
ld a,L
call ShowHex
ret
H... |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET x=5: GO SUB 1000: PRINT "5! = ";r
999 STOP
1000 REM *************
1001 REM * FACTORIAL *
1002 REM *************
1010 LET r=1
1020 IF x<2 THEN RETURN
1030 FOR i=2 TO x: LET r=r*i: NEXT i
1040 RETURN |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #zkl | zkl | const PORT=12321;
pipe:=Thread.Pipe(); // how server tells thread to connect to user
fcn echo(socket){ // a thread, one per connection
text:=Data();
while(t:=socket.read()){
text.append(t);
if(text.find("\n",text.cursor)){ text.readln().print(); }
}
// socket was closed
}
// Set up the s... |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Racket | Racket | #lang racket/gui
(require math/matrix math/array)
(define (Rx θ)
(matrix [[1.0 0.0 0.0]
[0.0 (cos θ) (- (sin θ))]
[0.0 (sin θ) (cos θ)]]))
(define (Ry θ)
(matrix [[ (cos θ) 0.0 (sin θ)]
[ 0.0 1.0 0.0 ]
[(- (sin θ)) 0.0 (cos θ)]]))
(define (... |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Raku | Raku | use Terminal::Caca;
given my $canvas = Terminal::Caca.new {
.title('Rosetta Code - Rotating cube - Press any key to exit');
sub scale-and-translate($x, $y, $z) {
$x * 5 / ( 5 + $z ) * 15 + 40,
$y * 5 / ( 5 + $z ) * 7 + 15,
$z;
}
sub rotate3d-x( $x, $y, $z, $angle ) {
... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Tcl | Tcl | package require Tcl 8.5
proc alias {name args} {uplevel 1 [list interp alias {} $name {} {*}$args]}
# Engine for elementwise operations between matrices
proc elementwiseMatMat {lambda A B} {
set C {}
foreach rA $A rB $B {
set rC {}
foreach vA $rA vB $rB {
lappend rC [apply $lambda $vA $vB]
}
lappend ... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #BASIC | BASIC | DIM SHARED angle AS DOUBLE
SUB turn (degrees AS DOUBLE)
angle = angle + degrees*3.14159265/180
END SUB
SUB forward (length AS DOUBLE)
LINE - STEP (COS(angle)*length, SIN(angle)*length), 7
END SUB
SUB dragon (length AS DOUBLE, split AS INTEGER, d AS DOUBLE)
IF split=0 THEN
forward length
EL... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #D | D | import std.stdio, std.math, std.algorithm, std.numeric;
alias V3 = double[3];
immutable light = normalize([30.0, 30.0, -50.0]);
V3 normalize(V3 v) pure @nogc {
v[] /= dotProduct(v, v) ^^ 0.5;
return v;
}
double dot(in ref V3 x, in ref V3 y) pure nothrow @nogc {
immutable double d = dotProduct(x, y);
... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Python | Python | def insert(anchor, new):
new.next = anchor.next
new.prev = anchor
anchor.next.prev = new
anchor.next = new |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Racket | Racket | role DLElem[::T] {
has DLElem[T] $.prev is rw;
has DLElem[T] $.next is rw;
has T $.payload = T;
method pre-insert(T $payload) {
die "Can't insert before beginning" unless $!prev;
my $elem = ::?CLASS.new(:$payload);
$!prev.next = $elem;
$elem.prev = $!prev;
$elem... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #C.2B.2B | C++ |
#include <windows.h>
#include <string>
#include <math.h>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const int BMP_SIZE = 300, MY_TIMER... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Objeck | Objeck |
class Traverse {
function : Main(args : String[]) ~ Nil {
list := Collection.IntList->New();
list->Insert(100);
list->Insert(50);
list->Insert(25);
list->Insert(10);
list->Insert(5);
"-- forward --"->PrintLine();
list->Rewind();
while(list->More()) {
... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Oforth | Oforth | DList method: forEachNext
dup ifNull: [ drop @head ifNull: [ false ] else: [ @head @head true] return ]
next dup ifNull: [ drop false ] else: [ dup true ] ;
DList method: forEachPrev
dup ifNull: [ drop @tail ifNull: [ false ] else: [ @tail @tail true] return ]
prev dup ifNull: [ drop false ] else: [ dup t... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Oforth | Oforth | Object Class new: DNode(value, mutable prev, mutable next) |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Oz | Oz | fun {CreateNewNode Value}
node(prev:{NewCell _}
next:{NewCell _}
value:Value)
end |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Pascal | Pascal | type link_ptr = ^link;
data_ptr = ^data; (* presumes that type 'data' is defined above *)
link = record
prev: link_ptr;
next: link_ptr;
data: data_ptr;
end; |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Perl | Perl | my %node = (
data => 'say what',
next => \%foo_node,
prev => \%bar_node,
);
$node{next} = \%quux_node; # mutable |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #J | J | i2b=: {&(;:'red white blue') |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #Java | Java | import java.util.Arrays;
import java.util.Random;
public class DutchNationalFlag {
enum DutchColors {
RED, WHITE, BLUE
}
public static void main(String[] args){
DutchColors[] balls = new DutchColors[12];
DutchColors[] values = DutchColors.values();
Random rand = new Rando... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Go | Go | package main
import "fmt"
func cuboid(dx, dy, dz int) {
fmt.Printf("cuboid %d %d %d:\n", dx, dy, dz)
cubLine(dy+1, dx, 0, "+-")
for i := 1; i <= dy; i++ {
cubLine(dy-i+1, dx, i-1, "/ |")
}
cubLine(0, dx, dy, "+-|")
for i := 4*dz - dy - 2; i > 0; i-- {
cubLine(0, dx, dy, "| |"... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Z80_Assembly | Z80 Assembly | org &8000
WaitChar equ &BB06 ;Amstrad CPC BIOS call, loops until user presses a key. That key's ASCII value is returned in A.
PrintChar equ &BB5A ;Amstrad CPC BIOS call, A is treated as an ASCII value and is printed to the screen.
getInput:
call WaitChar
;returns key press in A
or a ;set flags according to ac... |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Scala | Scala | import java.awt.image.BufferedImage
import java.awt.Color
import scala.language.reflectiveCalls
object RgbBitmap extends App {
class RgbBitmap(val dim: (Int, Int)) {
def width = dim._1
def height = dim._2
private val image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
def ap... |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DEF FN e(a)=a-INT (a/2)*2-1
20 DEF FN h(a)=INT (a/2)
30 DEF FN d(a)=2*a
40 LET x=17: LET y=34: LET tot=0
50 IF x<1 THEN GO TO 100
60 PRINT x;TAB (4);
70 IF FN e(x)=0 THEN LET tot=tot+y: PRINT y: GO TO 90
80 PRINT "---"
90 LET x=FN h(x): LET y=FN d(y): GO TO 50
100 PRINT TAB (4);"===",TAB (4);tot |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Ring | Ring |
#===================================================================#
# Based on Original Sample from RayLib (https://www.raylib.com/)
# Ported to RingRayLib by Ring Team
#===================================================================#
load "raylib.ring"
screenWidth = 800
screenHeight = 450
InitWindow(scre... |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Scala | Scala | import java.awt.event.ActionEvent
import java.awt._
import javax.swing.{JFrame, JPanel, Timer}
import scala.math.{Pi, atan, cos, sin, sqrt}
object RotatingCube extends App {
class RotatingCube extends JPanel {
private val vertices: Vector[Array[Double]] =
Vector(Array(-1, -1, -1), Array(-1, -1, 1), ... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Vlang | Vlang | import math
struct Matrix {
mut:
ele []f64
stride int
}
fn matrix_from_rows(rows [][]f64) Matrix {
if rows.len == 0 {
return Matrix{[], 0}
}
mut m := Matrix{[]f64{len: rows.len*rows[0].len}, rows[0].len}
for rx, row in rows {
m.ele = m.ele[..rx*m.stride]
m.ele << row
m.ele <... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Wren | Wren | import "/fmt" for Fmt
import "/matrix" for Matrix
// matrix-matrix element wise ops
class MM {
static add(m1, m2) { m1 + m2 }
static sub(m1, m2) { m1 - m2 }
static mul(m1, m2) {
if (!m1.sameSize(m2)) Fiber.abort("Matrices must be of the same size.")
var m = Matrix.new(m1.numRows, m1.numC... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #BASIC256 | BASIC256 | # Version without functions (for BASIC-256 ver. 0.9.6.66)
graphsize 390,270
level = 18 : insize = 247 # initial values
x = 92 : y = 94 #
iters = 2^level # total number of iterations
qiter = 510/iters # constant for computing colors
SQ = sqrt(2) : QPI = pi/4 # constants
rotation = 0 : ite... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Delphi | Delphi |
program DrawASphere;
{$APPTYPE CONSOLE}
uses
SysUtils,
Math;
type
TDouble3 = array[0..2] of Double;
TChar10 = array[0..9] of Char;
var
shades: TChar10 = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@');
light: TDouble3 = (30, 30, -50 );
procedure normalize(var v: TDouble3);
var
len: D... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Raku | Raku | role DLElem[::T] {
has DLElem[T] $.prev is rw;
has DLElem[T] $.next is rw;
has T $.payload = T;
method pre-insert(T $payload) {
die "Can't insert before beginning" unless $!prev;
my $elem = ::?CLASS.new(:$payload);
$!prev.next = $elem;
$elem.prev = $!prev;
$elem... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #ContextFree | ContextFree |
startshape START
TIME_IN_SECONDS = 60
shape START {
SECOND_HAND[r (TIME_IN_SECONDS*-6)]
CIRCLE[s 50 50]
}
shape SECOND_HAND
{
TRIANGLE [[z 1 s 1 30 y 0.26 b 1]]
}
|
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Oz | Oz | declare
proc {Walk Node Action}
case Node of nil then skip
[] node(value:V next:N ...) then
{Action V}
{Walk @N Action}
end
end
proc {WalkBackwards Node Action}
Tail = {GetLast Node}
proc {Loop N}
case N of nil then skip
[] node(value:V prev:P ...) then
{Action V}
{Loop @P}
... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Pascal | Pascal | enum NEXT,PREV,DATA
constant empty_dll = {{1,1}}
sequence dll = deep_copy(empty_dll)
procedure insert_after(object data, integer pos=1)
integer prv = dll[pos][PREV]
dll = append(dll,{pos,prv,data})
if prv!=0 then
dll[prv][NEXT] = length(dll)
end if
dll[pos][PREV] = length(dll)
end procedur... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Phix | Phix | enum NEXT,PREV,DATA
type slnode(object x)
return (sequence(x) and length(x)=DATA and <i>udt</i>(x[DATA]) and integer(x[NEXT] and integer(x[PREV]))
end type
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #PicoLisp | PicoLisp | +-----+-----+ +-----+-----+
| Val | ---+---> | | | ---+---> next
+-----+-----+ +--+--+-----+
|
prev <---+
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #PL.2FI | PL/I |
define structure
1 Node,
2 value fixed decimal,
2 back_pointer handle(Node),
2 fwd_pointer handle(Node);
P = NEW(: Node :); /* Creates a node, and lets P point at it. */
get (P => value); /* Reads in a value to the node we just created. */
/* Assuming that back_pointer and fwd_... |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #JavaScript | JavaScript | const dutchNationalFlag = () => {
/**
* Return the name of the given number in this way:
* 0 = Red
* 1 = White
* 2 = Blue
* @param {!number} e
*/
const name = e => e > 1 ? 'Blue' : e > 0 ? 'White' : 'Red';
/**
* Given an array of numbers return true if each number is bigger than
* or t... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Haskell | Haskell | import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
-- Draw a cuboid. Its vertices are those of a unit cube, which is then scaled
-- to the required dimensions. We only specify the visible faces, each of
-- which is composed of two triangles. The faces are rotated into position and
-- rendered with a perspect... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #zkl | zkl | vname:="foo"; // or vname:=ask("var name = ");
klass:=Compiler.Compiler.compileText("var %s=123".fmt(vname))(); // compile & run the constructor
klass.vars.println();
klass.foo.println();
klass.setVar(vname).println(); // setVar(name,val) sets the var |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Zsh | Zsh | read name
typeset $name=42 |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #SmileBASIC | SmileBASIC | XSCREEN 3
DISPLAY 1
GPSET 100, 100, RGB(255, 0, 0)
WAIT 60 |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Standard_ML | Standard ML | open XWindows ;
open Motif ;
val imgWindow = fn () =>
let
val shell = XtAppInitialise "" "demo" "top" [] [ XmNwidth 320, XmNheight 240 ] ;
val main = XmCreateMainWindow shell "main" [ XmNmappedWhenManaged true ] ;
val canvas = XmCreateDrawingArea main "drawarea" [ XmNwidth 3... |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Tcl | Tcl | package require Tcl 8.5
package require Tk
pack [canvas .c -width 320 -height 240 -bg #fff] -anchor nw
.c create rectangle 100 100 100 100 -fill #f00 -outline "" |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Tcl | Tcl | # matrix operation support:
package require math::linearalgebra
namespace import ::math::linearalgebra::matmul
namespace import ::math::linearalgebra::crossproduct
namespace import ::math::linearalgebra::dotproduct
namespace import ::math::linearalgebra::sub
# returns a cube as a list of faces,
# where each face is a... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
M:=GSL.Matrix(3,3).set(3,5,7, 1,2,3, 2,4,6);
x:=2;
println("M = \n%s\nx = %s".fmt(M.format(),x));
foreach op in (T('+,'-,'*,'/)){
println("M %s x:\n%s\n".fmt(op.toString()[3,1],op(M.copy(),x).format()));
}
foreach op in (T("addElements","subElement... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #BBC_BASIC | BBC BASIC | MODE 8
MOVE 800,400
GCOL 11
PROCdragon(512, 12, 1)
END
DEF PROCdragon(size, split%, d)
PRIVATE angle
IF split% = 0 THEN
DRAW BY -COS(angle)*size, SIN(angle)*size
ELSE
angle += d*PI/4
PROCdragon(size/SQR(2), split%-1, 1)
angle -= d*P... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #DWScript | DWScript |
type
TFloat3 = array[0..2] of Float;
var
light : TFloat3 = [ 30, 30, -50 ];
procedure normalize(var v : TFloat3);
var
len: Float;
begin
len := sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len;
v[1] /= len;
v[2] /= len;
end;
function dot(x, y : TFloat3) : Float;
begin
Result := ... |
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.