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/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
#REXX
REXX
/*REXX program that implements various List Manager functions. */ /*┌────────────────────────────────────────────────────────────────────┐ ┌─┘ Functions of the List Manager └─┐ │ │ │ @init ─── initializes the List. │ │ │ │ @size ─── returns the size of the List [could be 0 (zero)]. │ │ │ │ @show ─── shows (displays) the complete List. │ │ @show k,1 ─── shows (displays) the Kth item. │ │ @show k,m ─── shows (displays) M items, starting with Kth item. │ │ @show ,,─1 ─── shows (displays) the complete List backwards. │ │ │ │ @get k ─── returns the Kth item. │ │ @get k,m ─── returns the M items starting with the Kth item. │ │ │ │ @put x ─── adds the X items to the end (tail) of the List. │ │ @put x,0 ─── adds the X items to the start (head) of the List. │ │ @put x,k ─── adds the X items to before of the Kth item. │ │ │ │ @del k ─── deletes the item K. │ │ @del k,m ─── deletes the M items starting with item K. │ └─┐ ┌─┘ └────────────────────────────────────────────────────────────────────┘*/ call sy 'initializing the list.'  ; call @init call sy 'building list: Was it a cat I saw'; call @put 'Was it a cat I saw' call sy 'displaying list size.'  ; say 'list size='@size() call sy 'forward list'  ; call @show call sy 'backward list'  ; call @show ,,-1 call sy 'showing 4th item'  ; call @show 4,1 call sy 'showing 6th & 6th items'  ; call @show 5,2 call sy 'adding item before item 4: black' ; call @put 'black',4 call sy 'showing list'  ; call @show call sy 'adding to tail: there, in the ...'; call @put 'there, in the shadows, stalking its prey (and next meal).' call sy 'showing list'  ; call @show call sy 'adding to head: Oy!'  ; call @put 'Oy!',0 call sy 'showing list'  ; call @show exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────subroutines─────────────────────────*/ p: return word(arg(1),1) sy: say; say left('',30) "───" arg(1) '───'; return @hasopt: arg o; return pos(o,opt)\==0 @size: return $.# @init: $.@=''; $.#=0; return 0 @adjust: $.@=space($.@); $.#=words($.@); return 0   @parms: arg opt if @hasopt('k') then k=min($.#+1,max(1,p(k 1))) if @hasopt('m') then m=p(m 1) if @hasopt('d') then dir=p(dir 1) return   @show: procedure expose $.; parse arg k,m,dir if dir==-1 & k=='' then k=$.# m=p(m $.#); call @parms 'kmd' say @get(k,m,dir); return 0   @get: procedure expose $.; arg k,m,dir,_ call @parms 'kmd' do j=k for m by dir while j>0 & j<=$.# _=_ subword($.@,j,1) end /*j*/ return strip(_)   @put: procedure expose $.; parse arg x,k k=p(k $.#+1) call @parms 'k' $.@=subword($.@,1,max(0,k-1)) x subword($.@,k) call @adjust return 0   @del: procedure expose $.; arg k,m call @parms 'km' _=subword($.@,k,k-1) subword($.@,k+m) $.@=_ call @adjust return
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
#Delphi
Delphi
  unit main;   interface   uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ExtCtrls;   type TClock = class(TForm) tmrTimer: TTimer; procedure FormResize(Sender: TObject); procedure tmrTimerTimer(Sender: TObject); private { Private declarations } const degrees06 = PI / 30; degrees30 = degrees06 * 5; degrees90 = degrees30 * 3; margin = 20; var p0: TPoint; MinP0XY: Integer; class function IfThen(Condition: Boolean; TrueValue, FalseValue: Integer): Integer; overload; static; class function IfThen(Condition: Boolean; TrueValue, FalseValue: Double): Double; overload; static; procedure Paint; override; procedure DrawHand(Color: TColor; Angle, Size: Double; aWidth: Integer = 2); procedure DrawFace; procedure DrawCenter; procedure DrawNumbers(Angle: Double; Value: Integer); public { Public declarations } end;   var Clock: TClock;   implementation   {$R *.dfm}   { TClock }   procedure TClock.DrawCenter; var radius: Integer; begin radius := 6; with Canvas do begin pen.Color := clNone; Brush.Color := clBlack; Ellipse(p0.x - radius, p0.y - radius, p0.x + radius, p0.y + radius); end; end;   procedure TClock.DrawFace; var radius, h, m: Integer; begin radius := MinP0XY - margin; with Canvas do begin Pen.Color := clBlack; Pen.Width := 2; Brush.Color := clWhite; Ellipse(p0.x - radius, p0.y - radius, p0.x + radius, p0.y + radius); for m := 0 to 59 do DrawHand(clGray, m * degrees06, -0.08, 2);   for h := 0 to 11 do begin DrawHand(clBlack, h * degrees30, -0.09, 3); DrawNumbers((h + 3) * degrees30, 12 - h); end; end; end;   procedure TClock.DrawHand(Color: TColor; Angle, Size: Double; aWidth: Integer = 2); var radius, x0, y0, x1, y1: Integer; begin radius := MinP0XY - margin;   x0 := p0.X + (IfThen(Size > 0, 0, Round(radius * (Size + 1) * cos(Angle)))); y0 := p0.Y + (IfThen(Size > 0, 0, Round(radius * (Size + 1) * sin(-Angle))));   x1 := p0.X + round(radius * IfThen(Size > 0, Size, 1) * cos(Angle)); y1 := p0.y + round(radius * IfThen(Size > 0, Size, 1) * sin(-Angle));   with Canvas do begin Pen.Color := Color; pen.Width := aWidth; MoveTo(x0, y0); LineTo(x1, y1); end; end;   procedure TClock.DrawNumbers(Angle: Double; Value: Integer); var radius, x0, y0, x1, y1, h, w: Integer; Size: Double; s: string; begin radius := MinP0XY - margin; Size := 0.85; s := (Value).ToString;   x1 := p0.X + round(radius * Size * cos(Angle)); y1 := p0.y + round(radius * Size * sin(-Angle));   with Canvas do begin radius := 5; Font.Size := 12; w := TextWidth(s); h := TextHeight(s);   x0 := x1 - (w div 2); y0 := y1 - (h div 2);   TextOut(x0, y0, s); end; end;   procedure TClock.FormResize(Sender: TObject); begin p0 := Tpoint.create(ClientRect.CenterPoint); MinP0XY := p0.x; if MinP0XY > p0.Y then MinP0XY := p0.y; Refresh(); end;   class function TClock.IfThen(Condition: Boolean; TrueValue, FalseValue: Double): Double; begin if Condition then exit(TrueValue); exit(FalseValue); end;   class function TClock.IfThen(Condition: Boolean; TrueValue, FalseValue: Integer): Integer; begin if Condition then exit(TrueValue); exit(FalseValue); end;   procedure TClock.Paint; var t: TDateTime; second, minute, hour: Integer; angle, minsecs, hourmins: Double; begin inherited;   t := time; second := trunc(Frac(t * 24 * 60) * 60); minute := trunc(Frac(t * 24) * 60); hour := trunc(t * 24);   DrawFace;   angle := degrees90 - (degrees06 * second); DrawHand(clred, angle, 0.95, 3);   minsecs := (minute + second / 60.0);   angle := degrees90 - (degrees06 * minsecs); DrawHand(clGreen, angle, 0.8, 4);   hourmins := (hour + minsecs / 60.0); angle := degrees90 - (degrees30 * hourmins); DrawHand(clBlue, angle, 0.6, 5);   DrawCenter;   Caption := Format('%.2d:%.2d:%.2d', [hour, minute, second]); end;   procedure TClock.tmrTimerTimer(Sender: TObject); begin Refresh; end;   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
#Phix
Phix
enum NEXT,PREV,DATA constant empty_dll = {{1,1}} sequence dll = deep_copy(empty_dll) procedure insert_after(object data, integer pos=1) integer prv = dll[pos][PREV] dll = append(dll,{pos,prv,data}) if prv!=0 then dll[prv][NEXT] = length(dll) end if dll[pos][PREV] = length(dll) end procedure insert_after("ONE") insert_after("TWO") insert_after("THREE") ?dll procedure show(integer d) integer idx = dll[1][d] while idx!=1 do ?dll[idx][DATA] idx = dll[idx][d] end while end procedure show(NEXT) ?"==" show(PREV)
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
#PicoLisp
PicoLisp
# Print the elements a doubly-linked list (de 2print (DLst) (for (L (car DLst) L (cddr L)) (printsp (car L)) ) (prinl) )   # Print the elements a doubly-linked list in reverse order (de 2printReversed (DLst) (for (L (cdr DLst) L (cadr L)) (printsp (car L)) ) (prinl) )
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
#Plain_English
Plain English
An element is a thing with a number.
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
#Pop11
Pop11
uses objectclass; define :class Link; slot next = []; slot prev = []; slot data = []; enddefine;
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
#PureBasic
PureBasic
Structure node *prev.node *next.node value.i EndStructure
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
#Python
Python
class Node(object): def __init__(self, data = None, prev = None, next = None): self.prev = prev self.next = next self.data = data def __str__(self): return str(self.data) def __repr__(self): return repr(self.data) def iter_forward(self): c = self while c != None: yield c c = c.next def iter_backward(self): c = self while c != None: yield c c = c.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)
#Julia
Julia
  const COLORS = ["red", "white", "blue"]   function dutchsort!(a::Array{ASCIIString,1}, lo=COLORS[1], hi=COLORS[end]) i = 1 j = 1 n = length(a) while j <= n if a[j] == lo a[i], a[j] = a[j], a[i] i += 1 j += 1 elseif a[j] == hi a[j], a[n] = a[n], a[j] n -= 1 else j += 1 end end return a end   function dutchsort(a::Array{ASCIIString,1}, lo=COLORS[1], hi=COLORS[end]) dutchsort!(copy(a), lo, hi) 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)
