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/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #Vlang | Vlang | struct Range {
start i64
end i64
print bool
}
fn main() {
rgs := [Range{2, 1000, true},
Range{1000, 4000, true},
Range{2, 10000, false},
Range{2, 100000, false},
Range{2, 1000000, false},
Range{2, 10000000, false},
Range{2, 100000000, false},
... |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #Wren | Wren | var rgs = [
[2, 1000, true],
[1000, 4000, true],
[2, 1e4, false],
[2, 1e5, false],
[2, 1e6, false],
[2, 1e7, false],
[2, 1e8, false],
[2, 1e9, false]
]
for (rg in rgs) {
if (rg[0] == 2) {
System.print("eban numbers up to and including %(rg[1])")
} else {
System.pr... |
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 ... | #Maple | Maple | plots:-display(
seq(
plots:-display(
plottools[cuboid]( [0,0,0], [1,1,1] ),
axes=none, scaling=constrained, orientation=[0,45,i] ),
i = 0..360, 20 ),
insequence=true ); |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Dynamic[
Graphics3D[
GeometricTransformation[
GeometricTransformation[Cuboid[], RotationTransform[Pi/4, {1, 1, 0}]],
RotationTransform[Clock[2 Pi], {0, 0, 1}]
],
Boxed -> False]] |
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 ... | #Racket | Racket | #lang racket(require math/array)
(define mat (list->array #(2 2) '(1 3 2 4)))
mat
(array+ mat (array 2))
(array* mat (array 2))
(array-map expt mat (array 2))
(array+ mat mat)
(array* mat mat)
(array-map expt mat mat)
|
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 ... | #Raku | Raku | my @a =
[1,2,3],
[4,5,6],
[7,8,9];
sub msay(@x) {
say .map( { ($_%1) ?? $_.nude.join('/') !! $_ } ).join(' ') for @x;
say '';
}
msay @a «+» @a;
msay @a «-» @a;
msay @a «*» @a;
msay @a «/» @a;
msay @a «+» [1,2,3];
msay @a «-» [1,2,3];
msay @a «*» [1,2,3];
msay @a «/» [1,2,3];
msay @a «+» 2;
msay ... |
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... | #Action.21 | Action! | DEFINE MAXSIZE="20"
INT ARRAY
xStack(MAXSIZE),yStack(MAXSIZE),
dxStack(MAXSIZE),dyStack(MAXSIZE)
BYTE ARRAY
dirStack(MAXSIZE),
depthStack(MAXSIZE),stageStack(MAXSIZE)
BYTE stacksize=[0]
BYTE FUNC IsEmpty()
IF stacksize=0 THEN RETURN (1) FI
RETURN (0)
BYTE FUNC IsFull()
IF stacksize=MAXSIZE THEN RETURN... |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { 30, 30, -50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double 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... | #Kotlin | Kotlin | // version 1.1.2
class Node<T: Number>(var data: T, var prev: Node<T>? = null, var next: Node<T>? = null) {
override fun toString(): String {
val sb = StringBuilder(this.data.toString())
var node = this.next
while (node != null) {
sb.append(" -> ", node.data.toString())
... |
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... | #Lua | Lua | ds = CreateDataStructure["DoublyLinkedList"];
ds["Append", "A"];
ds["Append", "B"];
ds["Append", "C"];
ds["SwapPart", 2, 3];
ds["Elements"] |
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... | #AutoHotkey | AutoHotkey | ; gdi+ ahk analogue clock example written by derRaphael
; Parts based on examples from Tic's GDI+ Tutorials and of course on his GDIP.ahk
; This code has been licensed under the terms of EUPL 1.0
#SingleInstance, Force
#NoEnv
SetBatchLines, -1
; Uncomment if Gdip.ahk is not in your standard library
;#Include, Gdi... |
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... | #Groovy | Groovy | class DoubleLinkedListTraversing {
static void main(args) {
def linkedList = (1..9).collect() as LinkedList
linkedList.each {
print it
}
println()
linkedList.reverseEach {
print it
}
}
} |
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... | #Haskell | Haskell | main = print . traverse True $ create [10,20,30,40]
data DList a = Leaf | Node { prev::(DList a), elt::a, next::(DList a) }
create = go Leaf
where go _ [] = Leaf
go prev (x:xs) = current
where current = Node prev x next
next = go current xs
isLeaf Leaf ... |
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
... | #Go | Go | type dlNode struct {
string
next, prev *dlNode
} |
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
... | #Haskell | Haskell |
data DList a = Leaf | Node (DList a) a (DList a)
updateLeft _ Leaf = Leaf
updateLeft Leaf (Node _ v r) = Node Leaf v r
updateLeft new@(Node nl _ _) (Node _ v r) = current
where current = Node prev v r
prev = updateLeft nl new
updateRight _ Leaf = Leaf
updateRight Leaf (Node l v _) = Node l v Leaf
... |
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
... | #Icon_and_Unicon | Icon and Unicon |
class DoubleLink (value, prev_link, next_link)
initially (value, prev_link, next_link)
self.value := value
self.prev_link := prev_link # links are 'null' if not given
self.next_link := next_link
end
|
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... | #Factor | Factor | USING: combinators grouping kernel math prettyprint random
sequences ;
: sorted? ( seq -- ? ) [ <= ] monotonic? ;
: random-non-sorted-integers ( length n -- seq )
2dup random-integers
[ dup sorted? ] [ drop 2dup random-integers ] while 2nip ;
: dnf-sort! ( seq -- seq' )
[ 0 0 ] dip [ length 1 - ] [ ] ... |
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... | #Forth | Forth | \ Dutch flag DEMO for CAMEL99 Forth
\ *SORTS IN PLACE FROM Video MEMORY*
INCLUDE DSK1.GRAFIX.F
INCLUDE DSK1.RANDOM.F
INCLUDE DSK1.CASE.F
\ TMS9918 Video chip Specific code
HEX
FFFF FFFF FFFF FFFF PATTERN: SQUARE
\ define colors and characters
DECIMAL
24 32 * CONSTANT SIZE \ flag will fill GRAPHICS screen
... |
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... | #D | D | import std.stdio, std.array;
void printCuboid(in int dx, in int dy, in int dz) {
static cline(in int n, in int dx, in int dy, in string cde) {
writef("%*s", n+1, cde[0 .. 1]);
write(cde[1 .. 2].replicate(9*dx - 1));
write(cde[0]);
writefln("%*s", dy+1, cde[2 .. $]);
}
cli... |
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.
| #Retro | Retro | :newVariable ("-) s:get var ;
newVariable: foo |
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.
| #REXX | REXX | /*REXX program demonstrates the use of dynamic variable names & setting a val.*/
parse arg newVar newValue
say 'Arguments as they were entered via the command line: ' newVar newValue
say
call value newVar, newValue
say 'The newly assigned value (as per the VALUE bif)------' newVar value(newVar)
... |
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 | #Python | Python | from PIL import Image
img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()
|
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 | #QB64 | QB64 | Screen _NewImage(320, 240, 32)
PSet (100, 100), _RGB(255, 0, 0) |
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... | #Swift | Swift | extension BinaryInteger {
@inlinable
public func egyptianDivide(by divisor: Self) -> (quo: Self, rem: Self) {
let table =
(0...).lazy
.map({i -> (Self, Self) in
let power = Self(2).power(Self(i))
return (power, power * divisor)
})
.prefix(while: { $0.1 <= self... |
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... | #Tailspin | Tailspin |
templates egyptianDivision
def dividend: $(1);
def divisor: $(2);
def table: [ { powerOf2: 1"1", doubling: ($divisor)"1" } -> \(
when <{doubling: <..$dividend>}> do
$ !
{ powerOf2: $.powerOf2 * 2, doubling: $.doubling * 2 } -> #
\)];
@: { answer: 0"1", accumulator: 0"1" };
$table(last..1:-... |
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... | #Scala | Scala | import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
abstract class Frac extends Comparable[Frac] {
val num: BigInt
val denom: BigInt
def toEgyptian: List[Frac] = {
if (num == 0) {
return List(this)
}
val fracs = new Arra... |
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 ... | #Vlang | Vlang | fn halve(i int) int { return i/2 }
fn double(i int) int { return i*2 }
fn is_even(i int) bool { return i%2 == 0 }
fn eth_multi(ii int, jj int) int {
mut r := 0
mut i, mut j := ii, jj
for ; i > 0; i, j = halve(i), double(j) {
if !is_even(i) {
r += j
}
}
return r
}
... |
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... | #XLISP | XLISP | (defun factorial (x)
(if (< x 0)
nil
(if (<= x 1)
1
(* x (factorial (- x 1))) ) ) ) |
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... | #Scala | Scala | import java.io.PrintWriter
import java.net.{ServerSocket, Socket}
import scala.io.Source
object EchoServer extends App {
private val serverSocket = new ServerSocket(23)
private var numConnections = 0
class ClientHandler(clientSocket: Socket) extends Runnable {
private val (connectionId, closeCmd) = ({nu... |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #Yabasic | Yabasic | data 2, 100, true
data 1000, 4000, true
data 2, 1e4, false
data 2, 1e5, false
data 2, 1e6, false
data 2, 1e7, false
data 2, 1e8, false
REM data 2, 1e9, false // it takes a lot of time
data 0, 0, false
do
read start, ended, printable
if not start break
if start = 2 then
Print "eban numbers up t... |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #zkl | zkl | rgs:=T( T(2, 1_000, True), // (start,end,print)
T(1_000, 4_000, True),
T(2, 1e4, False), T(2, 1e5, False), T(2, 1e6, False), T(2, 1e7, False),
T(2, 1e8, False), T(2, 1e9, False), // slow and very slow
);
foreach start,end,pr in (rgs){
if(start==2) println("eban numbers up to and inclu... |
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 ... | #Nim | Nim | import math
import sdl2
const
Width = 500
Height = 500
Offset = 500 / 2
var nodes = [(x: -100.0, y: -100.0, z: -100.0),
(x: -100.0, y: -100.0, z: 100.0),
(x: -100.0, y: 100.0, z: -100.0),
(x: -100.0, y: 100.0, z: 100.0),
(x: 100.0, y: -100.0, z: -100.0)... |
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 ... | #Objeck | Objeck | #~
Rotating Cube
~#
use Collection.Generic;
use Game.SDL2;
use Game.Framework;
class RotatingCube {
# game framework
@framework : GameFramework;
@initialized : Bool;
@nodes : Float[,];
@edges : Int[,];
New() {
@initialized := true;
@framework := GameFramework->New(GameConsts->SCREEN_WIDTH, G... |
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 ... | #REXX | REXX | /*REXX program multiplies two matrices together, displays the matrices and the result.*/
m= (1 2 3) (4 5 6) (7 8 9)
w= words(m); do rows=1; if rows*rows>=w then leave
end /*rows*/
cols= rows
call showMat M, 'M matrix'
answer= matAdd(m, 2 ); call showMat ... |
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... | #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
STRUCT (REAL x, y, heading, BOOL pen down) turtle;
PROC turtle init = VOID: (
draw erase (window);
turtle := (0.5, 0.5, 0, TRUE);
draw move (window, x OF turtle, y OF turtle);
draw colour name(window, "white")
);
PROC turtle left = (REAL left turn)VOID:
heading OF turtle +:= le... |
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
| #C.23 | C# | using System;
namespace Sphere {
internal class Program {
private const string Shades = ".:!*oe%&#@";
private static readonly double[] Light = {30, 30, -50};
private static void Normalize(double[] v) {
double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ds = CreateDataStructure["DoublyLinkedList"];
ds["Append", "A"];
ds["Append", "B"];
ds["Append", "C"];
ds["SwapPart", 2, 3];
ds["Elements"] |
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... | #Nim | Nim | proc insertAfter[T](l: var List[T], r, n: Node[T]) =
n.prev = r
n.next = r.next
n.next.prev = n
r.next = n
if r == l.tail: l.tail = n |
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... | #Oberon-2 | Oberon-2 |
PROCEDURE (dll: DLList) InsertAfter*(p: Node; o: Box.Object);
VAR
n: Node;
BEGIN
n := NewNode(o);
n.prev := p;
n.next := p.next;
IF p.next # NIL THEN p.next.prev := n END;
p.next := n;
IF p = dll.last THEN dll.last := n END;
INC(dll.size)
END InsertAfter;
|
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... | #AWK | AWK |
# syntax: GAWK -f DRAW_A_CLOCK.AWK [-v xc="*"]
BEGIN {
# clearscreen_cmd = "clear" ; sleep_cmd = "sleep 1s" # Unix
clearscreen_cmd = "CLS" ; sleep_cmd = "TIMEOUT /T 1 >NUL" # MS-Windows
clock_build_digits()
while (1) {
now = strftime("%H:%M:%S")
t[1] = substr(now,1,1)
t[2] = substr(now... |
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... | #Icon_and_Unicon | Icon and Unicon | class DoubleLink (value, prev_link, next_link)
# insert given node after this one, removing its existing connections
method insert_after (node)
node.prev_link := self
if (\next_link) then next_link.prev_link := node
node.next_link := next_link
self.next_link := node
end
# use a generator to ... |
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... | #J | J | traverse=:1 :0
work=. result=. conew 'DoublyLinkedListHead'
current=. y
while. y ~: current=. successor__current do.
work=. (work;result;<u data__current) conew 'DoublyLinkedListElement'
end.
result
) |
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
... | #J | J | coclass'DoublyLinkedListElement'
create=:3 :0
this=:coname''
'predecessor successor data'=:y
successor__predecessor=: predecessor__successor=: this
) |
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
... | #Java | Java | public class Node<T> {
private T element;
private Node<T> next, prev;
public Node<T>(){
next = prev = element = null;
}
public Node<T>(Node<T> n, Node<T> p, T elem){
next = n;
prev = p;
element = elem;
}
public void setNext(Node<T> n){
next = n;
}
public ... |
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... | #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon Jun 3 11:18:24
!
!a=./f && make FFLAGS='-O0 -g' $a && OMP_NUM_THREADS=2 $a < unixdict.txt
!gfortran -std=f2008 -O0 -g -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
! Original and flag sequences
! WHITE RED b... |
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... | #FreeBASIC | FreeBASIC |
' El problema planteado por Edsger Dijkstra es:
' "Dado un número de bolas rojas, azules y blancas en orden aleatorio,
' ordénelas en el orden de los colores de la bandera nacional holandesa."
Dim As String c = "RBW", n = "121509"
Dim As Integer bolanum = 9
Dim As Integer d(bolanum), k, i, j
Randomize Timer
Colo... |
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... | #Delphi | Delphi |
program Draw_a_cuboid;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
procedure cubLine(n, dx, dy: Integer; cde: string);
var
i: integer;
begin
write(format('%' + (n + 1).ToString + 's', [cde.Substring(0, 1)]));
for i := 9 * dx - 1 downto 1 do
Write(cde.Substring(1, 1));
Write(cde.Substring(0, 1));
... |
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.
| #Ring | Ring |
See "Enter the variable name: " give cName eval(cName+"=10")
See "The variable name = " + cName + " and the variable value = " + eval("return "+cName) + nl
|
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.
| #RLaB | RLaB | >> s = "myusername"
myusername
>> $$.[s] = 10;
>> myusername
10 |
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.
| #Ruby | Ruby | p "Enter a variable name"
x = "@" + gets.chomp!
instance_variable_set x, 42
p "The value of #{x} is #{instance_variable_get x}"
|
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 | #QBasic | QBasic | ' http://rosettacode.org/wiki/Draw_a_pixel
' This program can run in QBASIC, QuickBASIC, gw-BASIC (adding line numbers) and VB-DOS
SCREEN 1
COLOR , 0
PSET (100, 100), 2
END |
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 | #Racket | Racket | #lang racket
(require racket/draw)
(let ((b (make-object bitmap% 320 240)))
(send b set-argb-pixels 100 100 1 1 (bytes 255 0 0 255))
b) |
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... | #VBA | VBA | Option Explicit
Private Type MyTable
powers_of_2 As Long
doublings As Long
End Type
Private Type Assemble
answer As Long
accumulator As Long
End Type
Private Type Division
Quotient As Long
Remainder As Long
End Type
Private Type DivEgyp
Dividend As Long
Divisor As Long
End Type
... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function EgyptianDivision(dividend As ULong, divisor As ULong, ByRef remainder As ULong) As ULong
Const SIZE = 64
Dim powers(SIZE) As ULong
Dim doublings(SIZE) As ULong
Dim i = 0
While i < SIZE
powers(i) = 1 << i
doublings(i) = divis... |
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... | #Sidef | Sidef | func ef(fr) {
var ans = []
if (fr >= 1) {
return([fr]) if (fr.is_int)
var intfr = fr.int
ans << intfr
fr -= intfr
}
var (x, y) = fr.nude
while (x != 1) {
ans << fr.inv.ceil.inv
fr = ((-y % x) / y*fr.inv.ceil)
(x, y) = fr.nude
}
ans << fr
return ans
}
for fr in [43/48, 5/121... |
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 ... | #Wren | Wren | var halve = Fn.new { |n| (n/2).truncate }
var double = Fn.new { |n| n * 2 }
var isEven = Fn.new { |n| n%2 == 0 }
var ethiopian = Fn.new { |x, y|
var sum = 0
while (x >= 1) {
if (!isEven.call(x)) sum = sum + y
x = halve.call(x)
y = double.call(y)
}
return sum
}
System.prin... |
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... | #XPL0 | XPL0 | func FactIter(N); \Factorial of N using iterative method
int N; \range: 0..12
int F, I;
[F:= 1;
for I:= 2 to N do F:= F*I;
return F;
];
func FactRecur(N); \Factorial of N using recursive method
int N; \range: 0..12
return if N<2 then 1 else N*FactRecur(N-1); |
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... | #Scheme | Scheme | ; Needed in Guile for read-line
(use-modules (ice-9 rdelim))
; Variable used to hold child PID returned from forking
(define child #f)
; Start listening on port 12321 for connections from any address
(let ((s (socket PF_INET SOCK_STREAM 0)))
(setsockopt s SOL_SOCKET SO_REUSEADDR 1)
(bind s AF_INET INADDR_ANY 12... |
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 ... | #OxygenBasic | OxygenBasic |
% Title "Rotating Cube"
% Animated
% PlaceCentral
uses ConsoleG
sub main
========
cls 0.0, 0.5, 0.7
shading
scale 7
pushstate
GoldMaterial.act
static float ang
rotateX ang
rotateY ang
go cube
popstate
ang+=.5 : if ang>=360 then ang-=360
end sub
EndScript
|
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 ... | #Perl | Perl | #!/usr/bin/perl
use strict; # http://www.rosettacode.org/wiki/Draw_a_rotating_cube
use warnings;
use Tk;
use Time::HiRes qw( time );
my $size = 600;
my $wait = int 1000 / 30;
my ($height, $width) = ($size, $size * sqrt 8/9);
my $mid = $width / 2;
my $rot = atan2(0, -1) / 3; # middle c... |
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 ... | #Ruby | Ruby | require 'matrix'
class Matrix
def element_wise( operator, other )
Matrix.build(row_size, column_size) do |row, col|
self[row, col].send(operator, other[row, col])
end
end
end
m1, m2 = Matrix[[3,1,4],[1,5,9]], Matrix[[2,7,1],[8,2,2]]
puts "m1: #{m1}\nm2: #{m2}\n\n"
[:+, :-, :*, :/, :fdiv, :**, :%... |
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... | #AmigaE | AmigaE | 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
| #C.2B.2B | C++ | // Based on https://www.cairographics.org/samples/gradient/
#include <QImage>
#include <QPainter>
int main() {
const QColor black(0, 0, 0);
const QColor white(255, 255, 255);
const int size = 300;
const double diameter = 0.6 * size;
QImage image(size, size, QImage::Format_RGB32);
QPainte... |
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... | #Objeck | Objeck | method : public : native : AddBack(value : Base) ~ Nil {
node := ListNode->New(value);
if(@head = Nil) {
@head := node;
@tail := @head;
}
else {
@tail->SetNext(node);
node->SetPrevious(@tail);
@tail := node;
};
} |
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... | #OCaml | OCaml | (* val _insert : 'a dlink -> 'a dlink -> unit *)
let _insert anchor newlink =
newlink.next <- anchor.next;
newlink.prev <- Some anchor;
begin match newlink.next with
| None -> ()
| Some next ->
next.prev <-Some newlink;
end;
anchor.next <- Some newlink;;
(* val insert : 'a dlink option -> 'a -> un... |
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... | #BASIC | BASIC | xp=320:yp=95:size=150
CIRCLE (xp,yp),size,,,,.5
lasth=0:lastm=0:lasts=0
hs=.25*size:ms=.45*size:ss=ms
pi=3.141592
FOR i=1 TO 12
w=2*i*pi/12
CIRCLE (xp+size*SIN(w),yp+size/2*COS(w)),size/15
NEXT
ON TIMER(1) GOSUB Clock
TIMER ON
loop: GOTO loop
Clock:
t$=TIME$
h=VAL(MID$(t$,1,2))
m=VAL(MID$(t$,4,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... | #Java | Java |
package com.rosettacode;
import java.util.LinkedList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class DoubleLinkedListTraversing {
public static void main(String[] args) {
final LinkedList<String> doubleLinkedList =
IntStream.range(1, 10)
.mapToObj... |
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... | #JavaScript | JavaScript | DoublyLinkedList.prototype.getTail = function() {
var tail;
this.traverse(function(node){tail = node;});
return tail;
}
DoublyLinkedList.prototype.traverseBackward = function(func) {
func(this);
if (this.prev() != null)
this.prev().traverseBackward(func);
}
DoublyLinkedList.prototype.printB... |
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
... | #JavaScript | JavaScript | function DoublyLinkedList(value, next, prev) {
this._value = value;
this._next = next;
this._prev = prev;
}
// from LinkedList, inherit: value(), next(), traverse(), print()
DoublyLinkedList.prototype = new LinkedList();
DoublyLinkedList.prototype.prev = function() {
if (arguments.length == 1)
... |
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
... | #Julia | Julia | abstract type AbstractNode{T} end
struct EmptyNode{T} <: AbstractNode{T} end
mutable struct Node{T} <: AbstractNode{T}
value::T
pred::AbstractNode{T}
succ::AbstractNode{T}
end |
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... | #Gambas | Gambas | Public Sub Main()
Dim Red As String = "0"
Dim White As String = "1"
Dim Blue As String = "2"
Dim siCount As Short
Dim sColours As New String[]
Dim sTemp As String
For siCount = 1 To 20
sColours.Add(Rand(Red, Blue))
Next
Print "Random: - ";
For siCount = 1 To 2
For Each sTemp In sColours
If sTemp = Red The... |
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... | #Elixir | Elixir | defmodule Cuboid do
@x 6
@y 2
@z 3
@dir %{-: {1,0}, |: {0,1}, /: {1,1}}
def draw(nx, ny, nz) do
IO.puts "cuboid #{nx} #{ny} #{nz}:"
{x, y, z} = {@x*nx, @y*ny, @z*nz}
area = Map.new
area = Enum.reduce(0..nz-1, area, fn i,acc -> draw_line(acc, x, 0, @z*i, :-) end)
area = Enum.reduce... |
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.
| #Scheme | Scheme | => (define (create-variable name initial-val)
(eval `(define ,name ,initial-val) (interaction-environment)))
=> (create-variable (read) 50)
<hello
=> hello
50 |
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.
| #Sidef | Sidef | var name = read("Enter a variable name: ", String); # type in 'foo'
class DynamicVar(name, value) {
method init {
DynamicVar.def_method(name, ->(_) { value })
}
}
var v = DynamicVar(name, 42); # creates a dynamic variable
say v.foo; # retrieves the value |
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 | #Raku | Raku | use GTK::Simple;
use GTK::Simple::DrawingArea;
use Cairo;
my $app = GTK::Simple::App.new(:title('Draw a Pixel'));
my $da = GTK::Simple::DrawingArea.new;
gtk_simple_use_cairo;
$app.set-content( $da );
$app.border-width = 5;
$da.size-request(320,240);
sub rect-do( $d, $ctx ) {
given $ctx {
.rgb(1, 0, 0... |
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... | #Vlang | Vlang | fn egyptian_divide(dividend int, divisor int) ?(int, int) {
if dividend < 0 || divisor <= 0 {
panic("Invalid argument(s)")
}
if dividend < divisor {
return 0, dividend
}
mut powers_of_two := [1]
mut doublings := [divisor]
mut doubling := divisor
for {
doubling *... |
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... | #Wren | Wren | var egyptianDivide = Fn.new { |dividend, divisor|
if (dividend < 0 || divisor <= 0) Fiber.abort("Invalid argument(s).")
if (dividend < divisor) return [0, dividend]
var powersOfTwo = [1]
var doublings = [divisor]
var doubling = divisor
while (true) {
doubling = 2 * doubling
if (d... |
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... | #Tcl | Tcl | # Just compute the denominator terms, as the numerators are always 1
proc egyptian {num denom} {
set result {}
while {$num} {
# Compute ceil($denom/$num) without floating point inaccuracy
set term [expr {$denom / $num + ($denom/$num*$num < $denom)}]
lappend result $term
set num [expr {-$denom % $num}]
set ... |
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 ... | #x86_Assembly | x86 Assembly | extern printf
global main
section .text
halve
shr ebx, 1
ret
double
shl ebx, 1
ret
iseven
and ebx, 1
cmp ebx, 0
ret ; ret preserves flags
main
push 1 ; tutor = true
push 34 ; 2nd operand
push 17 ; 1st operand
call ethiopicmult
add esp, 12
push eax ; result of 17*34
push fmt
call pri... |
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... | #Yabasic | Yabasic | // recursive
sub factorial(n)
if n > 1 then return n * factorial(n - 1) else return 1 end if
end sub
//iterative
sub factorial2(n)
local i, t
t = 1
for i = 1 to n
t = t * i
next
return t
end sub
for n = 0 to 9
print "Factorial(", n, ") = ", factorial(n)
next |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "socket.s7i";
include "listener.s7i";
const proc: main is func
local
var listener: aListener is listener.value;
var file: existingConnection is STD_NULL;
var file: newConnection is STD_NULL;
begin
aListener := openInetListener(12321);
listen(aListener, 10)... |
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 ... | #Phix | Phix | --
-- demo\rosetta\DrawRotatingCube.exw
-- =================================
--
-- credits: http://petercollingridge.appspot.com/3D-tutorial/rotating-objects
-- https://github.com/ssloy/tinyrenderer/wiki/Lesson-4:-Perspective-projection
--
-- Aside: low CPU usage, at least when using a 30ms timer (33 FPS, whic... |
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 ... | #Rust | Rust | struct Matrix {
elements: Vec<f32>,
pub height: u32,
pub width: u32,
}
impl Matrix {
fn new(elements: Vec<f32>, height: u32, width: u32) -> Matrix {
// Should check for dimensions but omitting to be succient
Matrix {
elements: elements,
height: height,
... |
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... | #Applesoft_BASIC | Applesoft 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
| #Clojure | Clojure |
(use 'quil.core)
(def w 500)
(def h 400)
(defn setup []
(background 0))
(defn draw []
(push-matrix)
(translate 250 200 0)
(sphere 100)
(pop-matrix))
(defsketch main
:title "sphere"
:setup setup
:size [w h]
:draw draw
:renderer :opengl)
|
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... | #Oforth | Oforth | : test // ( -- aDList )
| dl |
DList new ->dl
dl insertFront("A")
dl insertBack("B")
dl head insertAfter(DNode new("C", null , null))
dl ; |
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... | #Oz | Oz | declare
fun {CreateNewNode Value}
node(prev:{NewCell nil}
next:{NewCell nil}
value:Value)
end
proc {InsertAfter Node NewNode}
Next = Node.next
in
(NewNode.next) := @Next
(NewNode.prev) := Node
case @Next of nil then skip
[] node(prev:NextPrev ...) then
... |
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... | #Pascal | Pascal | procedure insert_link( a, b, c: link_ptr );
begin
a^.next := c;
if b <> nil then b^.prev := c;
c^.next := b;
c^.prev := a;
end; |
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... | #Batch_File | Batch File | ::Draw a Clock Task from Rosetta Code Wiki
::Batch File Implementation
::
::Directly open the Batch File...
@echo off & mode 44,8
title Sample Batch Clock
setlocal enabledelayedexpansion
chcp 65001
::Set the characters...
set "#0_1=█████"
set "#0_2=█ █"
set "#0_3=█ █"
set "#0_4=█ █"
set "#0_5=█████"
set "#1_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... | #Julia | Julia | mutable struct DLNode{T}
value::T
pred::Union{DLNode{T}, Nothing}
succ::Union{DLNode{T}, Nothing}
DLNode(v) = new{typeof(v)}(v, nothing, nothing)
end
function insertpost(prevnode, node)
succ = prevnode.succ
prevnode.succ = node
node.pred = prevnode
node.succ = succ
if succ != nothi... |
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... | #Kotlin | Kotlin | // version 1.1.2
class LinkedList<E> {
class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) {
override fun toString(): String {
val sb = StringBuilder(this.data.toString())
var node = this.next
while (node != null) {
sb.append... |
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
... | #Kotlin | Kotlin | // version 1.1.2
class Node<T: Number>(var data: T, var prev: Node<T>? = null, var next: Node<T>? = null) {
override fun toString(): String {
val sb = StringBuilder(this.data.toString())
var node = this.next
while (node != null) {
sb.append(" -> ", node.data.toString())
... |
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
... | #Lua | Lua | local node = { data=data, prev=nil, next=nil } |
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... | #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
// constants define order of colors in Dutch national flag
const (
red = iota
white
blue
nColors
)
// zero object of type is valid red ball.
type ball struct {
color int
}
// order of balls based on DNF
func (b1 ball) lt(b2 ball) b... |
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... | #Factor | Factor | USING: classes.struct kernel raylib.ffi ;
640 480 "cuboid" init-window
S{ Camera3D
{ position S{ Vector3 f 4.5 4.5 4.5 } }
{ target S{ Vector3 f 0 0 0 } }
{ up S{ Vector3 f 0 1 0 } }
{ fovy 45.0 }
{ type 0 }
}
60 set-target-fps
[ window-should-close ] [
begin-drawing
BLACK clear-... |
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.
| #Slate | Slate | define: #name -> (query: 'Enter a variable name: ') intern. "X"
define: name -> 42.
X print. |
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.
| #Smalltalk | Smalltalk | | varName |
varName := FillInTheBlankMorph
request: 'Enter a variable name'.
Compiler
evaluate:('| ', varName, ' | ', varName, ' := 42.
Transcript
show: ''value of ', varName, ''';
show: '' is '';
show: ', 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.
| #SNOBOL4 | SNOBOL4 | * # Get var name from user
output = 'Enter variable name:'
invar = trim(input)
* # Get value from user, assign
output = 'Enter value:'
$invar = trim(input)
* Display
output = invar ' == ' $invar
end |
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 | #ReScript | ReScript | type document // abstract type for a document object
type context = { mutable fillStyle: string, }
@val external doc: document = "document"
@send external getElementById: (document, string) => Dom.element = "getElementById"
@send external getContext: (Dom.element, string) => context = "getContext"
@send external... |
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 | #REXX | REXX | /*REXX program displays (draws) a pixel at a specified screen location in the color red.*/
parse upper version !ver .
!pcrexx= 'REXX/PERSONAL'==!ver | 'REXX/PC'==!ver /*obtain the REXX interpreter version. */
parse arg x y txt CC . /*obtain optional arguments from the CL*/
if x=='' | x==","... |
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.