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 billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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}, Range{2, 1000000000, false}, ] for rg in rgs { if rg.start == 2 { println("eban numbers up to and including $rg.end:") } else { println("eban numbers between $rg.start and $rg.end (inclusive):") } mut count := 0 for i := rg.start; i <= rg.end; i += 2 { b := i / 1000000000 mut r := i % 1000000000 mut m := r / 1000000 r = i % 1000000 mut t := r / 1000 r %= 1000 if m >= 30 && m <= 66 { m %= 10 } if t >= 30 && t <= 66 { t %= 10 } if r >= 30 && r <= 66 { r %= 10 } if b == 0 || b == 2 || b == 4 || b == 6 { if m == 0 || m == 2 || m == 4 || m == 6 { if t == 0 || t == 2 || t == 4 || t == 6 { if r == 0 || r == 2 || r == 4 || r == 6 { if rg.print { print("$i ") } count++ } } } } } if rg.print { println('') } println("count = $count\n") } }
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 billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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.print("eban numbers between %(rg[0]) and %(rg[1]) (inclusive):") } var count = 0 var i = rg[0] while (i <= rg[1]) { var b = (i/1e9).floor var r = i % 1e9 var m = (r/1e6).floor r = i % 1e6 var t = (r/1000).floor r = r % 1000 if (m >= 30 && m <= 66) m = m % 10 if (t >= 30 && t <= 66) t = t % 10 if (r >= 30 && r <= 66) r = r % 10 if (b == 0 || b == 2 || b == 4 || b == 6) { if (m == 0 || m == 2 || m == 4 || m == 6) { if (t == 0 || t == 2 || t == 4 || t == 6) { if (r == 0 || r == 2 || r == 4 || r == 6) { if (rg[2]) System.write("%(i) ") count = count + 1 } } } } i = i + 2 } if (rg[2]) System.print() System.print("count = %(count)\n") }
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 tasks Draw a cuboid write language name in 3D ASCII
#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 tasks Draw a cuboid write language name in 3D ASCII
#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 necessary to include additional basic operations, which should not require their own specialised task.
#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 necessary to include additional basic operations, which should not require their own specialised task.
#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 @a «-» 2; msay @a «*» 2; msay @a «/» 2;   # In addition to calling the underlying higher-order functions directly, it's possible to name a function.   sub infix:<M+> (\l,\r) { l <<+>> r }   msay @a M+ @a; msay @a M+ [1,2,3]; msay @a M+ 2;  
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 angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#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 (1) FI RETURN (0)   PROC Push(INT x,y,dx,dy BYTE dir,depth,stage) IF IsFull() THEN Break() FI xStack(stacksize)=x yStack(stacksize)=y dxStack(stacksize)=dx dyStack(stacksize)=dy dirStack(stacksize)=dir depthStack(stacksize)=depth stageStack(stackSize)=stage stacksize==+1 RETURN   PROC Pop(INT POINTER x,y,dx,dy BYTE POINTER dir,depth,stage) IF IsEmpty() THEN Break() FI stacksize==-1 x^=xStack(stacksize) y^=yStack(stacksize) dx^=dxStack(stacksize) dy^=dyStack(stacksize) dir^=dirStack(stacksize) depth^=depthStack(stacksize) stage^=stageStack(stacksize) RETURN   PROC DrawDragon(INT x,y,dx,dy BYTE depth) BYTE dir,stage INT nx,ny,dx2,dy2,tmp   Push(x,y,dx,dy,1,depth,0)   WHILE IsEmpty()=0 DO Pop(@x,@y,@dx,@dy,@dir,@depth,@stage) IF depth=0 THEN Plot(x,y) DrawTo(x+dx,y+dy) ELSE IF stage<2 THEN Push(x,y,dx,dy,dir,depth,stage+1) FI nx=dx/2 ny=dy/2 dx2=nx-ny dy2=nx+ny IF stage=0 THEN IF dir THEN Push(x,y,dx2,dy2,1,depth-1,0) ELSE Push(x,y,dy2,-dx2,1,depth-1,0) FI ELSEIF stage=1 THEN IF dir THEN tmp=-dx2 ;to avoid the compiler error Push(x+dx2,y+dy2,dy2,tmp,0,depth-1,0) ELSE Push(x+dy2,y-dx2,dx2,dy2,0,depth-1,0) FI FI FI OD RETURN   PROC Main() BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6   Graphics(8+16) Color=1 COLOR1=$0C COLOR2=$02   DrawDragon(104,72,128,0,12)   DO UNTIL CH#$FF OD CH=$FF 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 dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; }   void draw_sphere(double R, double k, double ambient) { int i, j, intensity; double b; double vec[3], x, y; for (i = floor(-R); i <= ceil(R); i++) { x = i + .5; for (j = floor(-2 * R); j <= ceil(2 * R); j++) { y = j / 2. + .5; if (x * x + y * y <= R * R) { vec[0] = x; vec[1] = y; vec[2] = sqrt(R * R - x * x - y * y); normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } else putchar(' '); } putchar('\n'); } }     int main() { normalize(light); draw_sphere(20, 4, .1); draw_sphere(10, 2, .4);   return 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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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()) node = node.next } return sb.toString() } }   fun <T: Number> insert(after: Node<T>, new: Node<T>) { new.next = after.next if (after.next != null) after.next!!.prev = new new.prev = after after.next = new }   fun main(args: Array<String>) { val a = Node(1) val b = Node(3, a) a.next = b println("Before insertion : $a") val c = Node(2) insert(after = a, new = c) println("After insertion : $a") }
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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#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, Gdip.ahk   If !pToken := Gdip_Startup() { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp } OnExit, Exit   SysGet, MonitorPrimary, MonitorPrimary SysGet, WA, MonitorWorkArea, %MonitorPrimary% WAWidth := WARight-WALeft WAHeight := WABottom-WATop   Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs Gui, 1: Show, NA hwnd1 := WinExist()   ClockDiameter := 180 Width := Height := ClockDiameter + 2 ; make width and height slightly bigger to avoid cut away edges CenterX := CenterY := floor(ClockDiameter/2) ; Center x   ; Prepare our pGraphic so we have a 'canvas' to work upon hbm := CreateDIBSection(Width, Height), hdc := CreateCompatibleDC() obm := SelectObject(hdc, hbm), G := Gdip_GraphicsFromHDC(hdc) Gdip_SetSmoothingMode(G, 4)   ; Draw outer circle Diameter := ClockDiameter pBrush := Gdip_BrushCreateSolid(0x66008000) Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) Gdip_DeleteBrush(pBrush)   ; Draw inner circle Diameter := ceil(ClockDiameter - ClockDiameter*0.08) ; inner circle is 8 % smaller than clock's diameter pBrush := Gdip_BrushCreateSolid(0x80008000) Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) Gdip_DeleteBrush(pBrush)   ; Draw Second Marks R1 := Diameter//2-1 ; outer position R2 := Diameter//2-1-ceil(Diameter//2*0.05) ; inner position Items := 60 ; we have 60 seconds pPen := Gdip_CreatePen(0xff00a000, floor((ClockDiameter/100)*1.2)) ; 1.2 % of total diameter is our pen width GoSub, DrawClockMarks Gdip_DeletePen(pPen)   ; Draw Hour Marks R1 := Diameter//2-1 ; outer position R2 := Diameter//2-1-ceil(Diameter//2*0.1) ; inner position Items := 12 ; we have 12 hours pPen := Gdip_CreatePen(0xc0008000, ceil((ClockDiameter//100)*2.3)) ; 2.3 % of total diameter is our pen width GoSub, DrawClockMarks Gdip_DeletePen(pPen)   ; The OnMessage will let us drag the clock OnMessage(0x201, "WM_LBUTTONDOWN") UpdateLayeredWindow(hwnd1, hdc, WALeft+((WAWidth-Width)//2), WATop+((WAHeight-Height)//2), Width, Height) SetTimer, sec, 1000   sec: ; prepare to empty previously drawn stuff Gdip_SetSmoothingMode(G, 1) ; turn off aliasing Gdip_SetCompositingMode(G, 1) ; set to overdraw   ; delete previous graphic and redraw background Diameter := ceil(ClockDiameter - ClockDiameter*0.18) ; 18 % less than clock's outer diameter   ; delete whatever has been drawn here pBrush := Gdip_BrushCreateSolid(0x00000000) ; fully transparent brush 'eraser' Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) Gdip_DeleteBrush(pBrush)   Gdip_SetCompositingMode(G, 0) ; switch off overdraw pBrush := Gdip_BrushCreateSolid(0x66008000) Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) Gdip_DeleteBrush(pBrush) pBrush := Gdip_BrushCreateSolid(0x80008000) Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) Gdip_DeleteBrush(pBrush)   ; Draw HoursPointer Gdip_SetSmoothingMode(G, 4) ; turn on antialiasing t := A_Hour*360//12 + (A_Min*360//60)//12 +90 R1 := ClockDiameter//2-ceil((ClockDiameter//2)*0.5) ; outer position pPen := Gdip_CreatePen(0xa0008000, floor((ClockDiameter/100)*3.5)) Gdip_DrawLine(G, pPen, CenterX, CenterY , ceil(CenterX - (R1 * Cos(t * Atan(1) * 4 / 180))) , ceil(CenterY - (R1 * Sin(t * Atan(1) * 4 / 180)))) Gdip_DeletePen(pPen)   ; Draw MinutesPointer t := A_Min*360//60+90 R1 := ClockDiameter//2-ceil((ClockDiameter//2)*0.25) ; outer position pPen := Gdip_CreatePen(0xa0008000, floor((ClockDiameter/100)*2.7)) Gdip_DrawLine(G, pPen, CenterX, CenterY , ceil(CenterX - (R1 * Cos(t * Atan(1) * 4 / 180))) , ceil(CenterY - (R1 * Sin(t * Atan(1) * 4 / 180)))) Gdip_DeletePen(pPen)   ; Draw SecondsPointer t := A_Sec*360//60+90 R1 := ClockDiameter//2-ceil((ClockDiameter//2)*0.2) ; outer position pPen := Gdip_CreatePen(0xa000FF00, floor((ClockDiameter/100)*1.2)) Gdip_DrawLine(G, pPen, CenterX, CenterY , ceil(CenterX - (R1 * Cos(t * Atan(1) * 4 / 180))) , ceil(CenterY - (R1 * Sin(t * Atan(1) * 4 / 180)))) Gdip_DeletePen(pPen)   UpdateLayeredWindow(hwnd1, hdc) ;, xPos, yPos, ClockDiameter, ClockDiameter) return   DrawClockMarks: Loop, % Items Gdip_DrawLine(G, pPen , CenterX - ceil(R1 * Cos(((a_index-1)*360//Items) * Atan(1) * 4 / 180)) , CenterY - ceil(R1 * Sin(((a_index-1)*360//Items) * Atan(1) * 4 / 180)) , CenterX - ceil(R2 * Cos(((a_index-1)*360//Items) * Atan(1) * 4 / 180)) , CenterY - ceil(R2 * Sin(((a_index-1)*360//Items) * Atan(1) * 4 / 180)) ) return   WM_LBUTTONDOWN() { PostMessage, 0xA1, 2 return }   esc:: Exit: SelectObject(hdc, obm) DeleteObject(hbm) DeleteDC(hdc) Gdip_DeleteGraphics(G) Gdip_Shutdown(pToken) ExitApp Return
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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 = True isLeaf _ = False   lastNode Leaf = Leaf lastNode dl = until (isLeaf.next) next dl   traverse _ Leaf = [] traverse True (Node l v Leaf) = v : v : traverse False l traverse dir (Node l v r) = v : traverse dir (if dir then r else l)
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 Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 updateRight new@(Node _ _ nr) (Node l v _) = current where current = Node l v next next = updateRight nr new  
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 Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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 - ] [ ] bi [ 2over <= ] [ pick over nth { { 0 [ reach reach pick exchange [ [ 1 + ] bi@ ] 2dip ] } { 1 [ [ 1 + ] 2dip ] } [ drop 3dup exchange [ 1 - ] dip ] } case ] while 3nip ;   10 3 random-non-sorted-integers dup . dnf-sort! .
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 flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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 SIZE 3 / CONSTANT #256 \ 256 chars per segment of flag 1 CONSTANT REDSQR \ red character 9 CONSTANT WHTSQR \ white character 19 CONSTANT BLUSQR \ blue character   \ color constants 1 CONSTANT TRANS 7 CONSTANT RED 5 CONSTANT BLU 16 CONSTANT WHT   SQUARE REDSQR CHARDEF SQUARE BLUSQR CHARDEF SQUARE WHTSQR CHARDEF   \ charset FG BG 0 RED TRANS COLOR 1 WHT TRANS COLOR 2 BLU TRANS COLOR   \ screen fillers : RNDI ( -- n ) SIZE 1+ RND ; \ return a random VDP screen address   : NOTRED ( -- n ) \ return rnd index that is not RED BEGIN RNDI DUP VC@ REDSQR = WHILE DROP REPEAT ;   : NOTREDWHT ( -- n ) \ return rnd index that is not RED or WHITE BEGIN RNDI DUP VC@ DUP REDSQR = SWAP WHTSQR = OR WHILE DROP REPEAT ;   : RNDRED ( -- ) \ Random RED on VDP screen #256 0 DO REDSQR NOTRED VC! LOOP ;   : RNDWHT ( -- ) \ place white where there is no red or white #256 0 DO WHTSQR NOTREDWHT VC! LOOP ;   : BLUSCREEN ( -- ) 0 768 BLUSQR VFILL ;   \ load the screen with random red,white&blue squares : RNDSCREEN ( -- ) BLUSCREEN RNDRED RNDWHT ;   : CHECKERED ( -- ) \ red,wht,blue checker board SIZE 0 DO BLUSQR I VC! WHTSQR I 1+ VC! REDSQR I 2+ VC! 3 +LOOP ;   : RUSSIAN \ Russian flag 0 0 WHTSQR 256 HCHAR 0 8 BLUSQR 256 HCHAR 0 16 REDSQR 256 HCHAR ;   : FRENCH \ kind of a French flag 0 0 BLUSQR 256 VCHAR 10 16 WHTSQR 256 VCHAR 21 8 REDSQR 256 VCHAR ;   \ ======================================================= \ Algorithm Dijkstra(A) \ A is an array of three colors \ begin \ r <- 1; \ b <- n; \ w <- n; \ while (w>=r) \ check the color of A[w] \ case 1: red \ swap(A[r],A [w]); \ r<-r+1; \ case 2: white \ w<-w-1 \ case 3: blue \ swap(A[w],A[b]); \ w<-w-1; \ b<-b-1; \ end   \ ====================================================== \ Dijkstra three color Algorithm in Forth   \ screen address pointers VARIABLE R VARIABLE B VARIABLE W   : XCHG ( vadr1 vadr2 -- ) \ Exchange chars in Video RAM OVER VC@ OVER VC@ ( -- addr1 addr2 char1 char2) SWAP ROT VC! SWAP VC! ; \ exchange chars in Video RAM   : DIJKSTRA ( -- ) 0 R ! SIZE 1- DUP B ! W ! BEGIN W @ R @ 1- > WHILE W @ VC@ ( fetch Video char at pointer W) CASE REDSQR OF R @ W @ XCHG 1 R +! ENDOF   WHTSQR OF -1 W +! ENDOF   BLUSQR OF W @ B @ XCHG -1 W +! -1 B +! ENDOF ENDCASE REPEAT ;   : WAIT ( -- ) 11 11 AT-XY ." Finished!" 1500 MS ;   : RUN ( -- ) PAGE CR ." Dijkstra Dutch flag Demo" CR CR ." Sorted in-place in Video RAM" CR CR CR ." Using the 3 colour algorithm" CR CR ." Press any key to begin" KEY DROP RNDSCREEN DIJKSTRA WAIT CHECKERED DIJKSTRA WAIT RUSSIAN DIJKSTRA WAIT FRENCH DIJKSTRA WAIT 0 23 AT-XY CR ." Completed" ;  
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. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#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 .. $]); }   cline(dy+1, dx, 0, "+-"); foreach (i; 1 .. dy+1) cline(dy-i+1, dx, i-1, "/ |"); cline(0, dx, dy, "+-|"); foreach (_; 0 .. 4*dz - dy - 2) cline(0, dx, dy, "| |"); cline(0, dx, dy, "| +"); foreach_reverse (i; 0 .. dy) cline(0, dx, i, "| /"); cline(0, dx, 0, "+-\n"); }   void main() { printCuboid(2, 3, 4); printCuboid(1, 1, 1); printCuboid(6, 2, 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.
#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) /*stick a fork in it, we're all done. */
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 a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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 }) .reversed()   let (answer, acc) = table.reduce((Self(0), Self(0)), {cur, row in let ((ans, acc), (power, doubling)) = (cur, row)   return acc + doubling <= self ? (ans + power, doubling + acc) : cur })   return (answer, Self((acc - self).magnitude)) }   @inlinable public func power(_ n: Self) -> Self { return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) } }   let dividend = 580 let divisor = 34 let (quo, rem) = dividend.egyptianDivide(by: divisor)   print("\(dividend) divided by \(divisor) = \(quo) rem \(rem)")  
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 a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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:-1)... -> # $@ !   when <{doubling: <[email protected]>}> do @: { answer: [email protected] + $.powerOf2, accumulator: [email protected] + $.doubling }; end egyptianDivision   [580"1", 34"1"] -> egyptianDivision -> 'Quotient: $.answer; Remainder: $: 580"1" - $.accumulator;' -> !OUT::write  
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 is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#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 ArrayBuffer[Frac] if (num.abs >= denom.abs) { val div = Frac(num / denom, 1) val rem = this - div fracs += div egyptian(rem.num, rem.denom, fracs) } else { egyptian(num, denom, fracs) } fracs.toList }   @tailrec private def egyptian(n: BigInt, d: BigInt, fracs: mutable.Buffer[Frac]): Unit = { if (n == 0) { return } val n2 = BigDecimal.apply(n) val d2 = BigDecimal.apply(d) val (divbd, rembd) = d2./%(n2) var div = divbd.toBigInt() if (rembd > 0) { div = div + 1 } fracs += Frac(1, div) var n3 = -d % n if (n3 < 0) { n3 = n3 + n } val d3 = d * div val f = Frac(n3, d3) if (f.num == 1) { fracs += f return } egyptian(f.num, f.denom, fracs) }   def unary_-(): Frac = { Frac(-num, denom) }   def +(rhs: Frac): Frac = { Frac( num * rhs.denom + rhs.num * denom, denom * rhs.denom ) }   def -(rhs: Frac): Frac = { Frac( num * rhs.denom - rhs.num * denom, denom * rhs.denom ) }   override def compareTo(rhs: Frac): Int = { val ln = num * rhs.denom val rn = rhs.num * denom ln.compare(rn) }   def canEqual(other: Any): Boolean = other.isInstanceOf[Frac]   override def equals(other: Any): Boolean = other match { case that: Frac => (that canEqual this) && num == that.num && denom == that.denom case _ => false }   override def hashCode(): Int = { val state = Seq(num, denom) state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b) }   override def toString: String = { if (denom == 1) { return s"$num" } s"$num/$denom" } }   object Frac { def apply(n: BigInt, d: BigInt): Frac = { if (d == 0) { throw new IllegalArgumentException("Parameter d may not be zero.") }   var nn = n var dd = d   if (nn == 0) { dd = 1 } else if (dd < 0) { nn = -nn dd = -dd }   val g = nn.gcd(dd) if (g > 0) { nn /= g dd /= g }   new Frac { val num: BigInt = nn val denom: BigInt = dd } } }   object EgyptianFractions { def main(args: Array[String]): Unit = { val fracs = List.apply( Frac(43, 48), Frac(5, 121), Frac(2014, 59) ) for (frac <- fracs) { val list = frac.toEgyptian val it = list.iterator   print(s"$frac -> ") if (it.hasNext) { val value = it.next() if (value.denom == 1) { print(s"[$value]") } else { print(value) } } while (it.hasNext) { val value = it.next() print(s" + $value") } println() }   for (r <- List(98, 998)) { println() if (r == 98) { println("For proper fractions with 1 or 2 digits:") } else { println("For proper fractions with 1, 2 or 3 digits:") }   var maxSize = 0 var maxSizeFracs = new ListBuffer[Frac] var maxDen = BigInt(0) var maxDenFracs = new ListBuffer[Frac] val sieve = Array.ofDim[Boolean](r + 1, r + 2) for (i <- 0 until r + 1) { for (j <- i + 1 until r + 1) { if (!sieve(i)(j)) { val f = Frac(i, j) val list = f.toEgyptian val listSize = list.size if (listSize > maxSize) { maxSize = listSize maxSizeFracs.clear() maxSizeFracs += f } else if (listSize == maxSize) { maxSizeFracs += f } val listDen = list.last.denom if (listDen > maxDen) { maxDen = listDen maxDenFracs.clear() maxDenFracs += f } else if (listDen == maxDen) { maxDenFracs += f } if (i < r / 2) { var k = 2 while (j * k <= r + 1) { sieve(i * k)(j * k) = true k = k + 1 } } } } } println(s" largest number of items = $maxSize") println(s"fraction(s) with this number : ${maxSizeFracs.toList}") val md = maxDen.toString() print(s" largest denominator = ${md.length} digits, ") println(s"${md.substring(0, 20)}...${md.substring(md.length - 20)}") println(s"fraction(s) with this denominator : ${maxDenFracs.toList}") } } }
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 in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#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 }   fn main() { println("17 ethiopian 34 = ${eth_multi(17, 34)}") }
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 iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#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 localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#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) = ({numConnections += 1; numConnections}, ":exit")   override def run(): Unit = new PrintWriter(clientSocket.getOutputStream, true) { println(s"Connection opened, close with entering '$closeCmd'.") Source.fromInputStream(clientSocket.getInputStream).getLines .takeWhile(!_.toLowerCase.startsWith(closeCmd)) .foreach { line => Console.println(s"Received on #$connectionId: $line") println(line) // Echo } Console.println(s"Gracefully closing connection, #$connectionId") clientSocket.close() }   println(s"Handling connection, $connectionId") }   while (true) new Thread(new ClientHandler(serverSocket.accept())).start() }
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 billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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 to and including ", ended else Print "eban numbers between ", start, " and ", ended, " (inclusive):" endif count = 0 for i = start to ended step 2 b = int(i / 1000000000) r = mod(i, 1000000000) m = int(r / 1000000) r = mod(i, 1000000) t = int(r / 1000) r = mod(r, 1000) if m >= 30 and m <= 66 m = mod(m, 10) if t >= 30 and t <= 66 t = mod(t, 10) if r >= 30 and r <= 66 r = mod(r, 10) if b = 0 or b = 2 or b = 4 or b = 6 then if m = 0 or m = 2 or m = 4 or m = 6 then if t = 0 or t = 2 or t = 4 or t = 6 then if r = 0 or r = 2 or r = 4 or r = 6 then if printable Print i; count = count + 1 endif endif endif endif next if printable Print Print "count = ", count, "\n" loop
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 billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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 including %,d:".fmt(end)); else println("eban numbers between %,d and %,d (inclusive):".fmt(start,end));   count:=0; foreach i in ([start..end,2]){ b,r := i/100_0000_000, i%1_000_000_000; m,r := r/1_000_000, i%1_000_000; t,r := r/1_000, r%1_000; if(30<=m<=66) m=m%10; if(30<=t<=66) t=t%10; if(30<=r<=66) r=r%10;   if(magic(b) and magic(m) and magic(t) and magic(r)){ if(pr) print(i," "); count+=1; } } if(pr) println(); println("count = %,d\n".fmt(count)); } fcn magic(z){ z.isEven and z<=6 }
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 tasks Draw a cuboid write language name in 3D ASCII
#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), (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)]   const Edges = [(a: 0, b: 1), (a: 1, b: 3), (a: 3, b: 2), (a: 2, b: 0), (a: 4, b: 5), (a: 5, b: 7), (a: 7, b: 6), (a: 6, b: 4), (a: 0, b: 4), (a: 1, b: 5), (a: 2, b: 6), (a: 3, b: 7)]   var window: WindowPtr renderer: RendererPtr event: Event endSimulation = false   #---------------------------------------------------------------------------------------------------   proc rotateCube(angleX, angleY: float) = let sinX = sin(angleX) cosX = cos(angleX) sinY = sin(angleY) cosY = cos(angleY)   for node in nodes.mitems: var (x, y, z) = node node.x = x * cosX - z * sinX node.z = z * cosX + x * sinX z = node.z node.y = y * cosY - z * sinY node.z = z * cosY + y * sinY   #---------------------------------------------------------------------------------------------------   proc pollQuit(): bool = while pollEvent(event): if event.kind == QuitEvent: return true   #---------------------------------------------------------------------------------------------------   proc drawCube(): bool = var rect: Rect = (cint(0), cint(0), cint(Width), cint(Height)) rotateCube(PI / 4, arctan(sqrt(2.0))) for frame in 0..359: renderer.setDrawColor((0u8, 0u8, 0u8, 255u8)) renderer.fillRect(addr(rect)) renderer.setDrawColor((0u8, 220u8, 0u8, 255u8)) for edge in Edges: let xy1 = nodes[edge.a] let xy2 = nodes[edge.b] renderer.drawLine(cint(xy1.x + Offset), cint(xy1.y + Offset), cint(xy2.x + Offset), cint(xy2.y + Offset)) rotateCube(PI / 180, 0) renderer.present() if pollQuit(): return true delay 10   #———————————————————————————————————————————————————————————————————————————————————————————————————   if sdl2.init(INIT_EVERYTHING) == SdlError: quit(QuitFailure)   window = createWindow("Rotating cube", 10, 10, 500, 500, 0) renderer = createRenderer(window, -1, Renderer_Accelerated)   while not endSimulation: endSimulation = drawCube() window.destroy()
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 tasks Draw a cuboid write language name in 3D ASCII
#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, GameConsts->SCREEN_HEIGHT, "Rotating Cube");   @nodes := [[-100.0, -100.0, -100.0], [-100.0, -100.0, 100.0], [-100.0, 100.0, -100.0], [-100.0, 100.0, 100.0], [100.0, -100.0, -100.0], [100.0, -100.0, 100.0], [100.0, 100.0, -100.0], [100.0, 100.0, 100.0]];   @edges := [[0, 1], [1, 3], [3, 2], [2, 0], [4, 5], [5, 7], [7, 6], [6, 4], [0, 4], [1, 5], [2, 6], [3, 7]];   }   function : Main(args : String[]) ~ Nil { RotatingCube->New()->Play(); }   method : Play() ~ Nil { if(@initialized) { # initialization @framework->SetClearColor(Color->New(0, 0, 0)); RotateCube(Float->Pi(), 2.0->SquareRoot()->ArcTan());   quit := false; e := @framework->GetEvent(); while(<>quit) { @framework->FrameStart(); @framework->Clear();   # process input while(e->Poll() <> 0) { if(e->GetType() = EventType->SDL_QUIT) { quit := true; }; };   #draw DrawCube();   @framework->FrameEnd();   # render @framework->Show();   Timer->Delay(200);   RotateCube (Float->Pi() / 180.0, 0.0); }; } else { "--- Error Initializing Environment ---"->ErrorLine(); return; };   leaving { @framework->FreeShapes(); }; }   method : RotateCube(angleX : Float, angleY : Float) ~ Nil { sinX := angleX->Sin(); cosX := angleX->Cos();   sinY := angleY->Sin(); cosY := angleY->Cos();   node_sizes := @nodes->Size(); size := node_sizes[0];   for(i := 0; i < size; i += 1;) { x := @nodes[i, 0]; y := @nodes[i, 1]; z := @nodes[i, 2];   @nodes[i, 0] := x * cosX - z * sinX; @nodes[i, 2] := z * cosX + x * sinX;   z := @nodes[i, 2];   @nodes[i, 1] := y * cosY - z * sinY; @nodes[i, 2] := z * cosY + y * sinY; }; }   method : DrawCube() ~ Nil { edge_sizes := @edges->Size(); size := edge_sizes[0];   @framework->GetRenderer()->SetDrawColor(0, 220, 0, 0); for(i := 0; i < size; i += 1;) { x0y0 := @nodes[@edges[i, 0], 0]; x0y1 := @nodes[@edges[i, 0], 1];   x1y0 := @nodes[@edges[i, 1], 0]; x1y1 := @nodes[@edges[i, 1], 1];   @framework->GetRenderer()->DrawLine(x0y0 + GameConsts->DRAW_OFFSET, x0y1 + GameConsts->DRAW_OFFSET, x1y0 + GameConsts->DRAW_OFFSET, x1y1 + GameConsts->DRAW_OFFSET); }; } }   consts GameConsts { SCREEN_WIDTH := 600, SCREEN_HEIGHT := 600, DRAW_OFFSET := 300 }
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 necessary to include additional basic operations, which should not require their own specialised task.
#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 answer, 'M matrix, added 2' answer= matSub(m, 7 ); call showMat answer, 'M matrix, subtracted 7' answer= matMul(m, 2.5); call showMat answer, 'M matrix, multiplied by 2½' answer= matPow(m, 3 ); call showMat answer, 'M matrix, cubed' answer= matDiv(m, 4 ); call showMat answer, 'M matrix, divided by 4' answer= matIdv(m, 2 ); call showMat answer, 'M matrix, integer halved' answer= matMod(m, 3 ); call showMat answer, 'M matrix, modulus 3' exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ matAdd: parse arg @,#; call mat#; do j=1 for w;  !.j= !.j+#; end; return mat@() matSub: parse arg @,#; call mat#; do j=1 for w;  !.j= !.j-#; end; return mat@() matMul: parse arg @,#; call mat#; do j=1 for w;  !.j= !.j*#; end; return mat@() matDiv: parse arg @,#; call mat#; do j=1 for w;  !.j= !.j/#; end; return mat@() matIdv: parse arg @,#; call mat#; do j=1 for w;  !.j= !.j%#; end; return mat@() matPow: parse arg @,#; call mat#; do j=1 for w;  !.j= !.j**#; end; return mat@() matMod: parse arg @,#; call mat#; do j=1 for w;  !.j= !.j//#; end; return mat@() mat#: w= words(@); do j=1 for w;  !.j= word(@,j); end; return mat@: @= !.1; do j=2 to w; @=@ !.j; end; return @ /*──────────────────────────────────────────────────────────────────────────────────────*/ showMat: parse arg @, hdr; L= 0; say do j=1 for w; L= max(L, length( word(@,j) ) ); end say center(hdr, max( length(hdr)+4, cols * (L+1)+4), "─") n= 0 do r=1 for rows; _= do c=1 for cols; n= n+1; _= _ right( word(@, n), L); end; say _ end return
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 angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#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 +:= left turn;   PROC turtle right = (REAL right turn)VOID: heading OF turtle -:= right turn;   PROC turtle forward = (REAL distance)VOID:( x OF turtle +:= distance * cos(heading OF turtle) / width * height; y OF turtle +:= distance * sin(heading OF turtle); IF pen down OF turtle THEN draw line ELSE draw move FI (window, x OF turtle, y OF turtle) );   SKIP
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] /= len; v[1] /= len; v[2] /= len; }   private static double Dot(double[] x, double[] y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; }   public static void DrawSphere(double r, double k, double ambient) { var vec = new double[3]; for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) { double x = i + .5; for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) { double y = j/2.0 + .5; if(x*x + y*y <= r*r) { vec[0] = x; vec[1] = y; vec[2] = Math.Sqrt(r*r - x*x - y*y); Normalize(vec); double b = Math.Pow(Dot(Light, vec), k) + ambient; int intensity = (b <= 0) ? Shades.Length - 2 : (int)Math.Max((1 - b)*(Shades.Length - 1), 0); Console.Write(Shades[intensity]); } else Console.Write(' '); } Console.WriteLine(); } }   private static void Main() { Normalize(Light); DrawSphere(6, 4, .1); DrawSphere(10, 2, .4); Console.ReadKey(); } } }
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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#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,2,1) t[3] = 10 t[4] = substr(now,4,1) t[5] = substr(now,5,1) t[6] = 10 t[7] = substr(now,7,1) t[8] = substr(now,8,1) if (prev_now != now) { system(clearscreen_cmd) for (v=1; v<=8; v++) { printf("\t") for (h=1; h<=8; h++) { printf("%-8s",a[t[h],v]) } printf("\n") } prev_now = now } system(sleep_cmd) } exit(0) } function clock_build_digits( arr,i,j,x,y) { arr[1] = " 0000 1 2222 3333 4 555555 6666 777777 8888 9999 " arr[2] = "0 0 11 2 2 3 3 44 5 6 7 78 8 9 9 " arr[3] = "0 00 1 1 2 3 4 4 5 6 7 8 8 9 9  :: " arr[4] = "0 0 0 1 2 333 4 4 555555 66666 7 8888 9 9  :: " arr[5] = "0 0 0 1 22 3 444444 5 6 6 7 8 8 99999 " arr[6] = "00 0 1 2 3 4 5 6 6 7 8 8 9  :: " arr[7] = "0 0 1 2 3 3 4 5 5 6 6 7 8 8 9  :: " arr[8] = " 0000 1111111222222 3333 4 5555 6666 7 8888 9999 " for (i=1; i<=8; i++) { if (xc != "") { gsub(/[0-9:]/,substr(xc,1,1),arr[i]) # change "0-9" and ":" to substitution character } y++ x = -1 for (j=1; j<=77; j=j+7) { a[++x,y] = substr(arr[i],j,7) } } }  
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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 traverse # - keep suspending the prev/next link until a null node is reached method traverse_backwards () current := self while \current do { suspend current current := current.prev_link } end   method traverse_forwards () current := self while \current do { suspend current current := current.next_link } end   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   procedure main () l1 := DoubleLink (1) l2 := DoubleLink (2) l1.insert_after (l2) l1.insert_after (DoubleLink (3))   write ("Traverse from beginning to end") every (node := l1.traverse_forwards ()) do write (node.value)   write ("Traverse from end to beginning") every (node := l2.traverse_backwards ()) do write (node.value) end
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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 Node<T> getNext(){ return next; }   public void setElem(T elem){ element = elem; }   public T getElem(){ return element; }   public void setNext(Node<T> n){ next = n; }   public Node<T> setPrev(Node<T> p){ prev = p; }   public getPrev(){ return prev; } }
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 flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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 blue blue RED WHITE WHITE WHITE blue RED RED blue ! RED RED RED RED WHITE WHITE WHITE WHITE blue blue blue blue ! 12 items, 8 swaps. ! 999 items, 666 swaps. ! 9999 items, 6666 swaps. ! !Compilation finished at Mon Jun 3 11:18:24   program Netherlands   character(len=6), parameter, dimension(3) :: colors = (/'RED ', 'WHITE ', 'blue '/) integer, dimension(12) :: sort_me integer, dimension(999), target :: a999 integer, dimension(9999), target :: a9999 integer, dimension(:), pointer  :: pi integer :: i, swaps data sort_me/4*1,4*2,4*3/ call shuffle(sort_me, 5) write(6,*)'Original and flag sequences' write(6,*) (colors(sort_me(i)), i = 1, size(sort_me)) call partition3way(sort_me, 2, swaps) write(6,*) (colors(sort_me(i)), i = 1, size(sort_me)) write(6,*) 12,'items,',swaps,' swaps.' pi => a999 do i=1, size(pi) pi(i) = 1 + L(size(pi)/3 .lt. i) + L(2*size(pi)/3 .lt. i) end do call shuffle(pi, size(pi)/3+1) call partition3way(pi, 2, swaps) write(6,*) size(pi),'items,',swaps,' swaps.' pi => a9999 do i=1, size(pi) pi(i) = 1 + L(size(pi)/3 .lt. i) + L(2*size(pi)/3 .lt. i) end do call shuffle(pi, size(pi)/3+1) call partition3way(pi, 2, swaps) write(6,*) size(pi),'items,',swaps,' swaps.'   contains   integer function L(q)  ! In Ken Iverson's spirit, APL logicals are more useful as integers. logical, intent(in) :: q if (q) then L = 1 else L = 0 end if end function L   subroutine swap(a,i,j) integer, dimension(:), intent(inout) :: a integer, intent(in) :: i, j integer :: t t = a(i) a(i) = a(j) a(j) = t end subroutine swap   subroutine partition3way(a, pivot, swaps) integer, dimension(:), intent(inout) :: a integer, intent(in) :: pivot integer, intent(out) :: swaps integer :: i, j, k swaps = 0 i = 0 j = 1 k = size(a) + 1 do while (j .lt. k) if (pivot .eq. a(j)) then j = j+1 swaps = swaps-1 else if (pivot .lt. a(j)) then k = k-1 call swap(a, k, j) else i = i+1 call swap(a, i, j) j = j+1 end if swaps = swaps+1 end do end subroutine partition3way   subroutine shuffle(a, n) ! a rather specialized shuffle not for general use integer, intent(inout), dimension(:) :: a integer, intent(in) :: n integer :: i, j, k real :: harvest do i=1, size(a)-1 call random_number(harvest) harvest = harvest - epsilon(harvest)*L(harvest.eq.1) k = L(i.eq.1)*(n-1) + i j = i + int((size(a) - k) * harvest) call swap(a, i, j) end do end subroutine shuffle   end program Netherlands  
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 flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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   Color 15: Print "Aleatorio: "; For k = 1 To bolanum d(k) = Int(Rnd * 3) + 1 Color Val(Mid(n, d(k), 2)) Print Mid(c, d(k), 1) & Chr(219); Next k   Color 15: Print : Print "Ordenado: "; For i = 1 To 3 For j = 1 To bolanum If d(j) = i Then Color Val(Mid(n, i, 2)): Print Mid(c, i, 1) & Chr(219); Next j Next i End  
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. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#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)); Writeln(cde.Substring(2, cde.Length).PadLeft(dy + 1)); end;   procedure cuboid(dx, dy, dz: integer); var i: integer; begin Writeln(Format('cuboid %d %d %d:', [dx, dy, dz]));   cubLine(dy + 1, dx, 0, '+-');   for i := 1 to dy do cubLine(dy - i + 1, dx, i - 1, '/ |');   cubLine(0, dx, dy, '+-|');   for i := 4 * dz - dy - 2 downto 1 do cubLine(0, dx, dy, '| |');   cubLine(0, dx, dy, '| +');   for i := 1 to dy do cubLine(0, dx, dy - i, '| /');   cubLine(0, dx, 0, '+-'); Writeln; end;   begin cuboid(2, 3, 4); cuboid(1, 1, 1); cuboid(6, 2, 1);   readln; end.
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 a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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   Private Deg As DivEgyp   Sub Main() Dim d As Division Deg.Dividend = 580 Deg.Divisor = 34 d = Divise(CreateTable) Debug.Print "Quotient = " & d.Quotient & " Remainder = " & d.Remainder End Sub   Private Function CreateTable() As MyTable() Dim t() As MyTable, i As Long Do i = i + 1 ReDim Preserve t(i) t(i).powers_of_2 = 2 ^ (i - 1) t(i).doublings = Deg.Divisor * t(i).powers_of_2 Loop While 2 * t(i).doublings <= Deg.Dividend CreateTable = t End Function   Private Function Divise(t() As MyTable) As Division Dim a As Assemble, i As Long a.accumulator = 0 a.answer = 0 For i = UBound(t) To LBound(t) Step -1 If a.accumulator + t(i).doublings <= Deg.Dividend Then a.accumulator = a.accumulator + t(i).doublings a.answer = a.answer + t(i).powers_of_2 End If Next Divise.Quotient = a.answer Divise.Remainder = Deg.Dividend - a.accumulator End Function
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 a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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) = divisor << i If doublings(i) > dividend Then Exit While End If i = i + 1 End While   Dim answer As ULong = 0 Dim accumulator As ULong = 0 i = i - 1 While i >= 0 If accumulator + doublings(i) <= dividend Then accumulator += doublings(i) answer += powers(i) End If i = i - 1 End While   remainder = dividend - accumulator Return answer End Function   Sub Main(args As String()) If args.Length < 2 Then Dim name = Reflection.Assembly.GetEntryAssembly().Location Console.Error.WriteLine("Usage: {0} dividend divisor", IO.Path.GetFileNameWithoutExtension(name)) Return End If   Dim dividend = CULng(args(0)) Dim divisor = CULng(args(1)) Dim remainder As ULong   Dim ans = EgyptianDivision(dividend, divisor, remainder) Console.WriteLine("{0} / {1} = {2} rem {3}", dividend, divisor, ans, remainder) End Sub   End Module
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 is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#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, 2014/59] { "%s => %s\n".printf(fr.as_rat, ef(fr).map{.as_rat}.join(' + ')) }   var lenmax = (var denommax = [0]) for b in range(2, 99) { for a in range(1, b-1) { var fr = a/b var e = ef(fr) var (elen, edenom) = (e.length, e[-1].denominator) lenmax = [elen, fr] if (elen > lenmax[0]) denommax = [edenom, fr] if (edenom > denommax[0]) } }   "Term max is %s with %i terms\n".printf(lenmax[1].as_rat, lenmax[0]) "Denominator max is %s with %i digits\n".printf(denommax[1].as_rat, denommax[0].size) say denommax[0]
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 in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#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.print("17 x 34 = %(ethiopian.call(17, 34))") System.print("99 x 99 = %(ethiopian.call(99, 99))")
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 iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#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 localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#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 12321) (listen s 5) ; Queue size of 5   (simple-format #t "Listening for clients in pid: ~S" (getpid)) (newline)   ; Wait for connections forever (while #t (let* ((client-connection (accept s)) (client-details (cdr client-connection)) (client (car client-connection))) ; Once something connects fork (set! child (primitive-fork)) (if (zero? child) (begin ; Then have child fork to avoid zombie children (grandchildren aren't our responsibility) (set! child (primitive-fork)) (if (zero? child) (begin ; Display some connection details (simple-format #t "Got new client connection: ~S" client-details) (newline) (simple-format #t "Client address: ~S" (gethostbyaddr (sockaddr:addr client-details))) (newline) ; Wait for input from client and then echo the input back forever (or until client quits) (do ((line (read-line client)(read-line client))) ((zero? 1)) (display line client)(newline client)))) ; Child exits after spawning grandchild. (primitive-exit)) ; Parent waits for child to finish spawning grandchild (waitpid child)))))
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 tasks Draw a cuboid write language name in 3D ASCII
#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 tasks Draw a cuboid write language name in 3D ASCII
#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 corners every 60 degrees   my $mw = MainWindow->new; my $c = $mw->Canvas(-width => $width, -height => $height)->pack; $c->Tk::bind('<ButtonRelease>' => sub {$mw->destroy}); # click to exit draw(); MainLoop;   sub draw { my $angle = time - $^T; # full rotation every 2*PI seconds my @points = map { $mid + $mid * cos $angle + $_ * $rot, $height * ($_ % 2 + 1) / 3 } 0 .. 5; $c->delete('all'); $c->createLine( @points[-12 .. 1], $mid, 0, -width => 5,); $c->createLine( @points[4, 5], $mid, 0, @points[8, 9], -width => 5,); $c->createLine( @points[2, 3], $mid, $height, @points[6, 7], -width => 5,); $c->createLine( $mid, $height, @points[10, 11], -width => 5,); $mw->after($wait, \&draw); }
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 necessary to include additional basic operations, which should not require their own specialised task.
#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, :**, :%].each do |op| puts "m1 %-4s m2 =  %s" % [op, m1.element_wise(op, m2)] 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 angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#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 ELSE turn d*45 dragon length/1.4142136, split-1, 1 turn -d*90 dragon length/1.4142136, split-1, -1 turn d*45 END IF END SUB   ' Main program   SCREEN 12 angle = 0 PSET (150,180), 0 dragon 400, 12, 1 SLEEP
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); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing);   QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black);   QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush);   QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black);   QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));   image.save("sphere.png"); return 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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 -> unit *) let insert dl v = match dl with | (Some anchor) -> _insert anchor {data=v; prev=None; next=None} | None -> invalid_arg "dlink empty";;
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 cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#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)) s=VAL(MID$(t$,7,2)) LOCATE 1,1:PRINT t$ LINE (xp,yp)-(xp+2*hs*SIN(lasth),yp-hs*COS(lasth)),0 LINE (xp,yp)-(xp+2*ms*SIN(lastm),yp-ms*COS(lastm)),0 LINE (xp,yp)-(xp+2*ss*SIN(lasts),yp-ss*COS(lasts)),0 lasth=2*pi*(h/12+m/720) lastm=2*pi*m/60 lasts=2*pi*s/60 LINE (xp,yp)-(xp+2*hs*SIN(lasth),yp-hs*COS(lasth)),1 LINE (xp,yp)-(xp+2*ms*SIN(lastm),yp-ms*COS(lastm)),1 LINE (xp,yp)-(xp+2*ss*SIN(lasts),yp-ss*COS(lasts)),2 RETURN
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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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(String::valueOf) .collect(Collectors.toCollection(LinkedList::new));   doubleLinkedList.iterator().forEachRemaining(System.out::print); System.out.println(); doubleLinkedList.descendingIterator().forEachRemaining(System.out::print); } }
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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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.printBackward = function() { this.traverseBackward( function(node) {print(node.value())} ); }   var head = createDoublyLinkedListFromArray([10,20,30,40]); head.print(); head.getTail().printBackward();
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 Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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) this._prev = arguments[0]; else return this._prev; }   function createDoublyLinkedListFromArray(ary) { var node, prev, head = new DoublyLinkedList(ary[0], null, null); prev = head; for (var i = 1; i < ary.length; i++) { node = new DoublyLinkedList(ary[i], null, prev); prev.next(node); prev = node; } return head; }   var head = createDoublyLinkedListFromArray([10,20,30,40]);
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 Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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 Then Print "Red "; If sTemp = White Then Print "White "; If sTemp = Blue Then Print "Blue "; Next sColours.Sort Print If siCount = 1 Then Print "Sorted: - "; Next   End
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. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#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(0..ny, area, fn i,acc -> draw_line(acc, x, @y*i, z+@y*i, :-) end) area = Enum.reduce(0..nx-1, area, fn i,acc -> draw_line(acc, z, @x*i, 0, :|) end) area = Enum.reduce(0..ny, area, fn i,acc -> draw_line(acc, z, x+@y*i, @y*i, :|) end) area = Enum.reduce(0..nz-1, area, fn i,acc -> draw_line(acc, y, x, @z*i, :/) end) area = Enum.reduce(0..nx, area, fn i,acc -> draw_line(acc, y, @x*i, z, :/) end) Enum.each(y+z..0, fn j -> IO.puts Enum.map_join(0..x+y, fn i -> Map.get(area, {i,j}, " ") end) end) end   defp draw_line(area, n, sx, sy, c) do {dx, dy} = Map.get(@dir, c) draw_line(area, n, sx, sy, c, dx, dy) end   defp draw_line(area, n, _, _, _, _, _) when n<0, do: area defp draw_line(area, n, i, j, c, dx, dy) do Map.update(area, {i,j}, c, fn _ -> :+ end) |> draw_line(n-1, i+dx, j+dy, c, dx, dy) end end   Cuboid.draw(2,3,4) Cuboid.draw(1,1,1) Cuboid.draw(2,4,1) Cuboid.draw(4,2,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.
#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); .rectangle(100, 100, 1, 1); .fill; } }   my $ctx = $da.add-draw-handler( &rect-do ); $app.run;
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 a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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 *= 2 if doubling > dividend { break } l := powers_of_two.len powers_of_two << powers_of_two[l-1]*2 doublings << doubling } mut answer := 0 mut accumulator := 0 for i := doublings.len - 1; i >= 0; i-- { if accumulator+doublings[i] <= dividend { accumulator += doublings[i] answer += powers_of_two[i] if accumulator == dividend { break } } } return answer, dividend - accumulator }   fn main() { dividend := 580 divisor := 34 quotient, remainder := egyptian_divide(dividend, divisor)? println("$dividend divided by $divisor is $quotient with remainder $remainder") }
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 a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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 (doubling > dividend) break powersOfTwo.add(powersOfTwo[-1]*2) doublings.add(doubling) } var answer = 0 var accumulator = 0 for (i in doublings.count-1..0) { if (accumulator + doublings[i] <= dividend) { accumulator = accumulator + doublings[i] answer = answer + powersOfTwo[i] if (accumulator == dividend) break } } return [answer, dividend - accumulator] }   var dividend = 580 var divisor = 34 var res = egyptianDivide.call(dividend, divisor) System.print("%(dividend) ÷ %(divisor) = %(res[0]) with remainder %(res[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 is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#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 denom [expr {$denom * $term}] } return $result }
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 in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#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 printf add esp, 8   ret     %define plier 8 %define plicand 12 %define tutor 16   ethiopicmult enter 0, 0 cmp dword [ebp + tutor], 0 je .notut0 push dword [ebp + plicand] push dword [ebp + plier] push preamblefmt call printf add esp, 12 .notut0   xor eax, eax ; eax -> result mov ecx, [ebp + plier] ; ecx -> plier mov edx, [ebp + plicand] ; edx -> plicand   .whileloop cmp ecx, 1 jl .multend cmp dword [ebp + tutor], 0 je .notut1 call tutorme .notut1 mov ebx, ecx call iseven je .iseven add eax, edx ; result += plicand .iseven mov ebx, ecx ; plier >>= 1 call halve mov ecx, ebx   mov ebx, edx ; plicand <<= 1 call double mov edx, ebx   jmp .whileloop .multend leave ret     tutorme push eax push strucktxt mov ebx, ecx call iseven je .nostruck mov dword [esp], kepttxt .nostruck push edx push ecx push tutorfmt call printf add esp, 4 pop ecx pop edx add esp, 4 pop eax ret   section .data   fmt db "%d", 10, 0 preamblefmt db "ethiopic multiplication of %d and %d", 10, 0 tutorfmt db "%4d %6d %s", 10, 0 strucktxt db "struck", 0 kepttxt db "kept", 0
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 iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#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 localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#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); while TRUE do waitForRequest(aListener, existingConnection, newConnection); if existingConnection <> STD_NULL then if eof(existingConnection) then writeln("Close connection " <& numericAddress(address(existingConnection)) <& " port " <& port(existingConnection)); close(existingConnection); else write(existingConnection, gets(existingConnection, 1024)); end if; end if; if newConnection <> STD_NULL then writeln("New connection " <& numericAddress(address(newConnection)) <& " port " <& port(newConnection)); end if; end while; end func;
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 tasks Draw a cuboid write language name in 3D ASCII
#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, which is plenty). -- with javascript_semantics include pGUI.e constant title = "Draw a Rotating Cube" Ihandle dlg, canvas cdCanvas cd_canvas -- -- First, define 8 corners equidistant from {0,0,0}: -- -- 6-----2 -- 5-----1 3 -- 8-----4 -- -- ie the right face is 1-2-3-4 clockwise, and the left face -- is 5-6-7-8 counter-clockwise (unless using x-ray vision). -- (since this is not drawing textures, clockwise-ness does -- not matter, as shown by the corrected orange face, but -- it will if you (figure out how to) apply any textures.) -- (a quick (online) study of opengl texture documentation -- should convince you that stuff is best left to opengl.) -- enum X, Y, Z constant l = 100 constant corners = {{+l,+l,+l}, -- 1 (front top right) {+l,+l,-l}, -- 2 (back top "right") {+l,-l,-l}, -- 3 (back btm "right") {+l,-l,+l}, -- 4 (front btm right) {-l,+l,+l}, -- 5 (front top left) {-l,+l,-l}, -- 6 (back top "left") {-l,-l,-l}, -- 7 (back btm "left") {-l,-l,+l}} -- 8 (front btm left) -- I put left/right in quotes for the back face as a reminder -- those match the above diagram, but of course they would be -- swapped were you looking "at" the face/rotated it by 180. constant faces = {{CD_RED, 1,2,3,4}, -- right {CD_YELLOW, 1,5,6,2}, -- top {CD_DARK_GREEN, 1,4,8,5}, -- front {CD_BLUE, 2,3,7,6}, -- back {CD_WHITE, 3,4,8,7}, -- bottom -- {CD_ORANGE, 5,6,7,8}} -- left {CD_ORANGE, 8,7,6,5}} -- left -- rotation angles, 0..359, on a timer atom rx = 45, -- initially makes cube like a H ry = 35, -- " " " italic H rz = 0 constant naxes = {{Y,Z}, -- (rotate about the X-axis) {X,Z}, -- (rotate about the Y-axis) {X,Y}} -- (rotate about the Z-axis) function rotate(sequence points, atom angle, integer axis) -- -- rotate points by the specified angle about the given axis -- atom radians = angle*CD_DEG2RAD, sin_t = sin(radians), cos_t = cos(radians) integer {nx,ny} = naxes[axis] for i=1 to length(points) do atom x = points[i][nx], y = points[i][ny] points[i][nx] = x*cos_t - y*sin_t points[i][ny] = y*cos_t + x*sin_t end for return points end function function projection(sequence points, atom d) -- -- project points from {0,0,d} onto the perpendicular plane through {0,0,0} -- for i=1 to length(points) do atom {x,y,z} = points[i], denom = (1-z/d) points[i][X] = x/denom points[i][Y] = y/denom end for return points end function function nearest(sequence points) -- -- return the index of the nearest point (highest z value) -- return largest(vslice(points,Z),true) end function procedure draw_cube(integer cx, cy) -- {cx,cy} is the centre point of the canvas sequence points = deep_copy(corners) points = rotate(points,rx,X) points = rotate(points,ry,Y) points = rotate(points,rz,Z) points = projection(points,1000) integer np = nearest(points) -- -- find the three faces that contain the nearest point, -- then for each of those faces let diag be the point -- that is diagonally opposite said nearest point, and -- order by/draw those faces furthest diag away first. -- (one or two of them may be completely obscured due -- to the effects of the perspective projection.) -- (you could of course draw all six faces, as long as -- the 3 furthest are draw first/obliterated, which -- is what that commented-out "else" would achieve.) -- sequence faceset = {} for i=1 to length(faces) do sequence fi = faces[i] integer k = find(np,fi) -- k:=2..5, or 0 if k then integer diag = mod(k,4)+2 -- {2,3,4,5} --> {4,5,2,3} -- aka swap 2<=>4 & 3<=>5 diag = fi[diag] -- 1..8, diagonally opp. np faceset = append(faceset,{points[diag][Z],i}) -- else -- faceset = append(faceset,{-9999,i}) end if end for faceset = sort(faceset) for i=1 to length(faceset) do sequence face = faces[faceset[i][2]] cdCanvasSetForeground(cd_canvas,face[1]) -- first fill sides (with bresenham edges), then -- redraw edges, but anti-aliased aka smoother sequence modes = {CD_FILL,CD_CLOSED_LINES} for m=1 to length(modes) do cdCanvasBegin(cd_canvas,modes[m]) for fdx=2 to 5 do sequence pt = points[face[fdx]] cdCanvasVertex(cd_canvas,cx+pt[X],cy-pt[Y]) end for cdCanvasEnd(cd_canvas) end for end for end procedure function canvas_action_cb(Ihandle canvas) cdCanvasActivate(cd_canvas) cdCanvasClear(cd_canvas) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") draw_cube(floor(w/2),floor(h/2)) cdCanvasFlush(cd_canvas) return IUP_DEFAULT end function function canvas_map_cb(Ihandle canvas) IupGLMakeCurrent(canvas) if platform()=JS then cd_canvas = cdCreateCanvas(CD_IUP, canvas) else atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cd_canvas = cdCreateCanvas(CD_GL, "10x10 %g", {res}) end if cdCanvasSetBackground(cd_canvas, CD_PARCHMENT) return IUP_DEFAULT end function function canvas_resize_cb(Ihandle /*canvas*/) integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cdCanvasSetAttribute(cd_canvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res}) return IUP_DEFAULT end function function timer_cb(Ihandln /*ih*/) -- (feel free to add a bit more randomness here, maybe) rx = mod(rx+359,360) ry = mod(ry+359,360) rz = mod(rz+359,360) IupRedraw(canvas) return IUP_IGNORE end function procedure main() IupOpen() canvas = IupGLCanvas("RASTERSIZE=640x480") IupSetCallbacks(canvas, {"ACTION", Icallback("canvas_action_cb"), "MAP_CB", Icallback("canvas_map_cb"), "RESIZE_CB", Icallback("canvas_resize_cb")}) dlg = IupDialog(canvas,`TITLE="%s"`,{title}) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) Ihandle hTimer = IupTimer(Icallback("timer_cb"), 30) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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 necessary to include additional basic operations, which should not require their own specialised task.
#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, width: width, } }   fn get(&self, row: u32, col: u32) -> f32 { let row = row as usize; let col = col as usize; self.elements[col + row * (self.width as usize)] }   fn set(&mut self, row: u32, col: u32, value: f32) { let row = row as usize; let col = col as usize; self.elements[col + row * (self.width as usize)] = value; }   fn print(&self) { for row in 0..self.height { for col in 0..self.width { print!("{:3.0}", self.get(row, col)); } println!(""); } println!(""); } }   // Matrix addition will perform element-wise addition fn matrix_addition(first: &Matrix, second: &Matrix) -> Result<Matrix, String> { if first.width == second.width && first.height == second.height { let mut result = Matrix::new(vec![0.0f32; (first.height * first.width) as usize], first.height, first.width); for row in 0..first.height { for col in 0..first.width { let first_value = first.get(row, col); let second_value = second.get(row, col); result.set(row, col, first_value + second_value); } } Ok(result) } else { Err("Dimensions don't match".to_owned()) } }   fn scalar_multiplication(scalar: f32, matrix: &Matrix) -> Matrix { let mut result = Matrix::new(vec![0.0f32; (matrix.height * matrix.width) as usize], matrix.height, matrix.width); for row in 0..matrix.height { for col in 0..matrix.width { let value = matrix.get(row, col); result.set(row, col, scalar * value); } } result }   // Subtract second from first fn matrix_subtraction(first: &Matrix, second: &Matrix) -> Result<Matrix, String> { if first.width == second.width && first.height == second.height { let negative_matrix = scalar_multiplication(-1.0, second); let result = matrix_addition(first, &negative_matrix).unwrap(); Ok(result) } else { Err("Dimensions don't match".to_owned()) } }   // First must be a l x m matrix and second a m x n matrix for this to work. fn matrix_multiplication(first: &Matrix, second: &Matrix) -> Result<Matrix, String> { if first.width == second.height { let mut result = Matrix::new(vec![0.0f32; (first.height * second.width) as usize], first.height, second.width); for row in 0..result.height { for col in 0..result.width { let mut value = 0.0; for it in 0..first.width { value += first.get(row, it) * second.get(it, col); } result.set(row, col, value); } } Ok(result) } else { Err("Dimensions don't match. Width of first must equal height of second".to_owned()) } }     fn main() { let height = 2; let width = 3; // Matrix will look like: // | 1.0 2.0 3.0 | // | 4.0 5.0 6.0 | let matrix1 = Matrix::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], height, width);   // Matrix will look like: // | 6.0 5.0 4.0 | // | 3.0 2.0 1.0 | let matrix2 = Matrix::new(vec![6.0, 5.0, 4.0, 3.0, 2.0, 1.0], height, width);   // | 7.0 7.0 7.0 | // | 7.0 7.0 7.0 | matrix_addition(&matrix1, &matrix2).unwrap().print(); // | 2.0 4.0 6.0 | // | 8.0 10.0 12.0 | scalar_multiplication(2.0, &matrix1).print(); // | -5.0 -3.0 -1.0 | // | 1.0 3.0 5.0 | matrix_subtraction(&matrix1, &matrix2).unwrap().print();   // | 1.0 | // | 1.0 | // | 1.0 | let matrix3 = Matrix::new(vec![1.0, 1.0, 1.0], width, 1); // | 6 | // | 15 | matrix_multiplication(&matrix1, &matrix3).unwrap().print(); }
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 angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#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 ELSE turn d*45 dragon length/1.4142136, split-1, 1 turn -d*90 dragon length/1.4142136, split-1, -1 turn d*45 END IF END SUB   ' Main program   SCREEN 12 angle = 0 PSET (150,180), 0 dragon 400, 12, 1 SLEEP
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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 NextPrev := NewNode end Next := NewNode end   A = {CreateNewNode a} B = {CreateNewNode b} C = {CreateNewNode c} in {InsertAfter A B} {InsertAfter A C}
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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#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= █" set "#1_2= █" set "#1_3= █" set "#1_4= █" set "#1_5= █"   set "#2_1=█████" set "#2_2= █" set "#2_3=█████" set "#2_4=█ " set "#2_5=█████"   set "#3_1=█████" set "#3_2= █" set "#3_3=█████" set "#3_4= █" set "#3_5=█████"   set "#4_1=█ █" set "#4_2=█ █" set "#4_3=█████" set "#4_4= █" set "#4_5= █"   set "#5_1=█████" set "#5_2=█ " set "#5_3=█████" set "#5_4= █" set "#5_5=█████"   set "#6_1=█████" set "#6_2=█ " set "#6_3=█████" set "#6_4=█ █" set "#6_5=█████"   set "#7_1=█████" set "#7_2= █" set "#7_3= █" set "#7_4= █" set "#7_5= █"   set "#8_1=█████" set "#8_2=█ █" set "#8_3=█████" set "#8_4=█ █" set "#8_5=█████"   set "#9_1=█████" set "#9_2=█ █" set "#9_3=█████" set "#9_4= █" set "#9_5=█████"   set "#C_1= " set "#C_2=█" set "#C_3= " set "#C_4=█" set "#C_5= "   :clock_loop ::Clear display [leaving a whitespace]... for /l %%C in (1,1,5) do set "display%%C= " ::Get current time [all spaces will be replaced to zero]... ::Also, all colons will be replaced to "C" because colon has a function in variables... set "curr_time=%time: =0%" set "curr_time=%curr_time::=C%" ::Process the numbers to display [we will now use the formats we SET above]... for /l %%T in (0,1,7) do ( ::Check for each number and colons... for %%N in (0 1 2 3 4 5 6 7 8 9 C) do ( if "!curr_time:~%%T,1!"=="%%N" ( ::Now, barbeque each formatted char in 5 rows... for /l %%D in (1,1,5) do set "display%%D=!display%%D!!#%%N_%%D! " ) ) ) ::Refresh the clock... cls echo. echo.[%display1%] echo.[%display2%] echo.[%display3%] echo.[%display4%] echo.[%display5%] echo. timeout /t 1 /nobreak >nul goto :clock_loop
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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 != nothing succ.pred = node end node end   first(nd) = (while nd.pred != nothing nd = nd.prev end; nd) last(nd) = (while nd.succ != nothing nd = nd.succ end; nd)   function printconnected(nd; fromtail = false) if fromtail nd = last(nd) print(nd.value) while nd.pred != nothing nd = nd.pred print(" -> $(nd.value)") end else nd = first(nd) print(nd.value) while nd.succ != nothing nd = nd.succ print(" -> $(nd.value)") end end println() end   node1 = DLNode(1) node2 = DLNode(2) node3 = DLNode(3) insertpost(node1, node2) insertpost(node2, node3) print("From beginning to end: "); printconnected(node1) print("From end to beginning: "); printconnected(node1, fromtail = true)  
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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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(" -> ", node.data.toString()) node = node.next } return sb.toString() } }   var first: Node<E>? = null var last: Node<E>? = null   fun addFirst(value: E) { if (first == null) { first = Node(value) last = first } else { val node = first!! first = Node(value, null, node) node.prev = first } }   fun addLast(value: E) { if (last == null) { last = Node(value) first = last } else { val node = last!! last = Node(value, node, null) node.next = last } }   fun insert(after: Node<E>?, value: E) { if (after == null) addFirst(value) else if (after == last) addLast(value) else { val next = after.next val new = Node(value, after, next) after.next = new if (next != null) next.prev = new } }   override fun toString() = first.toString()   fun firstToLast() = first?.toString() ?: ""   fun lastToFirst(): String { if (last == null) return "" val sb = StringBuilder(last.toString()) var node = last!!.prev while (node != null) { sb.append(" -> ", node.data.toString()) node = node.prev } return sb.toString() } }   fun main(args: Array<String>) { val ll = LinkedList<Int>() ll.addFirst(1) ll.addLast(4) ll.insert(ll.first, 2) ll.insert(ll.last!!.prev, 3) println("First to last : ${ll.firstToLast()}") println("Last to first : ${ll.lastToFirst()}") }
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 Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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()) node = node.next } return sb.toString() } }   fun main(args: Array<String>) { val n1 = Node(1) val n2 = Node(2, n1) n1.next = n2 val n3 = Node(3, n2) n2.next = n3 println(n1) println(n2) println(n3) }
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 Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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) bool { return b1.color < b2.color }   // type for arbitrary ordering of balls type ordering []ball   // predicate tells if balls are ordered by DNF func (o ordering) ordered() bool { var b0 ball for _, b := range o { if b.lt(b0) { return false } b0 = b } return true }   func init() { rand.Seed(time.Now().Unix()) }   // constructor returns new ordering of balls which is randomized but // guaranteed to be not in DNF order. function panics for n < 2. func outOfOrder(n int) ordering { if n < 2 { panic(fmt.Sprintf("%d invalid", n)) } r := make(ordering, n) for { for i, _ := range r { r[i].color = rand.Intn(nColors) } if !r.ordered() { break } } return r }   // O(n) algorithm // http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/ func (a ordering) sort3() { lo, mid, hi := 0, 0, len(a)-1 for mid <= hi { switch a[mid].color { case red: a[lo], a[mid] = a[mid], a[lo] lo++ mid++ case white: mid++ default: a[mid], a[hi] = a[hi], a[mid] hi-- } } }   func main() { f := outOfOrder(12) fmt.Println(f) f.sort3() fmt.Println(f) }
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. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#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-background dup begin-mode-3d S{ Vector3 f 0 0 0 } 2 3 4 LIME draw-cube-wires end-mode-3d end-drawing ] until drop close-window
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 fillRect: (context, int, int, int, int) => unit = "fillRect"   let canvas = getElementById(doc, "my_canvas") let ctx = getContext(canvas, "2d")   ctx.fillStyle = "#F00" fillRect(ctx, 100, 100, 1, 1)
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=="," then x= 100 /*Not specified? Then use the default.*/ if y=='' | y=="," then y= 100 /* " " " " " " */ if CC=='' | CC="," then CC= 4 /* " " " " " " */ if txt=='' | txt="," then tzt= '·' /* " " " " " " */   if ¬!pcrexx then do; say; say "***error*** PC/REXX[interpreter] isn't being used."; say exit 23 end   call scrWrite x,y,txt,,,CC /*stick a fork in it, we're all done. */