#Kotlin
Kotlin
// version 1.1.4   import java.util.Random   enum class DutchColors { RED, WHITE, BLUE }   fun Array<DutchColors>.swap(i: Int, j: Int) { val temp = this[i] this[i] = this[j] this[j] = temp }   fun Array<DutchColors>.sort() { var lo = 0 var mid = 0 var hi = this.lastIndex   while (mid <= hi) { when (this[mid]) { DutchColors.RED -> this.swap(lo++, mid++) DutchColors.WHITE -> mid++ DutchColors.BLUE -> this.swap(mid, hi--) } } }   fun Array<DutchColors>.isSorted(): Boolean { return (1 until this.size) .none { this[it].ordinal < this[it - 1].ordinal } }   const val NUM_BALLS = 9   fun main(args: Array<String>) { val r = Random() val balls = Array(NUM_BALLS) { DutchColors.RED } val colors = DutchColors.values()   // give balls random colors whilst ensuring they're not already sorted do { for (i in 0 until NUM_BALLS) balls[i] = colors[r.nextInt(3)] } while (balls.isSorted())   // print the colors of the balls before sorting println("Before sorting : ${balls.contentToString()}")   // sort the balls in DutchColors order balls.sort()   // print the colors of the balls after sorting println("After sorting  : ${balls.contentToString()}") }
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
#J
J
vectors =. ((% +/&.:*:"1) _1 1 0,:_1 _1 3) +/@:*"1/~ 2 3 4*=i.3 ' .*o' {~ +/ 1 2 3* (|:"2 -."_ 1~ vectors) ([:*./ 1 = 0 1 I. %.~)"_ 1"_1 _ ]4j21 ,~"0/&:i: 4j41               oooo ooooooooooooo oooooooooooooo.... *****oooo......... *******........... *******........... *******........... *******........... *******........... *******........... *******........... *******......... *****.....    
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
#True_BASIC
True BASIC
SET WINDOW 0, 320, 0, 240 SET COLOR 4 PLOT 100,100 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
#VBA
VBA
Sub draw() Dim sh As Shape, sl As Shape Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240) Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100) sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0) End Sub
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
#TI-83_BASIC
TI-83 BASIC
:-1→Xmin:1→Xmax :-1→Ymin:1→Ymax :AxesOff :Degrees :While 1 :For(X,0,359,5 :sin(X-120→I% :sin(X→PV :sin(X+120→FV :Line(0,1,I%,.3 :Line(0,1,PV,.3 :Line(0,1,FV,.3 :Line(0,-1,-I%,-.3 :Line(0,-1,-PV,-.3 :Line(0,-1,-FV,-.3 :Line(.3,I%,-.3,-PV :Line(.3,I%,-.3,-FV :Line(.3,PV,-.3,-I% :Line(.3,PV,-.3,-FV :Line(.3,FV,-.3,-I% :Line(.3,FV,-.3,-PV :End :End
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
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "math" for Math   var Nodes = [ [-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1], [ 1, -1, -1], [ 1, -1, 1], [ 1, 1, -1], [ 1, 1, 1] ]   var 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] ]   class RotatingCube { construct new(width, height) { Window.title = "Rotating cube" Window.resize(width, height) Canvas.resize(width, height) _width = width _height = height _fore = Color.blue }   init() { scale(100) rotateCube(Num.pi / 4, Math.atan(2.sqrt)) drawCube() }   update() { rotateCube(Num.pi / 180, 0) }   draw(alpha) { drawCube() }   scale(s) { for (node in Nodes) { node[0] = node[0] * s node[1] = node[1] * s node[2] = node[2] * s } }   drawCube() { Canvas.cls(Color.white) Canvas.offset(_width / 2, _height / 2) for (edge in Edges) { var xy1 = Nodes[edge[0]] var xy2 = Nodes[edge[1]] Canvas.line(Math.round(xy1[0]), Math.round(xy1[1]), Math.round(xy2[0]), Math.round(xy2[1]), _fore) } for (node in Nodes) { Canvas.rectfill(Math.round(node[0]) - 4, Math.round(node[1]) - 4, 8, 8, _fore) } }   rotateCube(angleX, angleY) { var sinX = Math.sin(angleX) var cosX = Math.cos(angleX) var sinY = Math.sin(angleY) var cosY = Math.cos(angleY) for (node in Nodes) { var x = node[0] var y = node[1] var z = node[2] node[0] = x * cosX - z * sinX node[2] = z * cosX + x * sinX z = node[2] node[1] = y * cosY - z * sinY node[2] = z * cosY + y * sinY } } }   var Game = RotatingCube.new(640, 640)
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.
#Befunge
Befunge
" :htpeD">:#,_&>:00p:2%10p:2/:1+1>\#<1#*-#2:#\_$:1-20p510g2*-*1+610g4vv<v< | v%2\/3-1$_\#!4#:*#-\#1<\1+1:/4+1g00:\_\#$1<%2/2+1\g02\-1+%-g012\/-*<v"*/ _ >!>0$#0\#$\_-10p20p::00g4/:1+1>\#<1#*-#4:#\_$1-2*3/\2%!>0$#0\#$\_--vv|+2 v:\p06!*-1::p05<g00+1--g01g03\+-g01-p04+1:<0p03:-1_>>$$$1-\1->>:v:+1\<v~:: >:1+*!60g*!#v_!\!*50g0`*!40gg,::30g40g:2-#^_>>$>>:^:+1g02::\,+55_55+,@v":* v%2/2+*">~":< ^\-1g05-*">~"/2+*"|~"-%*"|~"\/*"|~":\-*">~"/2+%*"|~"\/*<^<: >60p\:"~>"*+2/2%60g+2%70p:"kI"*+2/2%60p\:"kI"*+2/2%60g+2%-\70g-"~|"**+"}"^
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
#Emacs_Lisp
Emacs Lisp
; Draw a sphere   (defun normalize (v) "Normalize a vector." (setq invlen (/ 1.0 (sqrt (dot v v)))) (mapcar (lambda (x) (* invlen x)) v))   (defun dot (v1 v2) "Dot product of two vectors." (+ (* (car v1) (car v2)) (* (cadr v1) (cadr v2)) (* (caddr v1) (caddr v2))))   (defun make-array (size) "Create an empty array with size*size elements." (setq m-array (make-vector size nil)) (dotimes (i size) (setf (aref m-array i) (make-vector size 0))) m-array)   (defun pic-lines (arr size) "Turn array into a string." (setq all "") (dotimes (y size) (setq line "") (dotimes (x size) (setq line (concat line (format "%i \n" (elt (elt arr y) x))))) (setq all (concat all line "\n"))) all)   (defun pic-show (arr size) "Convert size*size array to grayscale PBM image and show it." (insert-image (create-image (concat (format "P2 %i %i 255\n" size size) (pic-lines arr size)) 'pbm t)))   (defun sphere (size k amb dir) "Draw a sphere." (let ((arr (make-array size)) (ndir (normalize dir)) (r (/ size 2))) (dotimes (yp size) (dotimes (xp size) (setq x (- xp r)) (setq y (- yp r)) (setq z (- (* r r) (* x x) (* y y))) (if (>= z 0) (let* ((vec (normalize (list x y (sqrt z)))) (s (max 0 (dot vec ndir))) (lum (max 0 (min 255 (* 255 (+ amb (expt s k)) (/ (1+ amb))))))) (setf (elt (elt arr yp) xp) lum))))) (pic-show arr size)))   (sphere 200 1.5 0.2 '(-30 -30 50))
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
#Ruby
Ruby
class DListNode def insert_after(search_value, new_value) if search_value == value new_node = self.class.new(new_value, nil, nil) next_node = self.succ self.succ = new_node new_node.prev = self new_node.succ = next_node next_node.prev = new_node elsif self.succ.nil? raise StandardError, "value #{search_value} not found in list" else self.succ.insert_after(search_value, new_value) end end end   head = DListNode.from_array([:a, :b]) head.insert_after(: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
#Rust
Rust
use std::collections::LinkedList; fn main() { let mut list = LinkedList::new(); list.push_front(8); }
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
#Swift
Swift
typealias NodePtr<T> = UnsafeMutablePointer<Node<T>>   class Node<T> { var value: T fileprivate var prev: NodePtr<T>? fileprivate var next: NodePtr<T>?   init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) { self.value = value self.prev = prev self.next = next } }   @discardableResult func insert<T>(_ val: T, after: Node<T>? = nil, list: NodePtr<T>? = nil) -> NodePtr<T> { let node = NodePtr<T>.allocate(capacity: 1)   node.initialize(to: Node(value: val))   var n = list   while n != nil { if n?.pointee !== after { n = n?.pointee.next   continue }   node.pointee.prev = n node.pointee.next = n?.pointee.next n?.pointee.next?.pointee.prev = node n?.pointee.next = node   break }   return node }   // [1] let list = insert(1)   // [1, 2] insert(2, after: list.pointee, list: list)   // [1, 3, 2] insert(3, after: list.pointee, list: list)
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
#Tcl
Tcl
oo::define List { method insertBefore {elem} { $elem next [self] $elem previous $prev if {$prev ne ""} { $prev next $elem } set prev $elem } method insertAfter {elem} { $elem previous [self] $elem next $next if {$next ne ""} { $next previous $elem } set next $elem } }
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must 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
#EasyLang
EasyLang
# Clock # func draw hour min sec . . # dial color 333 move 50 50 circle 45 color 797 circle 44 color 333 for i range 60 a = i * 6 move 50 + sin a * 40 50 - cos a * 40 circle 0.25 . for i range 12 a = i * 30 move 50 + sin a * 40 50 - cos a * 40 circle 1 . # hour linewidth 2 color 000 a = (hour * 60 + min) / 2 move 50 50 line 50 + sin a * 32 50 - cos a * 32 # min linewidth 1.5 a = (sec + min * 60) / 10 move 50 50 line 50 + sin a * 40 50 - cos a * 40 # sec linewidth 1 color 700 a = sec * 6 move 50 50 line 50 + sin a * 40 50 - cos a * 40 . on timer if t <> floor systime t = floor systime h$ = timestr t sec = number substr h$ 17 2 min = number substr h$ 14 2 hour = number substr h$ 11 2 if hour > 12 hour -= 12 . call draw hour min sec . timer 0.1 . timer 0
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
#PL.2FI
PL/I
/* To implement a doubly-linked list -- i.e., a 2-way linked list. */ doubly_linked_list: proc options (main);   define structure 1 node, 2 value fixed, 2 fwd_pointer handle(node), 2 back_pointer handle(node);   declare (head, tail, t) handle (node); declare null builtin; declare i fixed binary;   head, tail = bind(:node, null:);   do i = 1 to 10; /* Add ten items to the tail of the queue. */ if head = bind(:node, null:) then do; head,tail = new(:node:); get list (head => value); put skip list (head => value); head => back_pointer, head => fwd_pointer = bind(:node, null:); /* A NULL link */ end; else do; t = new(:node:); t => back_pointer = tail; /* Point the new tail back to the old */ /* tail. */ tail => fwd_pointer = t; /* Point the tail to the new node. */ t => back_pointer = tail; /* Point the new tail back to the old */ /* tail. */ tail = t; /* Point at the new tail. */ tail => fwd_pointer = bind(:node, null:); /* Set the tail link to NULL */ get list (tail => value) copy; put skip list (tail => value); end; end;   if head = bind(:node, null:) then return; /* Empty list. */   /* Traverse the list from the head. */ put skip list ('In a forwards direction, the list has:'); t = head; do while (t ^= bind(:node, null:)); put skip list (t => value); t = t => fwd_pointer; end; /* Traverse the list from the tail to the head. */ put skip list ('In the reverse direction, the list has:'); t = tail; do while (t ^= bind(:node, null:)); put skip list (t => value); t = t => back_pointer; end; end doubly_linked_list;
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
#PureBasic
PureBasic
NewList MyData.i() ; Create a double linked list holding a single value (integer)   ;Set up a randomly long linked list in the range 25-125 elements For i=0 To (Random(100)+25) AddElement(MyData()) ; Create a new tailing element MyData()=Random(314) ; Inert a vale into it Next ; ;Traverse from the beginning of a doubly-linked list to the end. FirstElement(MyData()) Repeat Debug MyData() ; Present the value in the current cell Until Not NextElement(MyData()) ; ;Traverse from the end to the beginning. LastElement(MyData()) Repeat Debug MyData() ; Present the value in the current cell Until Not PreviousElement(MyData())
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
#Racket
Racket
  (define-struct dlist (head tail) #:mutable) (define-struct dlink (content prev next) #:mutable)  
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
#Raku
Raku
role DLElem[::T] { has DLElem[T] $.prev is rw; has DLElem[T] $.next is rw; has T $.payload = T;   method pre-insert(T $payload) { die "Can't insert before beginning" unless $!prev; my $elem = ::?CLASS.new(:$payload); $!prev.next = $elem; $elem.prev = $!prev; $elem.next = self; $!prev = $elem; $elem; }   method post-insert(T $payload) { die "Can't insert after end" unless $!next; my $elem = ::?CLASS.new(:$payload); $!next.prev = $elem; $elem.next = $!next; $elem.prev = self; $!next = $elem; $elem; }   method delete { die "Can't delete a sentinel" unless $!prev and $!next; $!next.prev = $!prev; $!prev.next = $!next; # conveniently returns next element } }
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)
#Lasso
Lasso
define orderdutchflag(a) => { local(r = array, w = array, b = array) with i in #a do => { match(#i) => { case('Red') #r->insert(#i) case('White') #w->insert(#i) case('Blue') #b->insert(#i) } } return #r + #w + #b }   orderdutchflag(array('Red', 'Red', 'Blue', 'Blue', 'Blue', 'Red', 'Red', 'Red', 'White', 'Blue'))
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national 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)
#Logo
Logo
; We'll just use words for the balls make "colors {red white blue}   ; to get a mapping from colors back to a numeric value, ; we make variables out of the color names (e.g. the variable ; "red" has value "1"). foreach arraytolist :colors [ make ? # ]   ; Make a random list of a given size to random_balls :n local "balls make "balls array n repeat n [ setitem # :balls pick :colors ] output :balls end   ; Test for Dutchness to dutch? :array output dutchlist? arraytolist :array end   ; List is easier than array to test to dutchlist? :list output cond [ [(less? count :list 2) "true] [(greater? thing first :list thing item 2 :list) "false ] [else dutchlist? butfirst :list] ] end   ; But array is better for sorting algorithm to dutch :array local "lo make "lo 0 local "hi make "hi sum 1 count :array local "i make "i 1 while [:i < :hi] [ case (item :i :array) [ [[red] make "lo sum :lo 1 swap :array :lo :i make "i sum :i 1 ] [[white] make "i sum :i 1 ] [[blue] make "hi difference :hi 1 swap :array :hi :i ] ] ] output :array end   ; utility routine to swap array elements to swap :array :a :b local "temp make "temp item :a :array setitem :a :array item :b :array setitem :b :array :temp 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
#Java
Java
import java.awt.*; import java.awt.event.*; import static java.lang.Math.*; import javax.swing.*;   public class Cuboid extends JPanel { double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1}, {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};   int[][] 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}};   int mouseX, prevMouseX, mouseY, prevMouseY;   public Cuboid() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white);   scale(80, 120, 160); rotateCube(PI / 5, PI / 9);   addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); } });   addMouseMotionListener(new MouseAdapter() { @Override public void mouseDragged(MouseEvent e) { prevMouseX = mouseX; prevMouseY = mouseY; mouseX = e.getX(); mouseY = e.getY();   double incrX = (mouseX - prevMouseX) * 0.01; double incrY = (mouseY - prevMouseY) * 0.01;   rotateCube(incrX, incrY); repaint(); } }); }   private void scale(double sx, double sy, double sz) { for (double[] node : nodes) { node[0] *= sx; node[1] *= sy; node[2] *= sz; } }   private void rotateCube(double angleX, double angleY) { double sinX = sin(angleX); double cosX = cos(angleX);   double sinY = sin(angleY); double cosY = cos(angleY);   for (double[] node : nodes) { double x = node[0]; double y = node[1]; double z = node[2];   node[0] = x * cosX - z * sinX; node[2] = z * cosX + x * sinX;   z = node[2];   node[1] = y * cosY - z * sinY; node[2] = z * cosY + y * sinY; } }   void drawCube(Graphics2D g) { g.translate(getWidth() / 2, getHeight() / 2);   for (int[] edge : edges) { double[] xy1 = nodes[edge[0]]; double[] xy2 = nodes[edge[1]]; g.drawLine((int) round(xy1[0]), (int) round(xy1[1]), (int) round(xy2[0]), (int) round(xy2[1])); }   for (double[] node : nodes) { g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8); } }   @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);   drawCube(g); }   public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Cuboid"); f.setResizable(false); f.add(new Cuboid(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
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
#Vlang
Vlang
import gg import gx   fn main() { mut context := gg.new_context( width: 320 height: 240 frame_fn: frame ) context.run() }   fn frame(mut ctx gg.Context) { ctx.begin() ctx.draw_pixel(100, 100, gx.red) ctx.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
#Wee_Basic
Wee Basic
keyhide plot 0 100,100,5 end
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
#XPL0
XPL0
def Size=100., Speed=0.05; \drawing size and rotation speed real X, Y, Z, Farthest; \arrays: 3D coordinates of vertices int I, J, K, ZI, Edge; def R2=sqrt(2.), R3=sqrt(3.), R13=sqrt(1./3.), R23=sqrt(2./3.), R232=R23*2.; \vertex:0 1 2 3 4 5 6 7 [X:= [ 0., R2, 0., -R2, 0., R2, 0., -R2]; Y:= [ -R3, -R13, R13, -R13, -R13, R13, R3, R13]; Z:= [ 0., -R23, -R232, -R23, R232, R23, 0., R23]; Edge:= [0,1, 1,2, 2,3, 3,0, 4,5, 5,6, 6,7, 7,4, 0,4, 1,5, 2,6, 3,7]; SetVid($101); \set 640x480x8 graphics repeat Farthest:= 0.0; \find the farthest vertex for I:= 0 to 8-1 do if Z(I) > Farthest then [Farthest:= Z(I); ZI:= I]; Clear; \erase screen for I:= 0 to 2*12-1 do \for all the vertices... [J:= Edge(I); I:= I+1; \get vertex numbers for edge Move(Fix(X(J)*Size)+640/2, Fix(Y(J)*Size)+480/2); K:= Edge(I); Line(Fix(X(K)*Size)+640/2, Fix(Y(K)*Size)+480/2, if J=ZI ! K=ZI then $F001 \dashed blue\ else $0C \red\); ]; DelayUS(55000); for I:= 0 to 8-1 do [X(I):= X(I) + Z(I)*Speed; \rotate vertices about Y axis Z(I):= Z(I) - X(I)*Speed; \ (which rotates in X-Z plane) ]; until KeyHit; \run until a key is struck SetVid(3); \restore normal text mode ]
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
#Yabasic
Yabasic
// Rosetta Code problem: http://rosettacode.org/wiki/Draw_a_rotating_cube // adapted to Yabasic by Galileo, 05/2022   // GFA Punch (code from tigen.ti-fr.com/) // Carré 3D en rotation   open window 50, 70 backcolor 0,0,0 clear window color 255,255,255   do clear window x = COS(T) * 20 y = SIN(T) * 18 r = SIN(T + T)   line (x + 40), (y + 40 - r), (-y + 40), (x + 40 - r) line (-y + 40), (x + 40 - r), (-x + 40), (-y + 40 - r) line (-x + 40), (-y + 40 - r), (y + 40), (-x + 40 - r) line (y + 40), (-x + 40 - r), (x + 40), (y + 40 - r)   line (x + 40), (y + 20 + r), (-y + 40), (x + 20 + r) line (-y + 40), (x + 20 + r), (-x + 40), (-y + 20 + r) line (-x + 40), (-y + 20 + r), (y + 40), (-x + 20 + r) line (y + 40), (-x + 20 + r), (x + 40), (y + 20 + r) line (x + 40), (y + 40 - r), (x + 40), (y + 20 + r) line (-y + 40), (x + 40 - r), (-y + 40), (x + 20 + r) line (-x + 40), (-y + 40 - r), (-x + 40), (-y + 20 + r) line (y + 40), (-x + 40 - r), (y + 40), (-x + 20 + r)   pause 0.02 T = T + 0.15 loop
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.
#BQN
BQN
Rot ← ¬⊸{-⌾(𝕨⊸⊑)⌽𝕩} Turns ← {{𝕩∾1∾¬⌾((⌊2÷˜≠)⊸⊑)𝕩}⍟𝕩 ⥊1}   •Plot´ <˘⍉>+` (<0‿1)(Rot˜)`Turns 3
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
#ERRE
ERRE
PROGRAM SPHERE   CONST SHADES$=".:!*oe&#%@"   DIM LIGHT[2],X[2],Y[2],V[2],VEC[2]   PROCEDURE DOT(X[],Y[]->D) D=X[0]*Y[0]+X[1]*Y[1]+X[2]*Y[2] IF D<0 THEN D=-D ELSE D=0 END IF END PROCEDURE   PROCEDURE NORMALIZE(V[]->V[]) LUNG=SQR(V[0]*V[0]+V[1]*V[1]+V[2]*V[2]) V[0]=V[0]/LUNG V[1]=V[1]/LUNG V[2]=V[2]/LUNG END PROCEDURE   PROCEDURE PDRAW(R,K,AMBIENT) FOR I=INT(-R) TO INT(R) DO X=I+0.5 FOR J=INT(-2*R) TO INT(2*R) DO Y=J/2+0.5 IF (X*X+Y*Y<=R*R) THEN VEC[0]=X VEC[1]=Y VEC[2]=SQR(R*R-X*X-Y*Y) NORMALIZE(VEC[]->VEC[]) DOT(LIGHT[],VEC[]->D) B=D^K+AMBIENT INTENSITY%=(1-B)*(LEN(SHADES$)-1) IF (INTENSITY%<0) THEN INTENSITY%=0 END IF IF (INTENSITY%>=LEN(SHADES$)-1) THEN INTENSITY%=LEN(SHADES$)-2 END IF PRINT(#1,MID$(SHADES$,INTENSITY%+1,1);) ELSE PRINT(#1,(" ");) END IF END FOR PRINT(#1,) END FOR END PROCEDURE   BEGIN LIGHT[]=(30,30,-50) OPEN("O",1,"SPHERE.PRN") NORMALIZE(LIGHT[]->LIGHT[]) PDRAW(10,2,0.4)   PRINT(#1,STRING$(79,"=")) PDRAW(20,4,0.1) CLOSE(1) END PROGRAM  
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
#Visual_Basic_.NET
Visual Basic .NET
Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T) Dim node As New Node(Of T)(value) a.Next = node node.Previous = a b.Previous = node node.Next = b End Sub
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
#Wren
Wren
import "/llist" for DLinkedList   var dll = DLinkedList.new(["A", "B"]) dll.insertAfter("A", "C") System.print(dll)
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
#Yabasic
Yabasic
// Rosetta Code problem: http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion & removal & traverse // by Galileo, 02/2022   FIL = 1 : DATO = 2 : LPREV = 3 : LNEXT = 4 countNodes = 0 : Nodes = 10   dim list(Nodes, 4)   list(0, LNEXT) = 1     sub searchNode(node) local i, Node   for i = 0 to node-1 Node = list(Node, LNEXT) next return Node end sub   sub insertNode(node, newNode) local Node, i   if not countNodes node = 2   for i = 1 to Nodes if not list(i, FIL) break next list(i, FIL) = true list(i, DATO) = newNode   Node = searchNode(node)   list(i, LPREV) = list(Node, LPREV) : list(list(i, LPREV), LNEXT) = i if i <> Node list(i, LNEXT) = Node : list(Node, LPREV) = i   countNodes = countNodes + 1 if countNodes = Nodes then Nodes = Nodes + 10 : redim list(Nodes, 4) : end if end sub     sub removeNode(n) local Node   Node = searchNode(n) list(list(Node, LPREV), LNEXT) = list(Node, LNEXT) list(list(Node, LNEXT), LPREV) = list(Node, LPREV) list(Node, LNEXT) = 0 : list(Node, LPREV) = 0 list(Node, FIL) = false countNodes = countNodes - 1 end sub     sub printNode(node) local Node   Node = searchNode(node) print list(Node, DATO); print end sub     sub traverseList() local i   for i = 1 to countNodes printNode(i) next end sub     insertNode(1, 1000) insertNode(2, 2000) insertNode(2, 3000)   traverseList()   removeNode(2)   print traverseList()
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
#F.23
F#
open System.Text.RegularExpressions   let numberTemplate = """ _ _ _ _ __ _ _ / \ /| ) _)|_||_ / /(_)(_) * \_/ | /_ _) | _)(_) / (_) / * """ let g = numberTemplate.Split([|'\n';'\r'|], System.StringSplitOptions.RemoveEmptyEntries) |> Array.map (fun s -> Regex.Matches(s, "...") |> Seq.cast<Match> |> Seq.map (fun m -> m.ToString()) |> Seq.toArray)   let idx c = let v c = ((int) c) - ((int) '0') let i = v c if 0 <= i && i <= 9 then i elif c = ':' then 10 else failwith ("Cannot draw character " + c.ToString())   let draw (s :string) = System.Console.Clear() g |> Array.iter (fun a -> s.ToCharArray() |> Array.iter (fun c -> let i = idx c printf "%s" (a.[i])) printfn "" )   [<EntryPoint>] let main argv = let showTime _ = draw (System.String.Format("{0:HH:mm:ss}", (System.DateTime.Now))) let timer = new System.Timers.Timer(500.) timer.AutoReset <- true // The timer triggers cyclically timer.Elapsed // An event stream |> Observable.subscribe showTime |> ignore // Subscribe to the event stream timer.Start() // Now it counts System.Console.ReadLine() |> ignore // Until return is hit showTime () 0
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
#Python
Python
class List: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev   def append(self, data): if self.next == None: self.next = List(data, None, self) return self.next else: return self.next.append(data)   # Build the list tail = head = List(10) for i in [ 20, 30, 40 ]: tail = tail.append(i)   # Traverse forwards node = head while node != None: print(node.data) node = node.next   # Traverse Backwards node = tail while node != None: print(node.data) node = node.prev
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
#Racket
Racket
(define (dlist-elements dlist) (let loop ([elements '()] [dlink (dlist-tail dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-prev dlink)) elements)))   (define (dlist-elements/reverse dlist) (let loop ([elements '()] [dlink (dlist-head dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-next dlink)) elements)))
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
#REXX
REXX
╔═════════════════════════════════════════════════════════════════════════╗ ║ ☼☼☼☼☼☼☼☼☼☼☼ Functions of the List Manager ☼☼☼☼☼☼☼☼☼☼☼ ║ ║ @init ─── initializes the List. ║ ║ ║ ║ @size ─── returns the size of the List [could be a 0 (zero)]. ║ ║ ║ ║ @show ─── shows (displays) the complete List. ║ ║ @show k,1 ─── shows (displays) the Kth item. ║ ║ @show k,m ─── shows (displays) M items, starting with Kth item. ║ ║ @show ,,─1 ─── shows (displays) the complete List backwards. ║ ║ ║ ║ @get k ─── returns the Kth item. ║ ║ @get k,m ─── returns the M items starting with the Kth item. ║ ║ ║ ║ @put x ─── adds the X items to the end (tail) of the List. ║ ║ @put x,0 ─── adds the X items to the start (head) of the List. ║ ║ @put x,k ─── adds the X items to before of the Kth item. ║ ║ ║ ║ @del k ─── deletes the item K. ║ ║ @del k,m ─── deletes the M items starting with item K. ║ ╚═════════════════════════════════════════════════════════════════════════╝
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
#Ruby
Ruby
class DListNode < ListNode attr_accessor :prev # accessors :succ and :value are inherited   def initialize(value, prev=nil, succ=nil) @value = value @prev = prev @prev.succ = self if prev @succ = succ @succ.prev = self if succ end   def self.from_values(*ary) ary << (f = ary.pop) ary.map! {|i| new i } ary.inject(f) {|p, c| p.succ = c; c.prev = p; c } end end   list = DListNode.from_values 1,2,3,4
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
#Rust
Rust
use std::collections::LinkedList; fn main() { // Doubly linked list containing 32-bit integers let list = LinkedList::<i32>::new(); }
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)
#Lua
Lua
-- "1. Generate a randomized order of balls.." math.randomseed(os.time()) N, balls, colors = 10, {}, { "red", "white", "blue" } for i = 1, N do balls[i] = colors[math.random(#colors)] end -- "..ensuring that they are not in the order of the Dutch national flag." order = { red=1, white=2, blue=3 } function issorted(t) for i = 2, #t do if order[t[i]] < order[t[i-1]] then return false end end return true end local function shuffle(t) for i = #t, 2, -1 do local j = math.random(i) t[i], t[j] = t[j], t[i] end end while issorted(balls) do shuffle(balls) end print("RANDOM: "..table.concat(balls,","))   -- "2. Sort the balls in a way idiomatic to your language." table.sort(balls, function(a, b) return order[a] < order[b] end)   -- "3. Check the sorted balls are in the order of the Dutch national flag." print("SORTED: "..table.concat(balls,",")) print(issorted(balls) and "Properly sorted." or "IMPROPERLY SORTED!!")
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
#JavaScript
JavaScript
<!DOCTYPE html> <html lang="en">   <head> <meta charset="UTF-8"> <style> canvas { background-color: black; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.querySelector("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight;   var g = canvas.getContext("2d");   canvas.addEventListener("mousemove", function (event) { prevMouseX = mouseX; prevMouseY = mouseY; mouseX = event.x; mouseY = event.y;   var incrX = (mouseX - prevMouseX) * 0.01; var incrY = (mouseY - prevMouseY) * 0.01;   rotateCuboid(incrX, incrY); drawCuboid(); });   var nodes = [[-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1], [1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1]];   var 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]];   var mouseX = 0, prevMouseX, mouseY = 0, prevMouseY;   function scale(factor0, factor1, factor2) { nodes.forEach(function (node) { node[0] *= factor0; node[1] *= factor1; node[2] *= factor2; }); }   function rotateCuboid(angleX, angleY) {   var sinX = Math.sin(angleX); var cosX = Math.cos(angleX);   var sinY = Math.sin(angleY); var cosY = Math.cos(angleY);   nodes.forEach(function (node) { var x = node[0]; var y = node[1]; var z = node[2];   node[0] = x * cosX - z * sinX; node[2] = z * cosX + x * sinX;   z = node[2];   node[1] = y * cosY - z * sinY; node[2] = z * cosY + y * sinY; }); }   function drawCuboid() { g.save();   g.clearRect(0, 0, canvas.width, canvas.height); g.translate(canvas.width / 2, canvas.height / 2); g.strokeStyle = "#FFFFFF"; g.beginPath();   edges.forEach(function (edge) { var p1 = nodes[edge[0]]; var p2 = nodes[edge[1]]; g.moveTo(p1[0], p1[1]); g.lineTo(p2[0], p2[1]); });   g.closePath(); g.stroke();   g.restore(); }   scale(80, 120, 160); rotateCuboid(Math.PI / 5, Math.PI / 9); </script>   </body> </html>
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
#Wren
Wren
import "dome" for Window import "graphics" for Canvas, Color   class Game { static init() { Window.title = "Draw a pixel" Window.resize(320, 240) Canvas.resize(320, 240) var red = Color.rgb(255, 0, 0) Canvas.pset(100, 100, red) // check it worked var col = Canvas.pget(100, 100) System.print("The color of the pixel at (100, 100) is %(getRGB(col))") }   static update() {}   static draw(dt) {}   static getRGB(col) { "{%(col.r), %(col.g), %(col.b)}" } }
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
#X86_Assembly
X86 Assembly
  .model tiny .code org 100h   start: mov ax, 0013h  ;set 320x200x8 graphic screen int 10h push 0A000h  ;point to graphic memory segment pop es mov byte ptr es:[320*100+100], 28h  ;draw bright red pixel   mov ah, 0  ;wait for keystroke int 16h mov ax, 0003h  ;restore normal text mode screen int 10h ret  ;return to OS end start  
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h>   /* x, y: coordinates of current point; dx, dy: direction of movement. * Think turtle graphics. They are divided by scale, so as to keep * very small coords/increments without losing precission. clen is * the path length travelled, which should equal to scale at the end * of the curve. */ long long x, y, dx, dy, scale, clen; typedef struct { double r, g, b; } rgb; rgb ** pix;   /* for every depth increase, rotate 45 degrees and scale up by sqrt(2) * Note how coords can still be represented by integers. */ void sc_up() { long long tmp = dx - dy; dy = dx + dy; dx = tmp; scale *= 2; x *= 2; y *= 2; }   /* Hue changes from 0 to 360 degrees over entire length of path; Value * oscillates along the path to give some contrast between segments * close to each other spatially. RGB derived from HSV gets *added* * to each pixel reached; they'll be dealt with later. */ void h_rgb(long long x, long long y) { rgb *p = &pix[y][x];   # define SAT 1 double h = 6.0 * clen / scale; double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1));   switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } }   /* string rewriting. No need to keep the string itself, just execute * its instruction recursively. */ void iter_string(const char * str, int d) { long tmp; # define LEFT tmp = -dy; dy = dx; dx = tmp # define RIGHT tmp = dy; dy = -dx; dx = tmp while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("X+YF+", d - 1); continue; case 'Y': if (d) iter_string("-FX-Y", d - 1); continue; case '+': RIGHT; continue; case '-': LEFT; continue; case 'F': /* draw: increment path length; add color; move. Here * is why the code does not allow user to choose arbitrary * image size: if it's not a power of two, aliasing will * occur and grid-like bright or dark lines will result * when normalized later. It can be gotten rid of, but that * involves computing multiplicative order and would be a huge * bore. */ clen ++; h_rgb(x/scale, y/scale); x += dx; y += dy; continue; } } }   void dragon(long leng, int depth) { long i, d = leng / 3 + 1; long h = leng + 3, w = leng + d * 3 / 2 + 2;   /* allocate pixel buffer */ rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h);   /* init coords; scale up to desired; exec string */ x = y = d; dx = leng; dy = 0; scale = 1; clen = 0; for (i = 0; i < depth; i++) sc_up(); iter_string("FX", depth);   /* write color PNM file */ unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf;   /* find highest value among pixels; normalize image according * to it. Highest value would be at points most travelled, so * this ends up giving curve edge a nice fade -- it's more apparaent * if we increase iteration depth by one or two. */ for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv;   printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); /* printf and fwrite may treat buffer differently */ fwrite(fpix, h * w * 3, 1, stdout); }   int main(int c, char ** v) { int size, depth;   depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth;   fprintf(stderr, "size: %d depth: %d\n", size, depth); dragon(size, depth * 2);   return 0; }
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
#Factor
Factor
USING: classes.struct kernel raylib.ffi ;   640 480 "sphere" 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 20 20 LIME draw-sphere-wires end-mode-3d end-drawing ] until drop close-window
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
#zkl
zkl
class Node{ fcn init(_value,_prev=Void,_next=Void) { var value=_value, prev=_prev, next=_next; } fcn toString{ value.toString() } fcn append(value){ b,c := Node(value,self,next),next; next=b; if(c) c.prev=b; b } }
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
#Forth
Forth
  HEX 8379 CONSTANT TICKER \ address of 1/60 second counter   CREATE PDT ( -- addr) \ bit pattern descriptors for 0..9 and colon 0038 , 444C , 5464 , 4438 , ( 0) 0010 , 3010 , 1010 , 1038 , ( 1) 0038 , 4404 , 1820 , 407C , ( 2) 007C , 0810 , 0804 , 4438 , ( 3) 0008 , 1828 , 487C , 0808 , ( 4) 007C , 4078 , 0404 , 4438 , ( 5) 0038 , 4040 , 7844 , 4438 , ( 6) 007C , 0408 , 1020 , 2020 , ( 7) 0038 , 4444 , 3844 , 4438 , ( 8) 0038 , 4444 , 3C04 , 0438 , ( 9) 0000 , 3030 , 0030 , 3000 , ( :)   : ]PDT ( 0..9 -- addr) [CHAR] 0 - 8 * PDT + ;   : BIG.TYPE ( caddr len -- ) 8 0 DO CR 2DUP BOUNDS  ?DO I C@ ]PDT J + C@ \ PDT char, byte# J 2 7 DO \ from bit# 7 to 2 DUP 1 I LSHIFT AND \ mask out each bit IF [char] * EMIT \ if true emit a character ELSE SPACE \ else print space THEN -1 +LOOP DROP LOOP LOOP 2DROP ;   DECIMAL   CREATE SECONDS 0 , 0 , \ 2 CELLS, holds a double integer   : SECONDS++ ( -- ) SECONDS 2@ 1 M+ SECONDS 2! ;   \ subtract old value from new value until ticker changes. : 1/60 ( -- ) TICKER DUP @ ( -- addr value) BEGIN PAUSE \ *Gives time to other Forth processes while we wait OVER @ \ read ticker addr OVER - \ subtract from old value UNTIL 2DROP ;   : SEXTAL ( -- ) 6 BASE ! ; : 1SEC ( -- ) 60 0 DO 1/60 LOOP SECONDS++  ; : ##: ( -- ) # SEXTAL # DECIMAL [CHAR] : HOLD  ; : .TIME ( d --) <# ##: ##: # # #> BIG.TYPE ;   : CLOCK ( -- ) DECIMAL \ set task's local radix BEGIN 1SEC 0 0 AT-XY SECONDS 2@ .TIME  ?TERMINAL UNTIL 2DROP ;
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
#Raku
Raku
say $dll.list; say $dll.reverse;
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
#REXX
REXX
/*REXX program that implements various List Manager functions. */ /*┌────────────────────────────────────────────────────────────────────┐ ┌─┘ Functions of the List Manager └─┐ │ │ │ @init ─── initializes the List. │ │ │ │ @size ─── returns the size of the List [could be 0 (zero)]. │ │ │ │ @show ─── shows (displays) the complete List. │ │ @show k,1 ─── shows (displays) the Kth item. │ │ @show k,m ─── shows (displays) M items, starting with Kth item. │ │ @show ,,─1 ─── shows (displays) the complete List backwards. │ │ │ │ @get k ─── returns the Kth item. │ │ @get k,m ─── returns the M items starting with the Kth item. │ │ │ │ @put x ─── adds the X items to the end (tail) of the List. │ │ @put x,0 ─── adds the X items to the start (head) of the List. │ │ @put x,k ─── adds the X items to before of the Kth item. │ │ │ │ @del k ─── deletes the item K. │ │ @del k,m ─── deletes the M items starting with item K. │ └─┐ ┌─┘ └────────────────────────────────────────────────────────────────────┘*/ call sy 'initializing the list.'  ; call @init call sy 'building list: Was it a cat I saw'; call @put 'Was it a cat I saw' call sy 'displaying list size.'  ; say 'list size='@size() call sy 'forward list'  ; call @show call sy 'backward list'  ; call @show ,,-1 call sy 'showing 4th item'  ; call @show 4,1 call sy 'showing 6th & 6th items'  ; call @show 5,2 call sy 'adding item before item 4: black' ; call @put 'black',4 call sy 'showing list'  ; call @show call sy 'adding to tail: there, in the ...'; call @put 'there, in the shadows, stalking its prey (and next meal).' call sy 'showing list'  ; call @show call sy 'adding to head: Oy!'  ; call @put 'Oy!',0 call sy 'showing list'  ; call @show exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────subroutines─────────────────────────*/ p: return word(arg(1),1) sy: say; say left('',30) "───" arg(1) '───'; return @hasopt: arg o; return pos(o,opt)\==0 @size: return $.# @init: $.@=''; $.#=0; return 0 @adjust: $.@=space($.@); $.#=words($.@); return 0   @parms: arg opt if @hasopt('k') then k=min($.#+1,max(1,p(k 1))) if @hasopt('m') then m=p(m 1) if @hasopt('d') then dir=p(dir 1) return   @show: procedure expose $.; parse arg k,m,dir if dir==-1 & k=='' then k=$.# m=p(m $.#); call @parms 'kmd' say @get(k,m,dir); return 0   @get: procedure expose $.; arg k,m,dir,_ call @parms 'kmd' do j=k for m by dir while j>0 & j<=$.# _=_ subword($.@,j,1) end /*j*/ return strip(_)   @put: procedure expose $.; parse arg x,k k=p(k $.#+1) call @parms 'k' $.@=subword($.@,1,max(0,k-1)) x subword($.@,k) call @adjust return 0   @del: procedure expose $.; arg k,m call @parms 'km' _=subword($.@,k,k-1) subword($.@,k+m) $.@=_ call @adjust return
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
#Sidef
Sidef
var node = Hash.new( data => 'say what', next => foo_node, prev => bar_node, );   node{:next} = quux_node; # mutable
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
#Swift
Swift
typealias NodePtr<T> = UnsafeMutablePointer<Node<T>>   class Node<T> { var value: T fileprivate var prev: NodePtr<T>? fileprivate var next: NodePtr<T>?   init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) { self.value = value self.prev = prev self.next = next } }  
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections 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
#Tcl
Tcl
oo::class create List { variable content next prev constructor {value {list ""}} { set content $value set next $list set prev "" if {$next ne ""} { $next previous [self] } } method value args { set content {*}$args } method next args { set next {*}$args } method previous args { set prev {*}$args } }
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)
#M2000_Interpreter
M2000 Interpreter
  Report "Dutch Flag from Dijkstra" const center=2 enum balls {Red, White, Blue} fillarray=lambda a=(Red, White, Blue) (size as long=10)-> { if size<1 then size=1 randomitem=lambda a->a#val(random(0,2)) dim a(size)<<randomitem() =a() } Display$=lambda$ (s as array) ->{ Document r$=eval$(array(s)) if len(s)>1 then For i=1 to len(s)-1 { r$=", "+eval$(array(s,i)) } end if =r$ } TestSort$=lambda$ (s as array)-> { ="unsorted: " x=array(s) for i=1 to len(s)-1 { k=array(s,i) if x>k then break swap x, k } ="sorted: " } Positions=lambda mid=White (a as array) ->{ m=len(a) dim Base 0, b(m)=-1 low=-1 high=m m-- i=0 medpos=stack link a to a() for i=m to 0 { if a(i)<=mid then exit high-- b(high)=high } for i=0 to m { if a(i)>=mid then exit low++ b(low)=low } if high-low>1 then for i=low+1 to high-1 { select case a(i)<=>Mid case -1 low++ : b(low)=i case 1 { high-- :b(high)=i if High<i then swap b(high), b(i) } else case stack medpos {data i} end select } end if if Len(medpos)>0 then dim c() c()=array(medpos) stock c(0) keep len(c()), b(low+1) for i=low+1 to high-1 if b(i)>low and b(i)<high and b(i)<>i then swap b(b(i)), b(i) next i end if if low>0 then for i=0 to low if b(i)<=low and b(i)<>i then swap b(b(i)), b(i) next end if if High<m then for i=m to High if b(i)>=High and b(i)<>i then swap b(b(i)), b(i) next end if =b() } InPlace=Lambda (&p(), &Final()) ->{ def i=0, j=-1, k=-1, many=0 for i=0 to len(p())-1 if p(i)<>i then j=i z=final(j) do final(j)=final(p(j)) k=j j=p(j) p(k)=k many++ until j=i final(k)=z end if next =many }     Dim final(), p(), second(), p1() Rem final()=(White,Red,Blue,White,Red, Red, Blue) Rem final()=(white, blue, red, blue, white)   final()=fillarray(30) Print "Items: ";len(final()) Report TestSort$(final())+Display$(final()) \\ backup for final() for second example second()=final() p()=positions(final()) \\ backup p() to p1() for second example p1()=p()     Report Center, "InPlace" rem Print p() ' show array items many=InPlace(&p(), &final()) rem print p() ' show array items Report TestSort$(final())+Display$(final()) print "changes: "; many     Report Center, "Using another array to make the changes" final()=second() \\ using a second array to place only the changes item=each(p1()) many=0 While item { if item^=array(item) else final(item^)=second(array(item)) : many++ } Report TestSort$(final())+Display$(final()) print "changes: "; many Module three_way_partition (A as array, mid as balls, &swaps) { Def i, j, k k=Len(A) Link A to A() While j < k if A(j) < mid Then Swap A(i), A(j) swaps++ i++ j++ Else.if A(j) > mid Then k-- Swap A(j), A(k) swaps++ Else j++ End if End While } Many=0 Z=second() Print Report center, {Three Way Partition } Report TestSort$(Z)+Display$(Z) three_way_partition Z, White, &many Print Report TestSort$(Z)+Display$(Z) Print "changes: "; many    
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)
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
flagSort[data_List] := Sort[data, (#1 === RED || #2 === BLUE) &]
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
#Julia
Julia
_pr(t::Dict, x::Int, y::Int, z::Int) = join((rstrip(join(t[(n, m)] for n in range(0, 3+x+z))) for m in reverse(range(0, 3+y+z))), "\n")   function cuboid(x::Int, y::Int, z::Int) t = Dict((n, m) => " " for n in range(0, 3 + x + z), m in range(0, 3 + y + z)) xrow = vcat("+", collect("$(i % 10)" for i in range(0, x)), "+") for (i, ch) in enumerate(xrow) t[(i, 0)] = t[(i, 1+y)] = t[(1+z+i, 2+y+z)] = ch end yrow = vcat("+", collect("$(j % 10)" for j in range(0, y)), "+") for (j, ch) in enumerate(yrow) t[(0, j)] = t[(x+1, j)] = t[(2+x+z, 1+z+j)] = ch end zdep = vcat("+", collect("$(k % 10)" for k in range(0, y)), "+") for (k, ch) in enumerate(xrow) t[(k, 1+y+k)] = t[(1+x+k, 1+y+k)] = t[(1+x+k, k)] = ch end   return _pr(t, x, y, z) end   for (x, y, z) in [(2, 3, 4), (3, 4, 2), (4, 2, 3), (5, 5, 6)] println("\nCUBOID($x, $y, $z)\n") println(cuboid(x, y, z)) 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
#XPL0
XPL0
[SetFB(320, 240, 24); Point(100, 100, $FF0000)]
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
#Yabasic
Yabasic
open window 320, 240 color 255, 0, 0 dot 100, 100
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms;   public class DragonCurve : Form { private List<int> turns; private double startingAngle, side;   public DragonCurve(int iter) { Size = new Size(800, 600); StartPosition = FormStartPosition.CenterScreen; DoubleBuffered = true; BackColor = Color.White;   startingAngle = -iter * (Math.PI / 4); side = 400 / Math.Pow(2, iter / 2.0);   turns = getSequence(iter); }   private List<int> getSequence(int iter) { var turnSequence = new List<int>(); for (int i = 0; i < iter; i++) { var copy = new List<int>(turnSequence); copy.Reverse(); turnSequence.Add(1); foreach (int turn in copy) { turnSequence.Add(-turn); } } return turnSequence; }   protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;   double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int)(Math.Cos(angle) * side); int y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; foreach (int turn in turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int)(Math.Cos(angle) * side); y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; } }   [STAThread] static void Main() { Application.Run(new DragonCurve(14)); } }
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
#Forth
Forth
: 3dup 2 pick 2 pick 2 pick ;   : sqrt ( u -- sqrt ) ( Babylonian method ) dup 2/ ( first square root guess is half ) dup 0= if drop exit then ( sqrt[0]=0, sqrt[1]=1 ) begin dup >r 2dup / r> + 2/ ( stack: square old-guess new-guess ) 2dup > while ( as long as guess is decreasing ) nip repeat ( forget old-guess and repeat ) drop nip ;   : normalize ( x1 y1 z1 -- x1' y1' z1' ) ( normalise down to 1000 ) 3dup dup * rot dup * rot dup * + + sqrt 1000 / >r ( length ) r@ / rot r@ / rot r> / rot ;   : r2-y2-x2 ( x y r -- z2 ) dup * swap dup * - swap dup * - ;   : shade ( u -- c ) C" @#&eo%*!:. " + c@ ;   : map-to-shade ( u -- u ) 0 shade * 1000 / 1 max 0 shade min ;   : dot-light ( x y z -- i ) ( hard coded light vector z, y, x ) -770 * rot 461 * rot 461 * + + 0 min 1000 / ;   : intensity ( x y z -- u ) dot-light dup * 1000 / map-to-shade ;   : pixel ( x y r -- c ) 3dup r2-y2-x2 dup 0> if ( if in disk ) sqrt nip normalize intensity shade ( z=sqrt[r2-x2-y2] ) else 2drop 2drop bl ( else blank ) then ;   : draw ( r -- ) ( r x1000 ) 1000 * dup dup negate do cr dup dup negate do dup I 500 + J 500 + rot pixel emit 500 +loop 1000 +loop drop ;   20 draw 10 draw
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
#Fortran
Fortran
  !Digital Text implemented as in C version - Anant Dixit (Oct, 2014) program clock implicit none integer :: t(8) do call date_and_time(values=t) call sleep(1) call system('clear') call digital_display(t(5),t(6),t(7)) end do end program   subroutine digital_display(H,M,S) !arguments integer :: H, M, S !local character(len=*), parameter :: nfmt='(A8)', cfmt='(A6)' character(len=88), parameter :: d1 = ' 00000 1 22222 33333 4 5555555 66666 7777777 88888 99999 ' character(len=88), parameter :: d2 = '0 0 11 2 2 3 3 44 5 6 6 7 7 8 8 9 9  :: ' character(len=88), parameter :: d3 = '0 00 1 1 2 3 4 4 5 6 7 8 8 9 9  :: ' character(len=88), parameter :: d4 = '0 0 0 1 2 3 4 4 5 6 7 8 8 9 9  :: ' character(len=88), parameter :: d5 = '0 0 0 1 2 333 4444444 555555 666666 7 88888 999999 ' character(len=88), parameter :: d6 = '0 0 0 1 2 3 4 5 6 6 7 8 8 9  :: ' character(len=88), parameter :: d7 = '00 0 1 2 3 4 5 6 6 7 8 8 9  :: ' character(len=88), parameter :: d8 = '0 0 1 2 3 3 4 5 5 6 6 7 8 8 9 9  :: ' character(len=88), parameter :: d9 = ' 00000 1111111 2222222 33333 4 55555 66666 7 88888 99999 ' integer :: h1, h2, m1, m2, s1, s2 h1 = 1+8*floor(dble(H)/10.D0) h2 = 1+8*modulo(H,10) m1 = 1+8*floor(dble(M)/10.D0) m2 = 1+8*modulo(M,10) s1 = 1+8*floor(dble(S)/10.D0) s2 = 1+8*modulo(S,10)   write(*,nfmt,advance='no') d1(h1:h1+8) write(*,nfmt,advance='no') d1(h2:h2+8) write(*,cfmt,advance='no') d1(81:88) write(*,nfmt,advance='no') d1(m1:m1+8) write(*,nfmt,advance='no') d1(m2:m2+8) write(*,cfmt,advance='no') d1(81:88) write(*,nfmt,advance='no') d1(s1:s1+8) write(*,nfmt) d1(s2:s2+8)   write(*,nfmt,advance='no') d2(h1:h1+8) write(*,nfmt,advance='no') d2(h2:h2+8) write(*,cfmt,advance='no') d2(81:88) write(*,nfmt,advance='no') d2(m1:m1+8) write(*,nfmt,advance='no') d2(m2:m2+8) write(*,cfmt,advance='no') d2(81:88) write(*,nfmt,advance='no') d2(s1:s1+8) write(*,nfmt) d2(s2:s2+8)   write(*,nfmt,advance='no') d3(h1:h1+8) write(*,nfmt,advance='no') d3(h2:h2+8) write(*,cfmt,advance='no') d3(81:88) write(*,nfmt,advance='no') d3(m1:m1+8) write(*,nfmt,advance='no') d3(m2:m2+8) write(*,cfmt,advance='no') d3(81:88) write(*,nfmt,advance='no') d3(s1:s1+8) write(*,nfmt) d3(s2:s2+8)   write(*,nfmt,advance='no') d4(h1:h1+8) write(*,nfmt,advance='no') d4(h2:h2+8) write(*,cfmt,advance='no') d4(81:88) write(*,nfmt,advance='no') d4(m1:m1+8) write(*,nfmt,advance='no') d4(m2:m2+8) write(*,cfmt,advance='no') d4(81:88) write(*,nfmt,advance='no') d4(s1:s1+8) write(*,nfmt) d4(s2:s2+8)   write(*,nfmt,advance='no') d5(h1:h1+8) write(*,nfmt,advance='no') d5(h2:h2+8) write(*,cfmt,advance='no') d5(81:88) write(*,nfmt,advance='no') d5(m1:m1+8) write(*,nfmt,advance='no') d5(m2:m2+8) write(*,cfmt,advance='no') d5(81:88) write(*,nfmt,advance='no') d5(s1:s1+8) write(*,nfmt) d5(s2:s2+8)   write(*,nfmt,advance='no') d6(h1:h1+8) write(*,nfmt,advance='no') d6(h2:h2+8) write(*,cfmt,advance='no') d6(81:88) write(*,nfmt,advance='no') d6(m1:m1+8) write(*,nfmt,advance='no') d6(m2:m2+8) write(*,cfmt,advance='no') d6(81:88) write(*,nfmt,advance='no') d6(s1:s1+8) write(*,nfmt) d6(s2:s2+8)   write(*,nfmt,advance='no') d7(h1:h1+8) write(*,nfmt,advance='no') d7(h2:h2+8) write(*,cfmt,advance='no') d7(81:88) write(*,nfmt,advance='no') d7(m1:m1+8) write(*,nfmt,advance='no') d7(m2:m2+8) write(*,cfmt,advance='no') d7(81:88) write(*,nfmt,advance='no') d7(s1:s1+8) write(*,nfmt) d7(s2:s2+8)   write(*,nfmt,advance='no') d8(h1:h1+8) write(*,nfmt,advance='no') d8(h2:h2+8) write(*,cfmt,advance='no') d8(81:88) write(*,nfmt,advance='no') d8(m1:m1+8) write(*,nfmt,advance='no') d8(m2:m2+8) write(*,cfmt,advance='no') d8(81:88) write(*,nfmt,advance='no') d8(s1:s1+8) write(*,nfmt) d8(s2:s2+8)   write(*,nfmt,advance='no') d9(h1:h1+8) write(*,nfmt,advance='no') d9(h2:h2+8) write(*,cfmt,advance='no') d9(81:88) write(*,nfmt,advance='no') d9(m1:m1+8) write(*,nfmt,advance='no') d9(m2:m2+8) write(*,cfmt,advance='no') d9(81:88) write(*,nfmt,advance='no') d9(s1:s1+8) write(*,nfmt) d9(s2:s2+8)   end subroutine  
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
#Ring
Ring
  # Project : Doubly-linked list/Traversal   trav = [123, 789, 456] travfor = sort(trav) see "Traverse forwards:" + nl see travfor see nl travback = reverse(travfor) see "Traverse backwards:" + nl see travback see nl  
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
#Ruby
Ruby
class DListNode def get_tail # parent class (ListNode) includes Enumerable, so the find method is available to us self.find {|node| node.succ.nil?} end   def each_previous(&b) yield self self.prev.each_previous(&b) if self.prev end end   head = DListNode.from_array([:a, :b, :c]) head.each {|node| p node.value} head.get_tail.each_previous {|node| p node.value}
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
#Visual_Basic_.NET
Visual Basic .NET
Public Class Node(Of T) Public Value As T Public [Next] As Node(Of T) Public Previous As Node(Of T) End Class
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
#Wren
Wren
import "/llist" for DNode   var dn1 = DNode.new(1) var dn2 = DNode.new(2) dn1.next = dn2 dn1.prev = null dn2.prev = dn1 dn2.next = null System.print(["node 1", "data = %(dn1.data)", "prev = %(dn1.prev)", "next = %(dn1.next)"]) System.print(["node 2", "data = %(dn2.data)", "prev = %(dn2.prev)", "next = %(dn2.next)"])
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections 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
#zkl
zkl
class Node{ fcn init(_value,_prev=Void,_next=Void) { var value=_value, prev=_prev, next=_next; } fcn toString{ value.toString() } }
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)
#Nim
Nim
import os, random, strutils   type Color {.pure.} = enum Red = "R", White = "W", Blue = "B"   #---------------------------------------------------------------------------------------------------   proc isSorted(a: openArray[Color]): bool = # Check if an array of colors is in the order of the dutch national flag. var prevColor = Red for color in a: if color < prevColor: return false prevColor = color return true   #---------------------------------------------------------------------------------------------------   proc threeWayPartition(a: var openArray[Color]; mid: Color) = ## Dijkstra way to sort the colors. var i, j = 0 var k = a.high while j <= k: if a[j] < mid: swap a[i], a[j] inc i inc j elif a[j] > mid: swap a[j], a[k] dec k else: inc j   #———————————————————————————————————————————————————————————————————————————————————————————————————   var n: Positive = 10   # Get the number of colors. if paramCount() > 0: try: n = paramStr(1).parseInt() if n <= 1: raise newException(ValueError, "") except ValueError: echo "Wrong number of colors" quit(QuitFailure)   # Create the colors. randomize() var colors = newSeqOfCap[Color](n)   while true: for i in 0..<n: colors.add(Color(rand(ord(Color.high)))) if not colors.isSorted(): break colors.setLen(0) # Reset for next try.   echo "Original: ", colors.join("")   # Sort the colors. var sortedColors = colors threeWayPartition(sortedColors, White) doAssert sortedColors.isSorted() echo "Sorted: ", sortedColors.join("")
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)
#PARI.2FGP
PARI/GP
compare(a,b)={ if (a==b, 0 , if(a=="red" || b=="blue", -1, 1) ) }; r(n)=vector(n,i,if(random(3),if(random(2),"red","white"),"blue")); inorder(v)=for(i=2,#v,if(compare(v[i-1],v[i])>0,return(0)));1;   v=r(10); while(inorder(v), v=r(10)); v=vecsort(v,compare); inorder(v)
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
#Kotlin
Kotlin
// version 1.1   import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.*   class Cuboid: JPanel() { private val nodes = arrayOf( doubleArrayOf(-1.0, -1.0, -1.0), doubleArrayOf(-1.0, -1.0, 1.0), doubleArrayOf(-1.0, 1.0, -1.0), doubleArrayOf(-1.0, 1.0, 1.0), doubleArrayOf( 1.0, -1.0, -1.0), doubleArrayOf( 1.0, -1.0, 1.0), doubleArrayOf( 1.0, 1.0, -1.0), doubleArrayOf( 1.0, 1.0, 1.0) ) private val edges = arrayOf( intArrayOf(0, 1), intArrayOf(1, 3), intArrayOf(3, 2), intArrayOf(2, 0), intArrayOf(4, 5), intArrayOf(5, 7), intArrayOf(7, 6), intArrayOf(6, 4), intArrayOf(0, 4), intArrayOf(1, 5), intArrayOf(2, 6), intArrayOf(3, 7) )   private var mouseX: Int = 0 private var prevMouseX: Int = 0 private var mouseY: Int = 0 private var prevMouseY: Int = 0   init { preferredSize = Dimension(640, 640) background = Color.white scale(80.0, 120.0, 160.0) rotateCube(Math.PI / 5.0, Math.PI / 9.0) addMouseListener(object: MouseAdapter() { override fun mousePressed(e: MouseEvent) { mouseX = e.x mouseY = e.y } })   addMouseMotionListener(object: MouseAdapter() { override fun mouseDragged(e: MouseEvent) { prevMouseX = mouseX prevMouseY = mouseY mouseX = e.x mouseY = e.y val incrX = (mouseX - prevMouseX) * 0.01 val incrY = (mouseY - prevMouseY) * 0.01 rotateCube(incrX, incrY) repaint() } }) }   private fun scale(sx: Double, sy: Double, sz: Double) { for (node in nodes) { node[0] *= sx node[1] *= sy node[2] *= sz } }   private fun rotateCube(angleX: Double, angleY: Double) { val sinX = Math.sin(angleX) val cosX = Math.cos(angleX) val sinY = Math.sin(angleY) val cosY = Math.cos(angleY) for (node in nodes) { val x = node[0] val y = node[1] var z = node[2] node[0] = x * cosX - z * sinX node[2] = z * cosX + x * sinX z = node[2] node[1] = y * cosY - z * sinY node[2] = z * cosY + y * sinY } }   private fun drawCube(g: Graphics2D) { g.translate(width / 2, height / 2) for (edge in edges) { val xy1 = nodes[edge[0]] val xy2 = nodes[edge[1]] g.drawLine(Math.round(xy1[0]).toInt(), Math.round(xy1[1]).toInt(), Math.round(xy2[0]).toInt(), Math.round(xy2[1]).toInt()) } for (node in nodes) { g.fillOval(Math.round(node[0]).toInt() - 4, Math.round(node[1]).toInt() - 4, 8, 8) } }   override public fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.color = Color.blue drawCube(g) } }   fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE f.title = "Cuboid" f.isResizable = false f.add(Cuboid(), BorderLayout.CENTER) f.pack() f.setLocationRelativeTo(null) f.isVisible = true } }
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
#ZX_Spectrum_Basic
ZX Spectrum Basic
PLOT INK 2;100,100
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.
#C.2B.2B
C++
  #include <windows.h> #include <iostream>   //----------------------------------------------------------------------------------------- using namespace std;   //----------------------------------------------------------------------------------------- const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;   //----------------------------------------------------------------------------------------- class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); }   bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;   hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc );   width = w; height = h; return true; }   void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); }   void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); }   void setPenColor( DWORD c ) { clr = c; createPen(); }   void setPenWidth( int w ) { wid = w; createPen(); }   void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;   GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];   ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; }   HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; }   private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); }   HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; //----------------------------------------------------------------------------------------- class dragonC { public: dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; } void draw( int iterations ) { generate( iterations ); draw(); }   private: void generate( int it ) { generator.push_back( 1 ); string temp;   for( int y = 0; y < it - 1; y++ ) { temp = generator; temp.push_back( 1 ); for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ ) temp.push_back( !( *x ) );   generator = temp; } }   void draw() { HDC dc = bmp.getDC(); unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff }; int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;   for( int t = 0; t < 4; t++ ) { int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++]; MoveToEx( dc, a, b, NULL );   bmp.setPenColor( clr[t] ); for( string::iterator x = generator.begin(); x < generator.end(); x++ ) { switch( dir ) { case NORTH: if( *x ) { a += LEN; dir = EAST; } else { a -= LEN; dir = WEST; } break; case EAST: if( *x ) { b += LEN; dir = SOUTH; } else { b -= LEN; dir = NORTH; } break; case SOUTH: if( *x ) { a -= LEN; dir = WEST; } else { a += LEN; dir = EAST; } break; case WEST: if( *x ) { b -= LEN; dir = NORTH; } else { b += LEN; dir = SOUTH; } } LineTo( dc, a, b ); } } // !!! change this path !!! bmp.saveBitmap( "f:/rc/dragonCpp.bmp" ); }   int dir; myBitmap bmp; string generator; }; //----------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { dragonC d; d.draw( 17 ); return system( "pause" ); } //-----------------------------------------------------------------------------------------  
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
#Frink
Frink
res = 254 / in v = callJava["frink.graphics.VoxelArray", "makeSphere", [1/2 inch res]]   v.projectX[undef].show["X"] v.projectY[undef].show["Y"] v.projectZ[undef].show["Z"]   filename = "sphere.stl" print["Writing $filename..."] w = new Writer[filename] w.println[v.toSTLFormat["sphere", 1/(res mm)]] w.close[] println["done."]
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
#FreeBASIC
FreeBASIC
' version 05-04-2017 ' compile with: fbc -s gui   Const As Double deg2rad = Atn(1) / 45 Const As UInteger w = 199, h = 199 Const As UInteger x0 = w \ 2, y0 = h \ 2 ' center   Dim As UInteger x, x1, x2, x3, y, y1, y2, y3 Dim As String sys_time, press Dim As Integer hours, minutes, seconds Dim As Double angle, a_sin, a_cos   ScreenRes w, h, 8 ' 8bit color depth (palette) WindowTitle "Simple Clock"   ' create image 8bit (palette) and set pixels to 15 (white) Dim clockdial As Any Ptr = ImageCreate(w, h, 15, 8)   If clockdial = 0 Then Print "Failed to create image." Sleep End -1 End If   ' draw clockdial in memory Circle clockdial, (x0, y0), 94 ,0 Circle clockdial, (x0, y0), 90 ,0   For x = 0 To 174 Step 6 a_sin = Sin(x * deg2rad) a_cos = Cos(x * deg2rad)   x1 = 94 * a_sin : y1 = 94 * a_cos If x Mod 30 = 0 Then x2 = 85 * a_sin : y2 = 85 * a_cos Else x2 = 90 * a_sin : y2 = 90 * a_cos End If   Line clockdial, (x0 + x1, y0 + y1) - (x0 + x2, y0 + y2), 0 Line clockdial, (x0 - x1, y0 - y1) - (x0 - x2, y0 - y2), 0 Next   'draw clock Do sys_time = Time hours = (sys_time[0] - Asc("0")) * 10 + sys_time[1] - Asc("0") minutes = (sys_time[3] - Asc("0")) * 10 + sys_time[4] - Asc("0") seconds = (sys_time[6] - Asc("0")) * 10 + sys_time[7] - Asc("0")   If hours > 12 Then hours -= 12   angle = (180 - (hours * 30 + minutes / 2)) * deg2rad x1 = 65 * Sin(angle) y1 = 65 * Cos(angle)   angle = (180 - (minutes * 6 + seconds / 10)) * deg2rad x2 = 80 * Sin(angle) y2 = 80 * Cos(angle)   angle = (180 - seconds * 6) * deg2rad x3 = 90 * Sin(angle) y3 = 90 * Cos(angle)   ScreenLock ' load image, setting pixels Put (0, 0), clockdial, PSet Line (x0, y0) - (x0 + x1, y0 + y1), 1 ' hour hand blue Line (x0, y0) - (x0 + x2, y0 + y2), 2 ' minute hand green Line (x0, y0) - (x0 + x3, y0 + y3), 12 ' second hand red ScreenUnLock   Sleep 300, 1 ' wait 300 ms, don't respond to keys pressed   ' press esc or mouse click on close window to stop program press = InKey If press = Chr(27) Or press = Chr(255) + "k" Then Exit Do   Loop   ImageDestroy(clockdial)   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
#Salmon
Salmon
class item(init_data) { variable next, previous, data := init_data; };   function prepend(tail, new_data) { immutable result := item(new_data); result.next := tail; result.previous := null; if (tail != null) tail.previous := result;; return result; };   variable my_list := null; my_list := prepend(my_list, "R"); my_list := prepend(my_list, "o"); my_list := prepend(my_list, "s"); my_list := prepend(my_list, "e"); my_list := prepend(my_list, "t"); my_list := prepend(my_list, "t"); my_list := prepend(my_list, "a");   "Items in the list going forward:"! variable follow := my_list; while (true) { follow.data! if (follow.next == null) break;; } step follow := follow.next;;   "Items in the list going backward:"! while (follow != null) follow.data! step follow := follow.previous;;
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
#Scala
Scala
import java.util   object DoublyLinkedListTraversal extends App {   private val ll = new util.LinkedList[String]   private def traverse(iter: util.Iterator[String]) = while (iter.hasNext) iter.next   traverse(ll.iterator) traverse(ll.descendingIterator) }
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)
#Perl
Perl
use warnings; use strict; use 5.010; # //   use List::Util qw( shuffle );   my @colours = qw( blue white red );   sub are_ordered { my $balls = shift; my $last = 0; for my $ball (@$balls) { return if $ball < $last; $last = $ball; } return 1; }     sub show { my $balls = shift; print join(' ', map $colours[$_], @$balls), "\n"; }     sub debug { return unless $ENV{DEBUG};   my ($pos, $top, $bottom, $balls) = @_; for my $i (0 .. $#$balls) { my ($prefix, $suffix) = (q()) x 2;   ($prefix, $suffix) = qw/( )/ if $i == $pos; $prefix .= '>' if $i == $top; $suffix .= '<' if $i == $bottom;   print STDERR " $prefix$colours[$balls->[$i]]$suffix"; } print STDERR "\n"; }     my $count = shift // 10; die "$count: Not enough balls\n" if $count < 3;   my $balls = [qw( 2 1 0 )]; push @$balls, int rand 3 until @$balls == $count; do { @$balls = shuffle @$balls } while are_ordered($balls);   show($balls);   my $top = 0; my $bottom = $#$balls;   my $i = 0; while ($i <= $bottom) { debug($i, $top, $bottom, $balls); my $col = $colours[ $balls->[$i] ]; if ('red' eq $col and $i < $bottom) { @{$balls}[$bottom, $i] = @{$balls}[$i, $bottom]; $bottom--; } elsif ('blue' eq $col and $i > $top) { @{$balls}[$top, $i] = @{$balls}[$i, $top]; $top++; } else { $i++; } } debug($i, $top, $bottom, $balls);   show($balls); are_ordered($balls) or die "Incorrect\n";
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
#Liberty_BASIC
Liberty BASIC
  Call cuboid 1,3,4   End   Sub cuboid width, height, depth wd=width*7+2: hi=height*3: dp=depth For i=1 To wd-2 w$=w$+"-":h$=h$+" " Next w$="+"+w$+"+":d$="/"+h$+"/":h$="|"+h$+"|" px=dp+2:py=1:Locate dp+2,py:Print w$; For i=2 To hi+1 Locate wd+dp+1,i:Print"|"; Next Locate wd+dp+1, i: Print "+"; For i=dp+1 To 1 Step -1 py=py+1:Locate i,py:Print d$; Next For i=1 To dp Locate wd+(dp+1)-i,hi+d+2+i:Print "/"; Next Locate 1, dp+2: Print w$; For i=dp+3 To hi+dp+2 Locate 1,i:Print h$; Next Locate 1, dp+hi+3: Print w$ End Sub  
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.
#COBOL
COBOL
>>SOURCE FORMAT FREE *> This code is dedicated to the public domain identification division. program-id. dragon. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 segment-length pic 9 value 2. 01 mark pic x value '.'. 01 segment-count pic 9999 value 513.   01 segment pic 9999. 01 point pic 9999 value 1. 01 point-max pic 9999. 01 point-lim pic 9999 value 8192. 01 dragon-curve. 03 filler occurs 8192. 05 ydragon pic s9999. 05 xdragon pic s9999.   01 x pic s9999 value 1. 01 y pic S9999 value 1.   01 xdelta pic s9 value 1. *> start pointing east 01 ydelta pic s9 value 0.   01 x-max pic s9999 value -9999. 01 x-min pic s9999 value 9999. 01 y-max pic s9999 value -9999. 01 y-min pic s9999 value 9999.   01 n pic 9999. 01 r pic 9.   01 xupper pic s9999. 01 yupper pic s9999.   01 window-line-number pic 99. 01 window-width pic 99 value 64. 01 window-height pic 99 value 22. 01 window. 03 window-line occurs 22. 05 window-point occurs 64 pic x.   01 direction pic x.   procedure division. start-dragon.   if segment-count * segment-length > point-lim *> too many segments for the point-table compute segment-count = point-lim / segment-length end-if   perform varying segment from 1 by 1 until segment > segment-count   *>=========================================== *> segment = n * 2 ** b *> if mod(n,4) = 3, turn left else turn right *>===========================================   *> calculate the turn divide 2 into segment giving n remainder r perform until r <> 0 divide 2 into n giving n remainder r end-perform divide 2 into n giving n remainder r   *> perform the turn evaluate r also xdelta also ydelta when 0 also 1 also 0 *> turn right from east when 1 also -1 also 0 *> turn left from west *> turn to south move 0 to xdelta move 1 to ydelta when 1 also 1 also 0 *> turn left from east when 0 also -1 also 0 *> turn right from west *> turn to north move 0 to xdelta move -1 to ydelta when 0 also 0 also 1 *> turn right from south when 1 also 0 also -1 *> turn left from north *> turn to west move 0 to ydelta move -1 to xdelta when 1 also 0 also 1 *> turn left from south when 0 also 0 also -1 *> turn right from north *> turn to east move 0 to ydelta move 1 to xdelta end-evaluate   *> plot the segment points perform segment-length times add xdelta to x add ydelta to y   move x to xdragon(point) move y to ydragon(point)   add 1 to point end-perform   *> update the limits for the display compute x-max = max(x, x-max) compute x-min = min(x, x-min) compute y-max = max(y, y-max) compute y-min = min(y, y-min) move point to point-max   end-perform   *>========================================== *> display the curve *> hjkl corresponds to left, up, down, right *> anything else ends the program *>==========================================   move 1 to yupper xupper   perform with test after until direction <> 'h' and 'j' and 'k' and 'l'   *>========================================== *> (yupper,xupper) maps to window-point(1,1) *>==========================================   *> move the window evaluate true when direction = 'h' *> move window left and xupper > x-min + window-width subtract 1 from xupper when direction = 'j' *> move window up and yupper < y-max - window-height add 1 to yupper when direction = 'k' *> move window down and yupper > y-min + window-height subtract 1 from yupper when direction = 'l' *> move window right and xupper < x-max - window-width add 1 to xupper end-evaluate   *> plot the dragon points in the window move spaces to window perform varying point from 1 by 1 until point > point-max if ydragon(point) >= yupper and < yupper + window-height and xdragon(point) >= xupper and < xupper + window-width *> we're in the window compute y = ydragon(point) - yupper + 1 compute x = xdragon(point) - xupper + 1 move mark to window-point(y, x) end-if end-perform   *> display the window perform varying window-line-number from 1 by 1 until window-line-number > window-height display window-line(window-line-number) end-perform   *> get the next window move or terminate display 'hjkl?' with no advancing accept direction end-perform   stop run . end program dragon.
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
#FutureBasic
FutureBasic
  include "Tlbx agl.incl" include "Tlbx glut.incl"   output file "Rotating Sphere"   local fn SphereDraw '~'1 begin globals dim as double  sRotation // 'static' var end globals   // Speed of rotation sRotation += 2.9 glMatrixMode( _GLMODELVIEW )   glLoadIdentity()   // Position parameters: x axis, y axis, z axis // Set to center of screen: glTranslated( 0.0, 0.0, 0.0 )   // Rotation (wobble) parameters: angle, x, y glRotated( sRotation, -0.45, -0.8, -0.6 )   // Set color of sphere's wireframe glColor3d( 1.0, 0.0, 0.3 )   // Set width of sphere's wireframe lines glLineWidth( 1.5 )   // Apply above to GLUT's built-in sphere wireframe // Size & frame parameters: radius, slices, stack fn glutWireSphere( 0.8, 25, 25 )   end fn   // main program dim as GLint           attrib(2) dim as CGrafPtr        port dim as AGLPixelFormat  fmt dim as AGLContext      glContext dim as EventRecord     ev dim as GLboolean       yesOK   // Make a window window 1, @"Rotating Sphere", (0,0) - (500,500)   // Minimal setup of OpenGL attrib(0) = _AGLRGBA attrib(1) = _AGLDOUBLEBUFFER attrib(2) = _AGLNONE   fmt = fn aglChoosePixelFormat( 0, 0, attrib(0) ) glContext = fn aglCreateContext( fmt, 0 ) aglDestroyPixelFormat( fmt )   // Set the FB window as port for drawing port = window( _wndPort ) yesOK = fn aglSetDrawable( glContext, port ) yesOK = fn aglSetCurrentContext( glContext )   // Background color: red, green, blue, alpha glClearColor( 0.0, 0.0, 0.0, 0.0 )   // 60/s HandleEvents Trigger poke long event - 8, 1 do // Clear window glClear( _GLCOLORBUFFERBIT ) // Run animation fn SphereDraw aglSwapBuffers( glContext ) HandleEvents until gFBquit  
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
#FunL
FunL
import concurrent.{scheduleAtFixedRate, scheduler}   val ROW = 10 val COL = 20 val digits = array( [ " __", " / /", "/__/ ", " ", " /", " / ", " __", " __/", "/__ ", " __", " __/", " __/ ", " ", " /__/", " / ", " __", " /__ ", " __/ ", " __", " /__ ", "/__/ ", " __", " /", " / ", " __", " /__/", "/__/ ", " __", " /__/", " __/ " ] ) val colon = array( [ " ", " .", ". " ] )   def displayTime = def pad( n ) = if n < 10 then '0' + n else n   t = $time s = (t + $timeZoneOffset)\1000%86400 time = pad( s\3600 ) + ':' + pad( s%3600\60 ) + ':' + pad( s%60 )   for row <- 0:3 print( if $os.startsWith('Windows') then '\n' else '\u001B[' + (ROW + row) + ';' + COL + 'H' )   for ch <- time print( if ch == ':' then colon(row) else digits(int(ch)*3 + row) )   println() t   if not $os.startsWith( 'Windows' ) print( '\u001B[2J\u001B[?25l' )   scheduleAtFixedRate( displayTime, 1000 - displayTime()%1000, 1000 ) readLine() scheduler().shutdown()   if not $os.startsWith( 'Windows' ) print( '\u001B[?25h' )
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
#Tcl
Tcl
# Modify the List class to add the iterator methods oo::define List { method foreach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node next]} { set v [$node value] uplevel 1 $script } } method revforeach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node previous]} { set v [$node value] uplevel 1 $script } } }   # Demonstrating... set first [List new a [List new b [List new c [set last [List new d]]]]] puts "Forward..." $first foreach char { puts $char } puts "Backward..." $last revforeach char { puts $char }
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
#Wren
Wren
import "/llist" for DLinkedList import "/fmt" for Fmt   // create a new doubly-linked list and add the first 50 positive integers to it var dll = DLinkedList.new(1..50)   // traverse the doubly-linked list from head to tail for (i in dll) { Fmt.write("$4d ", i) if (i % 10 == 0) System.print() } System.print() // traverse the doubly-linked list from tail to head for (i in dll.reversed) { Fmt.write("$4d ", i) if (i % 10 == 1) System.print() }
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)
#Phix
Phix
with javascript_semantics function three_way_partition(sequence s, integer mid) integer i=1, j=1, n = length(s) while j <= n do if s[j] < mid then {s[i],s[j]} = {s[j],s[i]} i += 1 j += 1 elsif s[j] > mid then {s[j],s[n]} = {s[n],s[j]} n -= 1 else j += 1 end if end while return s end function constant colours = {"red","white","blue"} enum /*red,*/ white = 2, blue, maxc = blue procedure show(string msg, sequence s) sequence t = repeat(0,length(s)) for i=1 to length(s) do t[i] = colours[s[i]] end for printf(1,"%s: %s\n",{msg,join(t)}) end procedure sequence unsorted, sorted while 1 do unsorted = sq_rand(repeat(maxc,12)) -- sorted = sort(deep_copy(unsorted)) -- (works just as well) sorted = three_way_partition(deep_copy(unsorted), white) if unsorted!=sorted then exit end if ?"oops" end while show("Unsorted",unsorted) show("Sorted",sorted)
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
#Logo
Logo
to cuboid :l1 :l2 :l3 cs perspective ;making the room ready to use setxyz :l1 0 0 setxyz :l1 :l2 0 setxyz 0 :l2 0 setxyz 0 0 0 setxyz :l1 0 0 setxyz :l1 0 -:l3 setxyz :l1 :l2 -:l3 setxyz :l1 :l2 0 setxyz 0 :l2 0 setxyz 0 :l2 -:l3 setxyz :l1 :l2 -:l3 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.
#Commodore_BASIC
Commodore BASIC
  10 REM DRAGON CURVE 20 REM SIN, COS IN ARRAYS FOR PI/4 MULTIPL. 30 DIM S(7),C(7) 40 QPI=ATN(1) 50 FOR I=0 TO 7 60 S(I)=SIN(I*QPI) 70 C(I)=COS(I*QPI) 80 NEXT I 90 LEVEL=15 100 INSIZE=128:REM 2^WHOLE_NUM (LOOKS BETTER) 110 X=112 120 Y=70 130 SQ=SQR(2) 140 ROTQPI=0:ITER=0:RQ=1 150 DIM R(LEVEL) 160 GRAPHIC 2,1 170 GOSUB 190 180 END 190 REM DRAGON 200 IF ROTQPI<0 THEN ROTQPI=ROTQPI+8:GOTO 220 210 IF ROTQPI>7 THEN ROTQPI=ROTQPI-8 220 IF LEVEL>1 THEN GO TO 290 230 YN=S(ROTQPI)*INSIZE+Y 240 XN=C(ROTQPI)*INSIZE+X 250 DRAW ,X,Y TO XN,YN 260 ITER=ITER+1 270 X=XN:Y=YN 280 RETURN 290 INSIZE=INSIZE*SQ/2 300 ROTQPI=ROTQPI+RQ 310 IF ROTQPI<0 THEN ROTQPI=ROTQPI+8:GOTO 330 320 IF ROTQPI>7 THEN ROTQPI=ROTQPI-8 330 LEVEL=LEVEL-1 340 R(LEVEL)=RQ:RQ=1 350 GOSUB 190 360 ROTQPI=ROTQPI-R(LEVEL)*2 370 IF ROTQPI<0 THEN ROTQPI=ROTQPI+8:GOTO 390 380 IF ROTQPI>7 THEN ROTQPI=ROTQPI-8 390 RQ=-1 400 GOSUB 190 410 RQ=R(LEVEL) 420 ROTQPI=ROTQPI+RQ 430 IF ROTQPI<0 THEN ROTQPI=ROTQPI+8:GOTO 450 440 IF ROTQPI>7 THEN ROTQPI=ROTQPI-8 450 LEVEL=LEVEL+1 460 INSIZE=INSIZE*SQ 470 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
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/png" "math" "os" )   type vector [3]float64   func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen }   func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] }   func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img }   func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
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
#Go
Go
package main   import ( "golang.org/x/net/websocket" "flag" "fmt" "html/template" "io" "math" "net/http" "time" )   var ( Portnum string Hostsite string )   type PageSettings struct { Host string Port string }   const ( Canvaswidth = 512 Canvasheight = 512 //color constants HourColor = "#ff7373" // pinkish MinuteColor = "#00b7e4" //light blue SecondColor = "#b58900" //gold )   func main() { flag.StringVar(&Portnum, "Port", "1234", "Port to host server.") flag.StringVar(&Hostsite, "Site", "localhost", "Site hosting server") flag.Parse() http.HandleFunc("/", webhandler) http.Handle("/ws", websocket.Handler(wshandle)) err := http.ListenAndServe(Hostsite+":"+Portnum, nil) if err != nil { fmt.Println(err) } fmt.Println("server running") }   func webhandler(w http.ResponseWriter, r *http.Request) { wsurl := PageSettings{Host: Hostsite, Port: Portnum} template, _ := template.ParseFiles("clock.html") template.Execute(w, wsurl) }   //Given a websocket connection, //serves updating time function func wshandle(ws *websocket.Conn) { for { hour, min, sec := time.Now().Clock() hourx, houry := HourCords(hour, Canvasheight/2) minx, miny := MinSecCords(min, Canvasheight/2) secx, secy := MinSecCords(sec, Canvasheight/2) msg := "CLEAR\n" msg += fmt.Sprintf("HOUR %d %d %s\n", hourx, houry, HourColor) msg += fmt.Sprintf("MIN %d %d %s\n", minx, miny, MinuteColor) msg += fmt.Sprintf("SEC %d %d %s", secx, secy, SecondColor) io.WriteString(ws, msg) time.Sleep(time.Second / 60.0) } }   //Given current minute or second time(i.e 30 min, 60 minutes) //and the radius, returns pair of cords to draw line to func MinSecCords(ctime int, radius int) (int, int) { //converts min/sec to angle and then to radians   theta := ((float64(ctime)*6 - 90) * (math.Pi / 180)) x := float64(radius) * math.Cos(theta) y := float64(radius) * math.Sin(theta) return int(x) + 256, int(y) + 256 }   //Given current hour time(i.e. 12, 8) and the radius, //returns pair of cords to draw line to func HourCords(ctime int, radius int) (int, int) { //converts hours to angle and then to radians theta := ((float64(ctime)*30 - 90) * (math.Pi / 180)) x := float64(radius) * math.Cos(theta) y := float64(radius) * math.Sin(theta) return int(x) + 256, int(y) + 256 }
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
#zkl
zkl
class Node{ fcn init(_value,_prev=Void,_next=Void) { var value=_value, prev=_prev, next=_next; } fcn toString{ value.toString() } fcn append(value){ b,c := Node(value,self,next),next; next=b; if(c) c.prev=b; b } }
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national 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)
#Picat
Picat
go => _ = random2(), % random seed N = 21, Map = new_map([1=red,2=white,3=blue]), [Rand,Sorted] = dutch_random_sort(N,Map,Map.inverse()), println('rand '=Rand), println(sorted=Sorted), nl.   % generate a random order and ensure it's not already dutch sorted dutch_random_sort(N,Map,MapInv) = [Rand,Sorted] => Rand = dutch_random1(N,Map), Sorted = dutch_sort(Rand,MapInv), while (Rand == Sorted) println("Randomize again"), Rand := dutch_random1(N,Map), Sorted := dutch_sort(Rand,MapInv) end.   dutch_random1(N,Map) = [Map.get(1+(random() mod Map.map_to_list().length)) : _I in 1..N].   dutch_sort(L,MapInv) = [R : _=R in [MapInv.get(R)=R : R in L].sort()].   inverse(Map) = new_map([V=K : K=V in Map]).
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)
#PicoLisp
PicoLisp
(def 'Colors (list (def 'RED 1) (def 'WHITE 2) (def 'BLUE 3) ) )   (let (L (make (do 9 (link (get Colors (rand 1 3))))) S (by val sort L)) (prin "Original balls ") (print L) (prinl (unless (= L S) " not sorted")) (prin "Sorted balls ") (print S) (prinl " are sorted") )
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
#LSL
LSL
vector vSCALE = <2.0, 3.0, 4.0>; default { state_entry() { llSetScale(vSCALE); } }
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
#Lua
Lua
-- needed for actual task cube.scale = function(self, sx, sy, sz) for i,v in ipairs(self.verts) do v[1], v[2], v[3] = v[1]*sx, v[2]*sy, v[3]*sz end end -- only needed for output -- (to size it for screen, given a limited camera) cube.translate = function(self, tx, ty, tz) for i,v in ipairs(self.verts) do v[1], v[2], v[3] = v[1]+tx, v[2]+ty, v[3]+tz end 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.
#Common_Lisp
Common Lisp
(defpackage #:dragon (:use #:clim-lisp #:clim) (:export #:dragon #:dragon-part)) (in-package #:dragon)   (defun dragon-part (depth bend-direction) (if (zerop depth) (draw-line* *standard-output* 0 0 1 0) (with-scaling (t (/ (sqrt 2))) (with-rotation (t (* pi -1/4 bend-direction)) (dragon-part (1- depth) 1) (with-translation (t 1 0) (with-rotation (t (* pi 1/2 bend-direction)) (dragon-part (1- depth) -1)))))))   (defun dragon (&optional (depth 7) (size 100)) (with-room-for-graphics () (with-scaling (t size) (dragon-part depth 1))))
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
#Haskell
Haskell
import Graphics.Rendering.OpenGL.GL import Graphics.UI.GLUT.Objects import Graphics.UI.GLUT   setProjection :: IO () setProjection = do matrixMode $= Projection ortho (-1) 1 (-1) 1 0 (-1)   grey1,grey9,red,white :: Color4 GLfloat grey1 = Color4 0.1 0.1 0.1 1 grey9 = Color4 0.9 0.9 0.9 1 red = Color4 1 0 0 1 white = Color4 1 1 1 1   setLights :: IO () setLights = do let l = Light 0 ambient l $= grey1 diffuse l $= white specular l $= white position l $= Vertex4 (-4) 4 3 (0 :: GLfloat) light l $= Enabled lighting $= Enabled   setMaterial :: IO () setMaterial = do materialAmbient Front $= grey1 materialDiffuse Front $= red materialSpecular Front $= grey9 materialShininess Front $= (32 :: GLfloat)   display :: IO() display = do clear [ColorBuffer] renderObject Solid $ Sphere' 0.8 64 64 swapBuffers   main :: IO() main = do _ <- getArgsAndInitialize _ <- createWindow "Sphere" clearColor $= Color4 0.0 0.0 0.0 0.0 setProjection setLights setMaterial displayCallback $= display mainLoop
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
#GUISS
GUISS
Start,Programs,Accessories,Analogue Clock
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)
#PowerShell
PowerShell
  $Colors = 'red', 'white','blue'   # Select 10 random colors $RandomBalls = 1..10 | ForEach { $Colors | Get-Random }   # Ensure we aren't finished before we start. For some reason. It's in the task requirements. While ( $RandomBalls -eq $RandomBalls | Sort { $Colors.IndexOf( $_ ) } ) { $RandomBalls = 1..10 | ForEach { $Colors | Get-Random } }   # Sort the colors $SortedBalls = $RandomBalls | Sort { $Colors.IndexOf( $_ ) }   # Display the results $RandomBalls '' $SortedBalls