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/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)
#Prolog
Prolog
dutch_flag(N) :- length(L, N), repeat, maplist(init,L), \+is_dutch_flag(L) , writeln(L), test_sorted(L), sort_dutch_flag(L, TmpFlag), append(TmpFlag, Flag), writeln(Flag), test_sorted(Flag). Β  Β  sort_dutch_flag([], [[], [], []]). Β  sort_dutch_flag([blue | T], [R, W, [blue|B]]) :- sort_dutch_flag(T, [R, W, B]). Β  sort_dutch_flag([red | T], [[red|R], W, B]) :- sort_dutch_flag(T, [R, W, B]). Β  Β  sort_dutch_flag([white | T], [R, [white | W], B]) :- sort_dutch_flag(T, [R, W, B]). Β  Β  init(C) :- R is random(3), nth0(R, [blue, red, white], C). Β  Β  test_sorted(Flag) :- ( is_dutch_flag(Flag) -> write('it is a dutch flag') ; write('it is not a dutch flag')), nl,nl. Β  % First color must be red is_dutch_flag([red | T]) :- is_dutch_flag_red(T). Β  Β  is_dutch_flag_red([red|T]) :- is_dutch_flag_red(T); % second color must be white T = [white | T1], is_dutch_flag_white(T1). Β  Β  is_dutch_flag_white([white | T]) :- is_dutch_flag_white(T); % last one must be blue T = [blue | T1], is_dutch_flag_blue(T1). Β  is_dutch_flag_blue([blue | T]) :- is_dutch_flag_blue(T). Β  is_dutch_flag_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
#Maple
Maple
plots:-display(plottools:-parallelepiped([2, 0, 0], [0, 0, 4], [0, 3, 0]), orientation = [45, 60])
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.
#D
D
import std.stdio, std.string; Β  struct Board { enum char spc = ' '; char[][] b = [[' ']]; // Set at least 1x1 board. int shiftx, shifty; Β  void clear() pure nothrow { shiftx = shifty = 0; b = [['\0']]; } Β  void check(in int x, in int y) pure nothrow { while (y + shifty < 0) { auto newr = new char[b[0].length]; newr[] = spc; b = newr ~ b; shifty++; } Β  while (y + shifty >= b.length) { auto newr = new char[b[0].length]; newr[] = spc; b ~= newr; } Β  while (x + shiftx < 0) { foreach (ref c; b) c = [spc] ~ c; shiftx++; } Β  while (x + shiftx >= b[0].length) foreach (ref c; b) c ~= [spc]; } Β  char opIndexAssign(in char value, in int x, in int y) pure nothrow { check(x, y); b[y + shifty][x + shiftx] = value; return value; } Β  string toString() const pure { return format("%-(%s\n%)", b); } } Β  struct Turtle { static struct TState { int[2] xy; int heading; } Β  enum int[2][] dirs = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; enum string trace = r"-\|/-\|/"; TState t; Β  void reset() pure nothrow { t = typeof(t).init; } Β  void turn(in int dir) pure nothrow { t.heading = (t.heading + 8 + dir) % 8; } Β  void forward(ref Board b) pure nothrow { with (t) { xy[] += dirs[heading][]; b[xy[0], xy[1]] = trace[heading]; xy[] += dirs[heading][]; b[xy[0], xy[1]] = b.spc; } } } Β  void dragonX(in int n, ref Turtle t, ref Board b) pure nothrow { if (n >= 0) { // X -> X+YF+ dragonX(n - 1, t, b); t.turn(2); dragonY(n - 1, t, b); t.forward(b); t.turn(2); } } Β  void dragonY(in int n, ref Turtle t, ref Board b) pure nothrow { if (n >= 0) { // Y -> -FX-Y t.turn(-2); t.forward(b); dragonX(n - 1, t, b); t.turn(-2); dragonY(n - 1, t, b); } } Β  void main() { Turtle t; Board b; // SeedΒ : FX t.forward(b); // <- F dragonX(7, t, b); // <- X writeln(b); }
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
#Icon_and_Unicon
Icon and Unicon
procedure main() W := open("Demo", "gl", "size=400,400", "bg=black") | stop("can't open window!") WAttrib(W, "slices=40", "rings=40", "light0=on, ambient white; diffuse gold; specular gold; position 5, 0, 0" ) Fg(W, "emission blue") DrawSphere(W, 0, 0, -5, 1) Event(W) end
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#Haskell
Haskell
import Control.Concurrent import Data.List import System.Time Β  -- Library: ansi-terminal import System.Console.ANSI Β  number :: (Integral a) => a -> [String] number 0 = ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ,"β–ˆβ–ˆ β–ˆβ–ˆ" ,"β–ˆβ–ˆ β–ˆβ–ˆ" ,"β–ˆβ–ˆ β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] number 1 = [" β–ˆβ–ˆ" ," β–ˆβ–ˆ" ," β–ˆβ–ˆ" ," β–ˆβ–ˆ" ," β–ˆβ–ˆ"] number 2 = ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ," β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ,"β–ˆβ–ˆ " ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] number 3 = ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ," β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ," β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] number 4 = ["β–ˆβ–ˆ β–ˆβ–ˆ" ,"β–ˆβ–ˆ β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ," β–ˆβ–ˆ" ," β–ˆβ–ˆ"] number 5 = ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ,"β–ˆβ–ˆ " ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ," β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] number 6 = ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ,"β–ˆβ–ˆ " ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ,"β–ˆβ–ˆ β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] number 7 = ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ," β–ˆβ–ˆ" ," β–ˆβ–ˆ" ," β–ˆβ–ˆ" ," β–ˆβ–ˆ"] number 8 = ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ,"β–ˆβ–ˆ β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ,"β–ˆβ–ˆ β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] number 9 = ["β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ,"β–ˆβ–ˆ β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ" ," β–ˆβ–ˆ" ,"β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"] Β  colon :: [String] colon = [" " ," β–ˆβ–ˆ " ," " ," β–ˆβ–ˆ " ," "] Β  newline :: [String] newline = ["\n" ,"\n" ,"\n" ,"\n" ,"\n"] Β  space :: [String] space = [" " ," " ," " ," " ," "] Β  leadingZero :: (Integral a) => a -> [[String]] leadingZero num = let (tens, ones) = divMod num 10 in [number tens, space, number ones] Β  fancyTime :: CalendarTime -> String fancyTime time = let hour = leadingZero $ ctHour time minute = leadingZero $ ctMin time second = leadingZero $ ctSec time nums = hour ++ [colon] ++ minute ++ [colon] ++ second ++ [newline] in concat $ concat $ transpose nums Β  main :: IO () main = do time <- getClockTime >>= toCalendarTime putStr $ fancyTime time threadDelay 1000000 setCursorColumn 0 cursorUp 5 main
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)
#Python
Python
import random Β  colours_in_order = 'Red White Blue'.split() Β  def dutch_flag_sort(items, order=colours_in_order): 'return sort of items using the given order' reverse_index = dict((x,i) for i,x in enumerate(order)) return sorted(items, key=lambda x: reverse_index[x]) Β  def dutch_flag_check(items, order=colours_in_order): 'Return True if each item of items is in the given order' reverse_index = dict((x,i) for i,x in enumerate(order)) order_of_items = [reverse_index[item] for item in items] return all(x <= y for x, y in zip(order_of_items, order_of_items[1:])) Β  def random_balls(mx=5): 'Select from 1 to mx balls of each colour, randomly' balls = sum([[colour] * random.randint(1, mx) for colour in colours_in_order], []) random.shuffle(balls) return balls Β  def main(): # Ensure we start unsorted while True: balls = random_balls() if not dutch_flag_check(balls): break print("Original Ball order:", balls) sorted_balls = dutch_flag_sort(balls) print("Sorted Ball Order:", sorted_balls) assert dutch_flag_check(sorted_balls), 'Whoops. Not sorted!' Β  if __name__ == '__main__': main()
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Graphics3D[Cuboid[{0,0,0},{2,3,4}]]
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.
#Delphi
Delphi
Β  program Dragon_curve; Β  {$APPTYPE CONSOLE} Β  uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics; Β  type TDragon = class private p: TColor; _sin: TArray<double>; _cos: TArray<double>; s: double; b: TBitmap; FAsBitmap: TBitmap; const sep = 512; depth = 14; procedure Dragon(n, a, t: Integer; d, x, y: Double; var b: TBitmap); public constructor Create; destructor Destroy; override; property AsBitmap: TBitmap read b; end; Β  { TDragon } Β  procedure TDragon.Dragon(n, a, t: Integer; d, x, y: Double; var b: TBitmap); begin if n <= 1 then begin with b.Canvas do begin Pen.Color := p; MoveTo(Trunc(x + 0.5), Trunc(y + 0.5)); LineTo(Trunc(x + d * _cos[a] + 0.5), Trunc(y + d * _sin[a] + 0.5)); exit; end; end; Β  d := d * s; var a1 := (a - t) and 7; var a2 := (a + t) and 7; Β  dragon(n - 1, a1, 1, d, x, y, b); dragon(n - 1, a2, -1, d, x + d * _cos[a1], y + d * _sin[a1], b); end; Β  constructor TDragon.Create; begin s := sqrt(2) / 2; _sin := [0, s, 1, s, 0, -s, -1, -s]; _cos := [1.0, s, 0.0, -s, -1.0, -s, 0.0, s]; p := Rgb(64, 192, 96); b := TBitmap.create; Β  var width := Trunc(sep * 11 / 6); var height := Trunc(sep * 4 / 3); b.SetSize(width, height); with b.Canvas do begin Brush.Color := clWhite; Pen.Width := 3; FillRect(Rect(0, 0, width, height)); end; dragon(14, 0, 1, sep, sep / 2, sep * 5 / 6, b); end; Β  destructor TDragon.Destroy; begin b.Free; inherited; end; Β  var Dragon: TDragon; Β  begin Dragon := TDragon.Create; Dragon.AsBitmap.SaveToFile('dragon.bmp'); Dragon.Free; end.
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
#J
J
Studio > Demos... > opengl simple... [ok] > sphere [Run]
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
#Icon_and_Unicon
Icon and Unicon
Β  link graphics Β  global xsize, ysize, fontsize Β  procedure main(args) if *args > 0 then xsize := ysize := numeric(args[1]) Β  /xsize := /ysize := 200 WIN := WOpen("size=" || xsize || "," || ysize, "label=Clock", "resize=on") | stop("Fenster geht nicht auf!", image(xsize), " - ", image(ysize)) ziffernblatt() Β  repeat { write(&time) Β  if *Pending(WIN) > 1 then while *Pending() > 0 do { e := Event() ziffernblatt() } Β  Fg("#CFB53B") FillCircle(xsize/2, ysize/2, xsize/2 * 0.81) Fg("black") Β  clock := &clock sec := clock[7:0] min := clock[4:6] hour := clock[1:3] Β  if fontsize > 7 then { #Fg("yellow") EraseArea(10,0, TextWidth(clock),WAttrib("fheight")) DrawString(10,fontsize, clock) } Β  draw_zeiger(hour, min, sec) Β  WFlush() delay(100) } end Β  procedure ziffernblatt() xsize := WAttrib("width") ysize := WAttrib("height") if xsize < ysize then ysize := xsize if ysize < xsize then xsize := ysize Β  EraseArea(0,0,WAttrib("width"),WAttrib("height")) Β  Fg("#CFB53B") FillCircle(xsize/2, ysize/2, xsize/2) Fg("black") fontsize := fontsize := 30 * xsize / 800.0 Β  every i := 1 to 60 do { winkel := 6 * i / 180.0 * &pi if i % 5 = 0 then { laenge := 0.95 if fontsize > 15 then { Font("mono," || integer(fontsize) || ",bold") WAttrib("linewidth=3") } if fontsize > 8 then { Font("sans," || integer(fontsize)) WAttrib("linewidth=2") } Β  if fontsize > 8 then DrawString(xsize/2 + 0.90 * xsize/2 * sin(winkel) - fontsize / 2, ysize/2 - 0.90 * ysize/2 * cos(winkel) + fontsize/2, (i/5)("I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII")) } else laenge := 0.98 if fontsize >= 5 then DrawLine(xsize/2 + laenge * xsize/2 * sin(winkel), ysize/2 - laenge * ysize/2 * cos(winkel), xsize/2 + 0.99 * xsize/2 * sin(winkel), ysize/2 - 0.99 * ysize/2 * cos(winkel)) if fontsize < 5 then if i % 5 = 0 then { WAttrib("linewidth=1") DrawLine(xsize/2 + laenge * xsize/2 * sin(winkel), ysize/2 - laenge * ysize/2 * cos(winkel), xsize/2 + 0.99 * xsize/2 * sin(winkel), ysize/2 - 0.99 * ysize/2 * cos(winkel)) } } clock := &clock sec := clock[7:0] min := clock[4:6] hour := clock[1:3] Β  if fontsize > 7 then { EraseArea(10,0, TextWidth(clock),WAttrib("fheight")) DrawString(10,fontsize, clock) } draw_zeiger(hour, min, sec) Β  Fg("#D4AF37") FillCircle(xsize/2, ysize/2, 5) Fg("black") WAttrib("linewidth=2") Β  DrawCircle(xsize/2, ysize/2,5) Β  end Β  procedure draw(laenge, breite, winkel) WAttrib("linewidth=" || breite) DrawLine(xsize/2,ysize/2,xsize/2 + laenge * sin(winkel), ysize/2 - laenge * cos(winkel)) end Β  procedure draw_zeiger(h, m, s) wh := 30 * ((h % 12) + m / 60.0 + s / 3600.0) / 180 * &pi wm := 6 * (m + s / 60.0) / 180.0 * &pi ws := 6 * s / 180.0 * &pi Β  draw(xsize/2 * 0.5, 5, wh) # Stundenzeiger draw(xsize/2 * 0.65, 3, wm) # Minutenzeiger draw(xsize/2 * 0.80, 1, ws) # Sekundenzeiger 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)
#Racket
Racket
Β  #lang racket Β  (define dutch-colors '(red white blue)) Β  (define (dutch-order? balls) Β ;; drop each color from the front, should end up empty (null? (for/fold ([r balls]) ([color dutch-colors]) (dropf r (curry eq? color))))) Β  (define (random-balls) (define balls (for/list ([i (random 20)]) (list-ref dutch-colors (random (length dutch-colors))))) (if (dutch-order? balls) (random-balls) balls)) Β  ;; first method: use a key to map colors to integers (define (order->key order) (let ([alist (for/list ([x order] [i (in-naturals)]) (cons x i))]) (Ξ»(b) (cdr (assq b alist))))) (define (sort-balls/key balls) (sort balls < #:key (order->key dutch-colors))) Β  ;; second method: use a comparator built from the ordered list (define ((order<? ord) x y) (memq y (cdr (memq x ord)))) (define (sort-balls/compare balls) (sort balls (order<? dutch-colors))) Β  (define (test sort) (define balls (random-balls)) (define sorted (sort balls)) (printf "Testing ~a:\n Random: ~s\n Sorted: ~s\n ==> ~s\n" (object-name sort) balls sorted (if (dutch-order? sorted) 'OK 'BAD))) (for-each test (list sort-balls/key sort-balls/compare)) Β 
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)
#Raku
Raku
enum NL <red white blue>; my @colors; Β  sub how'bout (&this-way) { sub show { say @colors; say "Ordered: ", [<=] @colors; } Β  @colors = NL.roll(20); show; this-way; show; say ''; } Β  say "Using functional sort"; how'bout { @colors = sort *.value, @colors } Β  say "Using in-place sort"; how'bout { @colors .= sort: *.value } Β  say "Using a Bag"; how'bout { @colors = flat red, white, blue Zxx bag(@colorsΒ».key)<red white blue> } Β  say "Using the classify method"; how'bout { @colors = flat (.list forΒ %(@colors.classify: *.value){0,1,2}) } Β  say "Using multiple greps"; how'bout { @colors = flat (.grep(red), .grep(white), .grep(blue) given @colors) }
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
#Maxima
Maxima
load(draw)$ Β  draw3d(xu_grid=100, yv_grid=100, surface_hide=true, palette=gray, enhanced3d=[x - z / 4 - y / 4, x, y, z], implicit(max(abs(x / 4), abs(y / 6), abs(z / 8)) = 1, x,-10,10,y,-10,10,z,-10,10))$
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree 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.
#EasyLang
EasyLang
color 050 linewidth 0.5 x = 25 y = 60 move x y angle = 0 # func dragon size lev d . . if lev = 0 x -= cos angle * size y += sin angle * size line x y else call dragon size / sqrt 2 lev - 1 1 angle -= d * 90 call dragon size / sqrt 2 lev - 1 -1 . . call dragon 60 12 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
#Java
Java
public class Sphere{ static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}; Β  static double[] light = { 30, 30, -50 }; private static void normalize(double[] v){ double len = Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } Β  private static double dot(double[] x, double[] y){ double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } Β  public static void drawSphere(double R, double k, double ambient){ double[] vec = new double[3]; for(int i = (int)Math.floor(-R); i <= (int)Math.ceil(R); i++){ double x = i + .5; for(int j = (int)Math.floor(-2 * R); j <= (int)Math.ceil(2 * R); j++){ double y = j / 2. + .5; if(x * x + y * y <= R * R) { vec[0] = x; vec[1] = y; vec[2] = Math.sqrt(R * R - x * x - y * y); normalize(vec); double b = Math.pow(dot(light, vec), k) + ambient; int intensity = (b <= 0) ? shades.length - 2 : (int)Math.max((1 - b) * (shades.length - 1), 0); System.out.print(shades[intensity]); } else System.out.print(' '); } System.out.println(); } } Β  public static void main(String[] args){ normalize(light); drawSphere(20, 4, .1); drawSphere(10, 2, .4); } }
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
#J
J
{{ require'gl2' coinsert 'jgl2' clock_face_paint=: {{ try. 'H M S'=. _3{.6!:0'' glclear'' center=. 2-~<.-:glqwh'' glpen 2: glrgb 0 0 0 255 glellipse 1+,0 2*/center center {{ gllines <.2+(m,m)+,0.97 1*/m*+.j.y}}"0^j.2r12p1*i.12 center {{ gllines <.2+(m,m)+,0.92 0.99*/m*+.j.y}}"0^j.2r4p1*i.4 hand=: center {{ glpen 2: glbrush glrgb<.4{.255*x,4#1 gllines<.2+m,m*1++.j.n*^j.1p1+y EMPTY }} 1 0 0 (0.8) hand 2r60p1*S 0 1 0 (0.7) hand 2r60p1*M+60%~S 0 0 1 (0.4) hand 2r12p1*H+60%~M+60%~S catch. echo 13!:12'' end. EMPTY }} clock_timer=: glpaint wd {{)n pc clock closeok; cc face isigraph; set face wh 200 200; ptimer 100; pshow; }} }}1
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order: Β  red Β  Β  (top) Β  then white, Β  and Β  lastly blue Β  (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national 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)
#REXX
REXX
/*REXX program reorders a set of random colored balls into a correct order, which is the*/ /*────────────────────────────────── order of colors on the Dutch flag: red white blue.*/ parse arg N colors /*obtain optional arguments from the CL*/ if N='' | N="," then N=15 /*Not specified? Then use the default.*/ if colors='' then colors= 'red white blue' /* " " " " " " */ #=words(colors) /*count the number of colors specified.*/ @=word(colors, #) word(colors, 1) /*ensure balls aren't already in order.*/ Β  do g=3 to N /*generate a random # of colored balls.*/ @=@ word( colors, random(1, #) ) /*append a random color to the @ list.*/ end /*g*/ Β  say 'number of colored balls generated = ' N Β ; say say center(' original ball order ', length(@), "─") say @ Β ; say $=; do j=1 for #; _=word(colors, j); $=$ copies(_' ', countWords(_, @)) end /*j*/ say say center(' sorted ball order ', length(@), "─") say space($) say do k=2 to N /*verify the balls are in correct order*/ if wordpos(word($,k), colors) >= wordpos(word($,k-1), colors) then iterate say "The list of sorted balls isn't in proper order!"; exit 13 end /*k*/ say say 'The sorted colored ball list has been confirmed as being sorted correctly.' exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ countWords: procedure; parse argΒ ?,hay; s=1 do r=0 until _==0; _=wordpos(?, hay, s); s=_+1; end /*r*/; return r
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
#Nim
Nim
import strutils Β  proc cline(n, x, y: int, cde: string) = echo cde[0..0].align n+1, repeat(cde[1], 9*x-1), cde[0], if cde.len > 2: cde[2..2].align y+1 else: "" Β  proc cuboid(x, y, z: int) = cline y+1, x, 0, "+-" for i in 1..y: cline y-i+1, x, i-1, "/ |" cline 0, x, y, "+-|" for i in 0..4*z-y-3: cline 0, x, y, "| |" cline 0, x, y, "| +" for i in countdown(y-1, 0): cline 0, x, i, "| /" cline 0, x, 0, "+-\n" Β  cuboid 2, 3, 4 cuboid 1, 1, 1 cuboid 6, 2, 1
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.
#Elm
Elm
import Color exposing (..) import Collage exposing (..) import Element exposing (..) import Time exposing (..) import Html exposing (..) import Html.App exposing (program) Β  Β  type alias Point = (Float, Float) Β  type alias Model = { pointsΒ : List Point , levelΒ : Int , frameΒ : Int } Β  maxLevel = 12 frameCount = 100 Β  type Msg = Tick Time Β  initΒ : (Model,Cmd Msg) init = ( { points = [(-200.0, -70.0), (200.0, -70.0)] , level = 0 , frame = 0 } , Cmd.none ) Β  -- New point between two existing points. Offset to left or right newPointΒ : Point -> Point -> Float -> Point newPoint (x0,y0) (x1,y1) offset = let (vx, vy) = ((x1 - x0) / 2.0, (y1 - y0) / 2.0) (dx, dy) = (-vy * offset , vx * offset ) in (x0 + vx + dx, y0 + vy + dy) --offset from midpoint Β  -- Insert between existing points. Offset to left or right side. newPointsΒ : Float -> List Point -> List Point newPoints offset points = case points of [] -> [] [p0] -> [p0] p0::p1::rest -> p0Β :: newPoint p0 p1 offsetΒ :: newPoints -offset (p1::rest) Β  updateΒ : Msg -> Model -> (Model, Cmd Msg) update _ model = let mo = if (model.level == maxLevel) then model else let nextFrame = model.frame + 1 in if (nextFrame == frameCount) then { points = newPoints 1.0 model.points , level = model.level+1 , frame = 0 } else { model | frame = nextFrame } in (mo, Cmd.none) Β  -- break a list up into n equal sized lists. breakupIntoΒ : Int -> List a -> List (List a) breakupInto n ls = let segmentCount = (List.length ls) - 1 breakup n ls = case ls of [] -> [] _ -> List.take (n+1) lsΒ :: breakup n (List.drop n ls) in if n > segmentCount then [ls] else breakup (segmentCount // n) ls Β  viewΒ : Model -> Html Msg view model = let offset = toFloat (model.frame) / toFloat frameCount colors = [red, orange, green, blue] in toHtml <| layers [ collage 700 500 (model.points |> newPoints offset |> breakupInto (List.length colors) -- for coloring |> List.map path |> List.map2 (\color path -> traced (solid color) path ) colors ) , show model.level ] Β  subscriptionsΒ : Model -> Sub Msg subscriptions _ = Time.every (5*millisecond) Tick Β  main = program { init = init , view = view , update = update , subscriptions = subscriptions }
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
#JavaScript
JavaScript
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Draw a sphere</title> <script> var light=[30,30,-50],gR,gk,gambient; Β  function normalize(v){ var len=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); v[0]/=len; v[1]/=len; v[2]/=len; return v; } Β  function dot(x,y){ var d=x[0]*y[0]+x[1]*y[1]+x[2]*y[2]; return d<0?-d:0; } Β  function draw_sphere(R,k,ambient){ var i,j,intensity,b,vec,x,y,cvs,ctx,imgdata,idx; cvs=document.getElementById("c"); ctx=cvs.getContext("2d"); cvs.width=cvs.height=2*Math.ceil(R)+1; imgdata=ctx.createImageData(2*Math.ceil(R)+1,2*Math.ceil(R)+1); idx=0; for(i=Math.floor(-R);i<=Math.ceil(R);i++){ x=i+.5; for(j=Math.floor(-R);j<=Math.ceil(R);j++){ y=j+.5; if(x*x+y*y<=R*R){ vec=[x,y,Math.sqrt(R*R-x*x-y*y)]; vec=normalize(vec); b=Math.pow(dot(light,vec),k)+ambient; intensity=(1-b)*256; if(intensity<0)intensity=0; if(intensity>=256)intensity=255; imgdata.data[idx++]=imgdata.data[idx++]=255-~~(intensity); //RG imgdata.data[idx++]=imgdata.data[idx++]=255; //BA } else { imgdata.data[idx++]=imgdata.data[idx++]=imgdata.data[idx++]=imgdata.data[idx++]=255; //RGBA } } } ctx.putImageData(imgdata,0,0); } Β  light=normalize(light); </script> </head> <body onload="gR=200;gk=4;gambient=.2;draw_sphere(gR,gk,gambient)"> R=<input type="range" id="R" name="R" min="5" max="500" value="200" step="5" onchange="document.getElementById('lR').innerHTML=gR=parseFloat(this.value);draw_sphere(gR,gk,gambient)"> <label for="R" id="lR">200</label><br> k=<input type="range" id="k" name="k" min="0" max="10" value="4" step=".25" onchange="document.getElementById('lk').innerHTML=gk=parseFloat(this.value);draw_sphere(gR,gk,gambient)"> <label for="k" id="lk">4</label><br> ambient=<input type="range" id="ambient" name="ambient" min="0" max="1" value=".2" step=".05" onchange="document.getElementById('lambient').innerHTML=gambient=parseFloat(this.value);draw_sphere(gR,gk,gambient)"> <label for="ambient" id="lambient">0.2</label><br> <canvas id="c">Unsupportive browser...</canvas><br> </body> </html>
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
#Java
Java
import java.awt.*; import java.awt.event.*; import static java.lang.Math.*; import java.time.LocalTime; import javax.swing.*; Β  class Clock extends JPanel { Β  final float degrees06 = (float) (PI / 30); final float degrees30 = degrees06 * 5; final float degrees90 = degrees30 * 3; Β  final int size = 590; final int spacing = 40; final int diameter = size - 2 * spacing; final int cx = diameter / 2 + spacing; final int cy = diameter / 2 + spacing; Β  public Clock() { setPreferredSize(new Dimension(size, size)); setBackground(Color.white); Β  new Timer(1000, (ActionEvent e) -> { repaint(); }).start(); } Β  @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Β  drawFace(g); Β  final LocalTime time = LocalTime.now(); int hour = time.getHour(); int minute = time.getMinute(); int second = time.getSecond(); Β  float angle = degrees90 - (degrees06 * second); drawHand(g, angle, diameter / 2 - 30, Color.red); Β  float minsecs = (minute + second / 60.0F); angle = degrees90 - (degrees06 * minsecs); drawHand(g, angle, diameter / 3 + 10, Color.black); Β  float hourmins = (hour + minsecs / 60.0F); angle = degrees90 - (degrees30 * hourmins); drawHand(g, angle, diameter / 4 + 10, Color.black); } Β  private void drawFace(Graphics2D g) { g.setStroke(new BasicStroke(2)); g.setColor(Color.white); g.fillOval(spacing, spacing, diameter, diameter); g.setColor(Color.black); g.drawOval(spacing, spacing, diameter, diameter); } Β  private void drawHand(Graphics2D g, float angle, int radius, Color color) { int x = cx + (int) (radius * cos(angle)); int y = cy - (int) (radius * sin(angle)); g.setColor(color); g.drawLine(cx, cy, x, y); } Β  public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Clock"); f.setResizable(false); f.add(new Clock(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
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)
#Ring
Ring
Β  # ProjectΒ : Dutch national flag problem Β  flag = ["Red","White","Blue"] balls = list(10) Β  see "Random: |" for i = 1 to 10 color = random(2) + 1 balls[i] = flag[color] see balls[i] + " |" next see nl Β  see "Sorted: |" for i = 1 to 3 color = flag[i] for j = 1 to 10 if balls[j] = color see balls[j] + " |" ok next next Β 
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)
#Ruby
Ruby
class Ball FLAG = {red: 1, white: 2, blue: 3} Β  def initialize @color = FLAG.keys.sample end Β  def color @color end Β  def <=>(other) # needed for sort, results in -1 for <, 0 for == and 1 for >. FLAG[self.color] <=> FLAG[other.color] end Β  def inspect @color end end Β  balls = [] balls = Array.new(8){Ball.new} while balls == balls.sort Β  puts "Random: #{balls}" puts "Sorted: #{balls.sort}" Β 
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
#Openscad
Openscad
// This will produce a simple cuboid cube([2,3,4]); Β 
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.
#Emacs_Lisp
Emacs Lisp
(defun dragon-ensure-line-above () "If point is in the first line of the buffer then insert a new line above." (when (= (line-beginning-position) (point-min)) (save-excursion (goto-char (point-min)) (insert "\n")))) Β  (defun dragon-ensure-column-left () "If point is in the first column then insert a new column to the left. This is designed for use in `picture-mode'." (when (zerop (current-column)) (save-excursion (goto-char (point-min)) (insert " ") (while (= 0 (forward-line 1)) (insert " "))) (picture-forward-column 1))) Β  (defun dragon-insert-char (char len) "Insert CHAR repeated LEN many times. After each CHAR point move in the current `picture-mode' direction (per `picture-set-motion' etc). Β  This is the same as `picture-insert' except in column 0 or row 0 a new row or column is inserted to make room, with existing buffer contents shifted down or right." Β  (dotimes (i len) (dragon-ensure-line-above) (dragon-ensure-column-left) (picture-insert char 1))) Β  (defun dragon-bit-above-lowest-0bit (n) "Return the bit above the lowest 0-bit in N. For example N=43 binary \"101011\" has lowest 0-bit at \"...0..\" and the bit above that is \"..1...\" so return 8 which is that bit." (logand n (1+ (logxor n (1+ n))))) Β  (defun dragon-next-turn-right-p (n) "Return non-nil if the dragon curve should turn right after segment N. Segments are numbered from N=0 for the first, so calling with N=0 is whether to turn right after drawing that N=0 segment." (zerop (dragon-bit-above-lowest-0bit n))) Β  (defun dragon-picture (len step) "Draw the dragon curve in a *dragon* buffer. LEN is the number of segments of the curve to draw. STEP is the length of each segment, in characters. Β  Any LEN can be given but a power-of-2 such as 256 shows the self-similar nature of the curve. Β  If STEP >= 2 then the segments are lines using \"-\" or \"|\" characters (`picture-rectangle-h' and `picture-rectangle-v'). If STEP=1 then only \"+\" corners. Β  There's a `sit-for' delay in the drawing loop to draw the curve progressively on screen." Β  (interactive (list (read-number "Length of curve " 256) (read-number "Each step size " 3))) (unless (>= step 1) (error "Step length must be >= 1")) Β  (switch-to-buffer "*dragon*") (erase-buffer) (ignore-errors ;; if already in picture-mode (picture-mode)) Β  (dotimes (n len) ;; n=0 to len-1, inclusive (dragon-insert-charΒ ?+ 1) ;; corner char (dragon-insert-char (if (zerop picture-vertical-step) picture-rectangle-h picture-rectangle-v) (1- step)) ;; line chars Β  (if (dragon-next-turn-right-p n) ;; turn right (picture-set-motion (- picture-horizontal-step) picture-vertical-step) ;; turn left (picture-set-motion picture-horizontal-step (- picture-vertical-step))) Β  ;; delay to display the drawing progressively (sit-for .01)) Β  (picture-insertΒ ?+ 1) ;; endpoint (picture-mode-exit) (goto-char (point-min))) Β  (dragon-picture 128 2)
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
#jq
jq
def svg: "<svg width='100%' height='100%' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>"Β ; Β  # A radial gradient to make a circle look like a sphere. # "colors" should be [startColor, intermediateColor, endColor] # or null for ["white", "teal", "black"] def sphericalGradient(id; colors): "<defs> <radialGradient id = '\(id)' cx = '30%' cy = '30%' r = '100%' fx='10%' fy='10%' > <stop stop-color = '\(colors[0]//"white")' offset = '0%'/> <stop stop-color = '\(colors[1]//"teal")' offset = '50%'/> <stop stop-color = '\(colors[1]//"black")' offset = '100%'/> </radialGradient> </defs>"Β ; Β  def sphere(cx; cy; r; gradientId): "<circle fill='url(#\(gradientId))' cx='\(cx)' cy='\(cy)' r='\(r)' />"Β ;
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
#JavaScript
JavaScript
var sec_old = 0; function update_clock() { var t = new Date(); var arms = [t.getHours(), t.getMinutes(), t.getSeconds()]; if (arms[2] == sec_old) return; sec_old = arms[2]; Β  var c = document.getElementById('clock'); var ctx = c.getContext('2d'); ctx.fillStyle = "rgb(0,200,200)"; ctx.fillRect(0, 0, c.width, c.height); ctx.fillStyle = "white"; ctx.fillRect(3, 3, c.width - 6, c.height - 6); ctx.lineCap = 'round'; Β  var orig = { x: c.width / 2, y: c.height / 2 }; arms[1] += arms[2] / 60; arms[0] += arms[1] / 60; draw_arm(ctx, orig, arms[0] * 30, c.width/2.5 - 15, c.width / 20, "green"); draw_arm(ctx, orig, arms[1] * 6, c.width/2.2 - 10, c.width / 30, "navy"); draw_arm(ctx, orig, arms[2] * 6, c.width/2.0 - 6, c.width / 100, "maroon"); } Β  function draw_arm(ctx, orig, deg, len, w, style) { ctx.save(); ctx.lineWidth = w; ctx.lineCap = 'round'; ctx.translate(orig.x, orig.y); ctx.rotate((deg - 90) * Math.PI / 180); ctx.strokeStyle = style; ctx.beginPath(); ctx.moveTo(-len / 10, 0); ctx.lineTo(len, 0); ctx.stroke(); ctx.restore(); } Β  function init_clock() { var clock = document.createElement('canvas'); clock.width = 100; clock.height = 100; clock.id = "clock"; document.body.appendChild(clock); Β  window.setInterval(update_clock, 200); }
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)
#Run_BASIC
Run BASIC
flag$ = "Red,White,Blue" Β  print "Random: |"; for i = 1 to 10 color = rnd(0) * 3 + 1 balls$(i) = word$(flag$,color,",") print balls$(i);" |"; next i Β  printΒ :print "Sorted: |"; for i = 1 to 3 color$ = word$(flag$,i,",") for j = 1 to 10 if balls$(j) = color$ then print balls$(j);" |"; end if next j next i
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)
#Rust
Rust
extern crate rand; Β  use rand::Rng; Β  // Color enums will be sorted by their top-to-bottom declaration order #[derive(Eq,Ord,PartialOrd,PartialEq,Debug)] enum Color { Red, White, Blue } Β  fn is_sorted(list: &Vec<Color>) -> bool { let mut state = &Color::Red; for current in list.iter() { if current < state { return false; } if current > state { state = current; } } true } Β  Β  fn main() { let mut rng = rand::thread_rng(); let mut colors: Vec<Color> = Vec::new(); Β  for _ in 1..10 { let r = rng.gen_range(0, 3); if r == 0 { colors.push(Color::Red); } else if r == 1 { colors.push(Color::White); } else if r == 2 { colors.push(Color::Blue); } } Β  while is_sorted(&colors) { rng.shuffle(&mut colors); } Β  println!("Before: {:?}", colors); colors.sort(); println!("After: {:?}", colors); ifΒ !is_sorted(&colors) { println!("Oops, did not sort colors correctly!"); } }
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
#OxygenBasic
OxygenBasic
Β  Β % Title "Cuboid 2x3x4" '% Animated Β % PlaceCentral uses ConsoleG Β  sub main ======== cls 0.0, 0.2, 0.7 shading scale 3 pushstate GoldMaterial.act static float ang=45 rotateX ang rotateY ang scale 2,3,4 go cube popstate end sub Β  EndScript Β 
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
#PARI.2FGP
PARI/GP
Β  \\ Simple "cuboid". Try different parameters of this Cuboid() function. \\ 4/11/16 aev Cuboid(a,b,c,u=10)={ my(dx,dy,ttl="Cuboid AxBxC: ",size=200,da=a*u,db=b*u,dc=c*u); print(" *** ",ttl,a,"x",b,"x",c,"; u=",u); plotinit(0); plotscale(0, 0,size, 0,size); plotcolor(0,7); \\grey plotmove(0, 0,0); plotrline(0,dc,da\2); plotrline(0,db,0); plotrline(0,-db,0); plotrline(0,0,da); plotcolor(0,2); \\black plotmove(0, db,da); plotrline(0,0,-da); plotrline(0,-db,0); plotrline(0,0,da); plotrline(0,db,0); plotrline(0,dc,da\2); plotrline(0,-db,0); plotrline(0,-dc,-da\2); plotmove(0, db,0); plotrline(0,dc,da\2); plotrline(0,0,da); plotdraw([0,size,size]); } Β  {\\ Executing: Cuboid(2,3,4,20); \\Cuboid1.png Cuboid(5,3,1,20); \\Cuboid2.png } Β 
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.
#ERRE
ERRE
Β  PROGRAM DRAGON Β  ! ! for rosettacode.org ! Β  !$DYNAMIC DIM RQS[0] Β  !$INCLUDE="PC.LIB" Β  PROCEDURE DRAGON IF LEVEL<=0 THEN YN=SIN(ROTATION)*INSIZE+Y XN=COS(ROTATION)*INSIZE+X LINE(X,Y,XN,YN,12,FALSE) ITER=ITER+1 X=XN Y=YN EXIT PROCEDURE END IF INSIZE=INSIZE/SQ ROTATION=ROTATION+RQ*QPI LEVEL=LEVEL-1 RQS[LEVEL]=RQ RQ=1 DRAGON ROTATION=ROTATION-RQS[LEVEL]*QPI*2 RQ=-1 DRAGON RQ=RQS[LEVEL] ROTATION=ROTATION+RQ*QPI LEVEL=LEVEL+1 INSIZE=INSIZE*SQ END PROCEDURE Β  BEGIN SCREEN(9) Β  LEVEL=12 INSIZE=287 Β ! initial values X=200 Y=120 Β ! Β  SQ=SQR(2) QPI=ATN(1) Β ! constants ROTATION=0 ITER=0 RQ=1 Β ! state variables Β !$DIM RQS[LEVEL] Β ! stack for RQ (ROTATION coefficient) LINE(0,0,639,349,14,TRUE) DRAGON GET(A$) END PROGRAM Β 
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
#Julia
Julia
function draw_sphere(r, k, ambient, light) shades = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@') for i in floor(Int, -r):ceil(Int, r) x = i + 0.5 line = IOBuffer() for j in floor(Int, -2r):ceil(2r) y = j / 2 + 0.5 if x ^ 2 + y ^ 2 ≀ r ^ 2 v = normalize([x, y, sqrt(r ^ 2 - x ^ 2 - y ^ 2)]) b = dot(light, v) ^ k + ambient intensity = ceil(Int, (1 - b) * (length(shades) - 1)) if intensity < 1 intensity = 1 end if intensity > length(shades) intensity = length(shades) end print(shades[intensity]) else print(' ') end end println() end end Β  light = normalize([30, 30, -50]) draw_sphere(20, 4, 0.1, light) draw_sphere(10, 2, 0.4, light) Β 
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
#Julia
Julia
Β  using Gtk, Colors, Graphics, Dates Β  const radius = 300 const win = GtkWindow("Clock", radius, radius) const can = GtkCanvas() push!(win, can) Β  global drawcontext = [] Β  function drawline(ctx, l, color) isempty(l) && return p = first(l) move_to(ctx, p.x, p.y) set_source(ctx, color) for i = 2:length(l) p = l[i] line_to(ctx, p.x, p.y) end stroke(ctx) end Β  function clockbody(ctx) set_coordinates(ctx, BoundingBox(0, 100, 0, 100)) rectangle(ctx, 0, 0, 100, 100) set_source(ctx, colorant"yellow") fill(ctx) set_source(ctx, colorant"blue") arc(ctx, 50, 50, 45, 45, 360) stroke(ctx) for hr in 1:12 radians = hr * pi / 6.0 drawline(ctx, [Point(50 + 0.95 * 45 * sin(radians), 50 - 0.95 * 45 * cos(radians)), Point(50 + 1.0 * 45 * sin(radians), 50 - 1.0 * 45 * cos(radians))], colorant"blue") end end Β  Gtk.draw(can) do widget ctx = getgc(can) if length(drawcontext) < 1 push!(drawcontext, ctx) else drawcontext[1] = ctx end clockbody(ctx) end Β  function update(can) dtim = now() hr = hour(dtim) mi = minute(dtim) sec = second(dtim) if length(drawcontext) < 1 return end ctx = drawcontext[1] clockbody(ctx) rad = (hrΒ % 12) * pi / 6.0 + mi * pi / 360.0 drawline(ctx, [Point(50, 50), Point(50 + 45 * 0.5 * sin(rad), 50 - 45 * 0.5 * cos(rad))], colorant"black") stroke(ctx) rad = mi * pi / 30.0 + sec * pi / 1800.0 drawline(ctx, [Point(50, 50), Point(50 + 0.7 * 45 * sin(rad), 50 - 0.7 * 45 * cos(rad))], colorant"darkgreen") stroke(ctx) rad = sec * pi / 30.0 drawline(ctx, [Point(50, 50), Point(50 + 0.9 * 45 * sin(rad), 50 - 0.9 * 45 * cos(rad))], colorant"red") stroke(ctx) reveal(can) end Β  Gtk.showall(win) sloc = Base.Threads.SpinLock() lock(sloc) signal_connect(win,Β :destroy) do widget unlock(sloc) end whileΒ !trylock(sloc) update(win) sleep(1.0) 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)
#Scala
Scala
object FlagColor extends Enumeration { type FlagColor = Value val Red, White, Blue = Value } Β  val genBalls = (1 to 10).map(i => FlagColor(scala.util.Random.nextInt(FlagColor.maxId))) val sortedBalls = genBalls.sorted val sorted = if (genBalls == sortedBalls) "sorted" else "not sorted" Β  println(s"Generated balls (${genBalls mkString " "}) are $sorted.") println(s"Sorted balls (${sortedBalls mkString " "}) are sorted.")
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)
#SQL
SQL
-- Create and populate tables CREATE TABLE colours (id INTEGER PRIMARY KEY, name VARCHAR(5)); INSERT INTO colours (id, name) VALUES ( 1, 'red' ); INSERT INTO colours (id, name) VALUES ( 2, 'white'); INSERT INTO colours (id, name) VALUES ( 3, 'blue' ); Β  CREATE TABLE balls ( colour INTEGER REFERENCES colours ); INSERT INTO balls ( colour ) VALUES ( 2 ); INSERT INTO balls ( colour ) VALUES ( 2 ); INSERT INTO balls ( colour ) VALUES ( 3 ); INSERT INTO balls ( colour ) VALUES ( 2 ); INSERT INTO balls ( colour ) VALUES ( 1 ); INSERT INTO balls ( colour ) VALUES ( 3 ); INSERT INTO balls ( colour ) VALUES ( 3 ); INSERT INTO balls ( colour ) VALUES ( 2 ); Β  -- Show the balls are unsorted SELECT colours.name FROM balls JOIN colours ON balls.colour = colours.id; Β  -- Show the balls in dutch flag order SELECT colours.name FROM balls JOIN colours ON balls.colour = colours.id ORDER BY colours.id; Β  -- Tidy up DROP TABLE balls; DROP TABLE colours;
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
#Pascal
Pascal
program Cuboid_Demo(output); Β  procedure DoCuboid(sWidth, sHeight, Depth: integer); const widthScale = 4; heightScale = 3; type TPage = array of array of char; var Cuboid: TPage; i, j: integer; Width, Height: integer; totalWidth, totalHeight: integer; begin Width := widthScale * sWidth; Height := heightScale * sHeight; totalWidth := 2 * Width + Depth + 3; totalHeight := Height + Depth + 3; setlength (Cuboid, totalHeight + 1); for i := 1 to totalHeight do setlength (Cuboid[i], totalwidth + 1); // points for i := low(Cuboid) to high(Cuboid) do for j := low(Cuboid[i]) to high(Cuboid[i]) do Cuboid[i,j] := ' '; Cuboid [1, 1] := '+'; Cuboid [Height + 2, 1] := '+'; Cuboid [1, 2 * Width + 2] := '+'; Cuboid [Height + 2, 2 * Width + 2] := '+'; Cuboid [totalHeight, Depth + 2] := '+'; Cuboid [Depth + 2, totalWidth] := '+'; Cuboid [totalHeight, totalWidth] := '+'; // width lines for I := 1 to 2 * Width do begin Cuboid [1, I + 1] := '-'; Cuboid [Height + 2, I + 1] := '-'; Cuboid [totalHeight, Depth + I + 2] := '-'; end; // height lines for I := 1 to Height do begin Cuboid [I + 1, 1] := '|'; Cuboid [I + 1, 2 * Width + 2] := '|'; Cuboid [Depth + I + 2, totalWidth] := '|'; end; // depth lines for I := 1 to Depth do begin Cuboid [Height + 2 + I, 1 + I] := '/'; Cuboid [1 + I, 2 * Width + 2 + I] := '/'; Cuboid [Height + 2 + I, 2 * Width + 2 + I] := '/'; end; for i := high(Cuboid) downto 1 do begin for j := 1 to high(Cuboid[i]) do write (Cuboid[i,j]); writeln; end; end; Β  begin writeln('1, 1, 1:'); DoCuboid(1, 1, 1); writeln('2, 3, 4:'); DoCuboid(2, 3, 4); writeln('6, 2, 1:'); DoCuboid(6, 2, 1); 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.
#F.23
F#
open System.Windows open System.Windows.Media Β  let m = Matrix(0.0, 0.5, -0.5, 0.0, 0.0, 0.0) Β  let step segs = seq { for a: Point, b: Point in segs do let x = a + 0.5 * (b - a) + (b - a) * m yield! [a, x; b, x] } Β  let rec nest n f x = if n=0 then x else nest (n-1) f (f x) Β  [<System.STAThread>] do let path = Shapes.Path(Stroke=Brushes.Black, StrokeThickness=0.001) path.Data <- PathGeometry [ for a, b in nest 13 step (seq [Point(0.0, 0.0), Point(1.0, 0.0)]) -> PathFigure(a, [(LineSegment(b, true)Β :> PathSegment)], false) ] (Application()).Run(Window(Content=Controls.Viewbox(Child=path))) |> ignore
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
#Kotlin
Kotlin
// version 1.0.6 Β  const val shades = ".:!*oe&#%@" val light = doubleArrayOf(30.0, 30.0, -50.0) Β  fun normalize(v: DoubleArray) { val len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) v[0] /= len; v[1] /= len; v[2] /= len } Β  fun dot(x: DoubleArray, y: DoubleArray): Double { val d = x[0] * y[0] + x[1] * y[1] + x[2] * y[2] return if (d < 0.0) -d else 0.0 } Β  fun drawSphere(r: Double, k: Double, ambient: Double) { val vec = DoubleArray(3) var intensity: Int var b : Double var x: Double var y: Double for (i in Math.floor(-r).toInt() .. Math.ceil(r).toInt()) { x = i + 0.5 for (j in Math.floor(-2.0 * r).toInt() .. Math.ceil(2.0 * r).toInt()) { y = j / 2.0 + 0.5 if (x * x + y * y <= r * r) { vec[0] = x vec[1] = y vec[2] = Math.sqrt(r * r - x * x - y * y) normalize(vec) b = Math.pow(dot(light, vec), k) + ambient intensity = ((1.0 - b) * (shades.length - 1)).toInt() if (intensity < 0) intensity = 0 if (intensity >= shades.length - 1) intensity = shades.length - 2 print(shades[intensity]) } else print(' ') } println() } } Β  fun main(args: Array<String>) { normalize(light) drawSphere(20.0, 4.0, 0.1) drawSphere(10.0, 2.0, 0.4) }
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
#Kotlin
Kotlin
// version 1.1 Β  import java.awt.* import java.time.LocalTime import javax.swing.* Β  class Clock : JPanel() { private val degrees06: Float = (Math.PI / 30.0).toFloat() private val degrees30: Float = degrees06 * 5.0f private val degrees90: Float = degrees30 * 3.0f private val size = 590 private val spacing = 40 private val diameter = size - 2 * spacing private val cx = diameter / 2 + spacing private val cy = cx Β  init { preferredSize = Dimension(size, size) background = Color.white Timer(1000) { repaint() }.start() } Β  override public fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawFace(g) val time = LocalTime.now() val hour = time.hour val minute = time.minute val second = time.second var angle: Float = degrees90 - degrees06 * second drawHand(g, angle, diameter / 2 - 30, Color.red) val minsecs: Float = minute + second / 60.0f angle = degrees90 - degrees06 * minsecs drawHand(g, angle, diameter / 3 + 10, Color.black) val hourmins: Float = hour + minsecs / 60.0f angle = degrees90 - degrees30 * hourmins drawHand(g, angle, diameter / 4 + 10, Color.black) } Β  private fun drawFace(g: Graphics2D) { g.stroke = BasicStroke(2.0f) g.color = Color.yellow g.fillOval(spacing, spacing, diameter, diameter) g.color = Color.black g.drawOval(spacing, spacing, diameter, diameter) } Β  private fun drawHand(g: Graphics2D, angle: Float, radius: Int, color: Color) { val x: Int = cx + (radius.toDouble() * Math.cos(angle.toDouble())).toInt() val y: Int = cy - (radius.toDouble() * Math.sin(angle.toDouble())).toInt() g.color = color g.drawLine(cx, cy, x, y) } } Β  fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE f.title = "Clock" f.isResizable = false f.add(Clock(), BorderLayout.CENTER) f.pack() f.setLocationRelativeTo(null) f.isVisible = true } }
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)
#Tcl
Tcl
# The comparison function proc dutchflagcompare {a b} { set colors {red white blue} return [expr {[lsearch $colors $a] - [lsearch $colors $b]}] } Β  # The test function (evil shimmer of list to string!) proc isFlagSorted lst { expr {![regexp {blue.*(white|red)} $lst] && ![regexp {white.*red} $lst]} } Β  # A ball generator proc generateBalls n { for {set i 0} {$i<$n} {incr i} { lappend result [lindex {red white blue} [expr {int(rand()*3)}]] } return $result } Β  # Do the challenge with 20 balls set balls [generateBalls 20] if {[isFlagSorted $balls]} { error "already a sorted flag" } set sorted [lsort -command dutchflagcompare $balls] if {[isFlagSorted $sorted]} { puts "Sorted the flag\n$sorted" } else { puts "sort failed\n$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
#Perl
Perl
sub cubLine ($$$$) { my ($n, $dx, $dy, $cde) = @_; Β  printf '%*s', $n + 1, substr($cde, 0, 1); Β  for (my $d = 9 * $dx - 1 ; $d > 0 ; --$d) { print substr($cde, 1, 1); } Β  print substr($cde, 0, 1); printf "%*s\n", $dy + 1, substr($cde, 2, 1); } Β  sub cuboid ($$$) { my ($dx, $dy, $dz) = @_; Β  printf "cuboidΒ %dΒ %dΒ %d:\n", $dx, $dy, $dz; cubLine $dy + 1, $dx, 0, '+-'; Β  for (my $i = 1 ; $i <= $dy ; ++$i) { cubLine $dy - $i + 1, $dx, $i - 1, '/ |'; } cubLine 0, $dx, $dy, '+-|'; Β  for (my $i = 4 * $dz - $dy - 2 ; $i > 0 ; --$i) { cubLine 0, $dx, $dy, '| |'; } cubLine 0, $dx, $dy, '| +'; Β  for (my $i = 1 ; $i <= $dy ; ++$i) { cubLine 0, $dx, $dy - $i, '| /'; } cubLine 0, $dx, 0, "+-\n"; } Β  cuboid 2, 3, 4; cuboid 1, 1, 1; cuboid 6, 2, 1;
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.
#Factor
Factor
Β  USING: accessors colors colors.hsv fry kernel locals math math.constants math.functions opengl.gl typed ui ui.gadgets ui.gadgets.canvas ui.renderΒ ; Β  IN: dragon Β  CONSTANT: depth 12 Β  TUPLE: turtle { angle fixnum } { color float } { x float } { y float }Β ; Β  TYPED: nxt-color ( turtle: turtle -- turtle ) [ [ 360 2 depth ^ /f + ] keep 1.0 1.0 1.0 <hsva> >rgba-components glColor4d ] change-colorΒ ; inline Β  TYPED: draw-fwd ( x1: float y1: float x2: float y2: float -- ) GL_LINES glBegin glVertex2d glVertex2d glEndΒ ; inline Β  TYPED:: fwd ( turtle: turtle l: float -- ) turtle x>> turtle y>> turtle angle>> pi * 180 /Β :> ( x y angle ) l angle [ cos * x + ] [ sin * y + ] 2biΒ :> ( dx dy ) turtle x y dx dy [ draw-fwd ] 2keep [ >>x ] [ >>y ] bi* dropΒ ; inline Β  TYPED: trn ( turtle: turtle d: fixnum -- turtle ) '[ _ + ] change-angleΒ ; inline Β  TYPED:: dragon' ( turtle: turtle l: float s: fixnum d: fixnum -- ) s zero? [ turtle nxt-color l fwdΒ ! don't like this drop ] [ turtle d 45 * trn l 2 sqrt / s 1 - 1 dragon' turtle d -90 * trn l 2 sqrt / s 1 - -1 dragon' turtle d 45 * trn drop ] ifΒ ; Β  : dragon ( -- ) 0 0 150 180 turtle boa 400 depth 1 dragon'Β ; Β  TUPLE: dragon-canvas < canvasΒ ; Β  M: dragon-canvas draw-gadget* [ drop dragon ] draw-canvasΒ ; M: dragon-canvas pref-dim* drop { 640 480 }Β ; Β  MAIN-WINDOW: dragon-window { { title "Dragon Curve" } } dragon-canvas new-canvas >>gadgetsΒ ; Β  MAIN: dragon-window Β 
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
#Lingo
Lingo
---------------------------------------- -- Draw a circle -- @param {image} img -- @param {integer} x -- @param {integer} y -- @param {integer} r -- @param {integer} lineSize -- @param {color} drawColor ---------------------------------------- on circle (img, x, y, r, lineSize, drawColor) props = [:] props[#shapeType] = #oval props[#lineSize] = lineSize props[#color] = drawColor img.draw(x-r, y-r, x+r, y+r, props) end
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#Lambdatalk
Lambdatalk
Β  1) lambdatalk code {watch} // displays the watch Β  {def watch {watch.init} {div {@ id="watch"}} } Β  {def watch.draw {lambda {:rΒ :gΒ :b} {svg {@ style="width:300px; height:300px;"} {let { {:rΒ :r} {:gΒ :g} {:bΒ :b} {:t {date}} } {watch.path 150 150 100 20Β :r 1Β :t} {watch.path 150 150 120 20Β :g 2Β :t} {watch.path 150 150 140 20Β :b 3Β :t} {watch.digitΒ :t} }}}} Β  {def watch.path {lambda {:xΒ :yΒ :rΒ :eΒ :cΒ :iΒ :t} {path {@ d="{watch.arcΒ :xΒ :yΒ :r {watch.timeΒ :iΒ :t}}" fill="none" stroke=":c" stroke-width=":e"}} }} Β  {def watch.arc {lambda {:xΒ :yΒ :rΒ :t} {let { {:xΒ :x} {:yΒ :y} {:rΒ :r} {:start {watch.pol2carΒ :xΒ :yΒ :rΒ :t}} {:end {watch.pol2carΒ :xΒ :yΒ :r 0}} {:flag {if {<=Β :t 180} then 0 else 1}} } M {carΒ :start} {cdrΒ :start} AΒ :rΒ :r 0Β :flag 0 {carΒ :end} {cdrΒ :end} }}} Β  {def watch.time {lambda {:iΒ :t} {if {=Β :i 1} then {/ {* 360 {% {S.get {+Β :i 2}Β :t} 12}} 12} else {/ {* 360 {S.get {+Β :i 2}Β :t}} 60} }}} Β  {def watch.pol2car {lambda {:cxΒ :cyΒ :rΒ :t} {let { {:cxΒ :cx} {:cyΒ :cy} {:rΒ :r} {:T {* {-Β :t 90} {/ {PI} 180}}} } {cons {+Β :cx {*Β :r {cosΒ :T}}} {+Β :cy {*Β :r {sinΒ :T}}}} }}} Β  {def watch.digit {lambda {:t} {text {@ x="50%" y="48%" base-line="middle" text-anchor="middle" font-size="2.0em" stroke="#ccc"} {S.get 0Β :t}/{S.get 1Β :t}/{S.get 2Β :t} } {text {@ x="50%" y="58%" base-line="middle" text-anchor="middle" font-size="2.0em" stroke="#ccc"} {S.get 3Β :t}Β : {S.get 4Β :t}Β : {S.get 5Β :t} } }} Β  2) javascript code (for timing) Β  {script var update = function () { document.getElementById("watch").innerHTML = LAMBDATALK.eval_forms( "{watch.draw #f00 #0f0 #00f}" ) }; LAMBDATALK.DICT['watch.init'] = function () { setTimeout( update, 10); setInterval( update, 1000); return '' }; } Β 
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)
#UNIX_Shell
UNIX Shell
COLORS=(red white blue) Β  # to go from name to number, we make variables out of the color names # (e.g. the variable "$red" has value "1"). for (( i=0; i<${#COLORS[@]}; ++i )); do eval ${COLORS[i]}=$i done Β  # Make a random list function random_balls { local -i n="$1" local -i i local balls=() for (( i=0; i < n; ++i )); do balls+=("${COLORS[RANDOM%${#COLORS[@]}]}") done echo "${balls[@]}" } Β  # Test for Dutchness function dutch? { if (( $# < 2 )); then return 0 else local first="$1" shift if eval "(( $first > $1 ))"; then return 1 else dutch? "$@" fi fi } Β  # Sort into order function dutch { local -i lo=-1 hi=$# i=0 local a=("$@") while (( i < hi )); do case "${a[i]}" in red) let lo+=1 local t="${a[lo]}" a[lo]="${a[i]}" a[i]="$t" let i+=1 ;; white) let i+=1;; blue) let hi-=1 local t="${a[hi]}" a[hi]="${a[i]}" a[i]="$t" ;; esac done echo "${a[@]}" }
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
#Phix
Phix
-- -- demo\rosetta\draw_cuboid.exw -- ============================ -- -- Author Pete Lomax, August 2015 -- Translated from XPL0. -- Ported to pGUI August 2017 -- -- Press space to toggle auto-rotate on and off, -- cursor keys to rotate manually, and -- +/- to zoom in/out. -- -- Note this uses simple orthogonal projection; -- there is no perspective here! -- (For that see DrawRotatingCube.exw) -- with javascript_semantics include pGUI.e constant title = "Draw Cuboid" Ihandle dlg, canvas, hTimer cdCanvas cd_canvas -- arrays: 3D coordinates of vertices sequence x = {-2.0, +2.0, +2.0, -2.0, -2.0, +2.0, +2.0, -2.0}, y = {-1.5, -1.5, +1.5, +1.5, -1.5, -1.5, +1.5, +1.5}, z = {-1.0, -1.0, -1.0, -1.0, +1.0, +1.0, +1.0, +1.0} constant segments = {{1,2}, {2,3}, {3,4}, {4,1}, {5,6}, {6,7}, {7,8}, {8,5}, {1,5}, {2,6}, {3,7}, {4,8}} atom Size = 50.0, -- drawing size Sz = 0.008, -- tumbling speeds Sx =-0.013, -- "" Sy = 0.005, -- "" S = 2 procedure draw_cube(integer cx, cy) -- {cx,cy} is the centre point of the canvas integer farthest = largest(z,true) for s=1 to length(segments) do integer {va,vb} = segments[s], bNear = not find(farthest,segments[s]) cdCanvasSetForeground(cd_canvas, iff(bNear?CD_RED:CD_BLUE)) cdCanvasSetLineStyle(cd_canvas, iff(bNear?CD_CONTINUOUS:CD_DASHED)) atom x1 = x[va]*Size+cx, y1 = y[va]*Size+cy, x2 = x[vb]*Size+cx, y2 = y[vb]*Size+cy cdCanvasLine(cd_canvas,x1,y1,x2,y2) end for end procedure function canvas_action_cb(Ihandle canvas) cdCanvasActivate(cd_canvas) cdCanvasClear(cd_canvas) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") draw_cube(floor(w/2),floor(h/2)) cdCanvasFlush(cd_canvas) return IUP_DEFAULT end function function canvas_map_cb(Ihandle canvas) IupGLMakeCurrent(canvas) if platform()=JS then cd_canvas = cdCreateCanvas(CD_IUP, canvas) else atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cd_canvas = cdCreateCanvas(CD_GL, "10x10Β %g", {res}) end if -- cdCanvasSetBackground(cd_canvas, CD_PARCHMENT) cdCanvasSetBackground(cd_canvas, CD_BLACK) return IUP_DEFAULT end function function canvas_unmap_cb(Ihandle canvas) cdKillCanvas(cd_canvas) return IUP_DEFAULT end function function canvas_resize_cb(Ihandle /*canvas*/) integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cdCanvasSetAttribute(cd_canvas, "SIZE", "%dx%dΒ %g", {canvas_width, canvas_height, res}) return IUP_DEFAULT end function function key_cb(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE elsif c=K_UP then for i=1 to 8 do y[i] += z[i]*Sx*S -- rotate vertices in Y-Z plane z[i] -= y[i]*Sx*S end for elsif c=K_DOWN then for i=1 to 8 do y[i] -= z[i]*Sx*S -- rotate vertices in Y-Z plane z[i] += y[i]*Sx*S end for elsif c=K_LEFT then for i=1 to 8 do x[i] += z[i]*Sy*S -- rotate vertices in X-Z plane z[i] -= x[i]*Sy*S end for elsif c=K_RIGHT then for i=1 to 8 do x[i] -= z[i]*Sy*S -- rotate vertices in X-Z plane z[i] += x[i]*Sy*S end for elsif c='+' then Size = min(500,Size+5) elsif c='-' then Size = max( 10,Size-5) elsif c=' ' then IupSetInt(hTimer,"RUN",not IupGetInt(hTimer,"RUN")) end if IupUpdate(canvas) return IUP_CONTINUE end function function timer_cb(Ihandle /*ih*/) for i=1 to 8 do x[i] = x[i]+y[i]*Sz*S -- rotate vertices in X-Y plane y[i] = y[i]-x[i]*Sz*S y[i] = y[i]+z[i]*Sx*S -- rotate vertices in Y-Z plane z[i] = z[i]-y[i]*Sx*S x[i] = x[i]+z[i]*Sy*S -- rotate vertices in X-Z plane z[i] = z[i]-x[i]*Sy*S end for IupUpdate(canvas) return IUP_IGNORE end function procedure main() IupOpen() canvas = IupGLCanvas("RASTERSIZE=640x480") IupSetCallbacks(canvas, {"ACTION", Icallback("canvas_action_cb"), "MAP_CB", Icallback("canvas_map_cb"), "UNMAP_CB", Icallback("canvas_unmap_cb"), "RESIZE_CB", Icallback("canvas_resize_cb")}) -- dlg = IupDialog(IupVbox({canvas}),`TITLE="%s"`,{title}) dlg = IupDialog(canvas,`TITLE="%s"`,{title}) IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) hTimer = IupTimer(Icallback("timer_cb"), 40) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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.
#Forth
Forth
include turtle.fs Β  2 value dragon-step Β  : dragon ( depth dir -- ) over 0= if dragon-step fd 2drop exit then dup rt over 1- 45 recurse dup 2* lt over 1- -45 recurse rt dropΒ ; Β  home clear 10 45 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
#Logo
Logo
to sphereΒ :r cs perspective htΒ ;making the room ready to use repeat 180 [polystart circleΒ :r polyend down 1] polyview end
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#Liberty_BASIC
Liberty BASIC
Β  WindowWidth =120 WindowHeight =144 nomainwin Β  open "Clock" for graphics_nsb_nf as #clock #clock "trapclose [exit]" #clock "fill white" for angle =0 to 330 step 30 #clock "upΒ ; homeΒ ; northΒ ; turn "; angle #clock "go 40Β ; downΒ ; go 5" next angle Β  #clock "flush" Β  timer 1000, [display] wait Β  [display] ' called only when seconds have changed time$ =time$() seconds =val( right$( time$, 2)) ' delete the last drawn segment, if there is one if segId >2 then #clock "delsegment "; segId -1 ' center the turtle #clock "upΒ ; homeΒ ; downΒ ; north" ' erase each hand if its position has changed if oldSeconds <>seconds then #clock, "size 1Β ; color whiteΒ ; turn "; oldSeconds *6Β ; "Β ; go 38Β ; homeΒ ; color blackΒ ; north" : oldSeconds =seconds ' redraw all three hands, second hand first #clock "size 1Β ; turn "; seconds * 6Β ; "Β ; go 38" ' flush to end segment, then get the next segment id # #clock "flush" #clock "segment" input #clock, segId Β  wait Β  [exit] close #clock Β  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)
#VBScript
VBScript
Β  'Solution derived from http://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/. 'build an unsorted array with n elements Function build_unsort(n) flag = Array("red","white","blue") Set random = CreateObject("System.Random") Dim arr() ReDim arr(n) For i = 0 To n arr(i) = flag(random.Next_2(0,3)) Next build_unsort = arr End Function Β  'sort routine Function sort(arr) lo = 0 mi = 0 hi = UBound(arr) Do While mi <= hi Select Case arr(mi) Case "red" tmp = arr(lo) arr(lo) = arr(mi) arr(mi) = tmp lo = lo + 1 mi = mi + 1 Case "white" mi = mi + 1 Case "blue" tmp = arr(mi) arr(mi) = arr(hi) arr(hi) = tmp hi = hi - 1 End Select Loop sort = Join(arr,",") End Function Β  unsort = build_unsort(11) WScript.StdOut.Write "Unsorted: " & Join(unsort,",") WScript.StdOut.WriteLine WScript.StdOut.Write "Sorted: " & sort(unsort) WScript.StdOut.WriteLine Β 
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)
#Visual_FoxPro
Visual FoxPro
Β  CLOSE DATABASES ALL LOCAL lcCollate As String, i As Integer, n As Integer lcCollate = SET("Collate") SET COLLATE TO "Machine" *!* Colours table CREATE CURSOR colours (id I UNIQUE, colour V(5)) INSERT INTO colours VALUES (1, "Red") INSERT INTO colours VALUES (2, "White") INSERT INTO colours VALUES (3, "Blue") *!* Balls table CREATE CURSOR balls (colour I, rowid I AUTOINC) INDEX ON colour TAG colour SET ORDER TO 0 *!* Make sure there is at least 1 of each colour INSERT INTO balls (colour) VALUES(3) INSERT INTO balls (colour) VALUES(1) INSERT INTO balls (colour) VALUES(2) RAND(-1) && Initialise random number generator n = 24 FOR i = 4 TO n INSERT INTO balls (colour) VALUES (RanInt()) ENDFOR *!* Show unsorted SELECT bb.rowid, cc.colour FROM colours cc JOIN balls bb ON cc.id = bb.colour *!* Select by correct order SELECT bb.rowid, cc.colour FROM colours cc JOIN balls bb ON cc.id = bb.colourΒ ; ORDER BY cc.id INTO CURSOR dutchflag *!* Show sorted records BROWSE NOMODIFY IN SCREEN SET COLLATE TO lcCollate Β  FUNCTION RanInt() As Integer RETURN INT(3*RAND()) + 1 ENDFUNC Β 
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
#PicoLisp
PicoLisp
(de cuboid (DX DY DZ) (cubLine (inc DY) "+" DX "-" 0) (for I DY (cubLine (- DY I -1) "/" DX " " (dec I) "|") ) (cubLine 0 "+" DX "-" DY "|") (do (- (* 4 DZ) DY 2) (cubLine 0 "|" DX " " DY "|") ) (cubLine 0 "|" DX " " DY "+") (for I DY (cubLine 0 "|" DX " " (- DY I) "/") ) (cubLine 0 "+" DX "-" 0) ) Β  (de cubLine (N C DX D DY E) (space N) (prin C) (do (dec (* 9 DX)) (prin D)) (prin C) (space DY) (prinl E) )
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
#POV-Ray
POV-Ray
camera { perspective location <2.6,2.2,-4.2> look_at <0,-.5,0> aperture .05 blur_samples 100 variance 1/100000 focal_point <2,1,-2>} Β  light_source{< 60,20,-20> color rgb 2} Β  sky_sphere { pigment{ gradient z color_map{[0 rgb 0.3][.1 rgb <.7,.8,1>][1 rgb .2]} }} Β  box { <0,0,0> <3,2,4> texture { pigment{ agate } normal { checker } finish { reflection {0.20 metallic 0.2} } } translate <-1,-.5,-2> }
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#F.C5.8Drmul.C3.A6
Fōrmulæ
Const pi As Double = 4 * Atn(1) Dim Shared As Double angulo = 0 Β  Sub giro (grados As Double) angulo += grados*pi/180 End Sub Β  Sub dragon (longitud As Double, division As Integer, d As Double) If division = 0 Then Line - Step (Cos(angulo)*longitud, Sin(angulo)*longitud), Int(Rnd * 7) Else giro d*45 dragon longitud/1.4142136, division-1, 1 giro -d*90 dragon longitud/1.4142136, division-1, -1 giro d*45 End If End Sub Β  '--- Programa Principal --- Screen 12 Pset (150,180), 0 dragon 400, 12, 1 Bsave "Dragon_curve_FreeBASIC.bmp",0 Sleep
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Lua
Lua
require ("math") Β  shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'} Β  function normalize (vec) len = math.sqrt(vec[1]^2 + vec[2]^2 + vec[3]^2) return {vec[1]/len, vec[2]/len, vec[3]/len} end Β  light = normalize{30, 30, -50} Β  function dot (vec1, vec2) d = vec1[1]*vec2[1] + vec1[2]*vec2[2] + vec1[3]*vec2[3] return d < 0 and -d or 0 end Β  function draw_sphere (radius, k, ambient) for i = math.floor(-radius),-math.floor(-radius) do x = i + .5 local line = '' for j = math.floor(-2*radius),-math.floor(-2*radius) do y = j / 2 + .5 if x^2 + y^2 <= radius^2 then vec = normalize{x, y, math.sqrt(radius^2 - x^2 - y^2)} b = dot(light,vec) ^ k + ambient intensity = math.floor ((1 - b) * #shades) line = line .. (shades[intensity] or shades[1]) else line = line .. ' ' end end print (line) end end Β  draw_sphere (20, 4, 0.1) draw_sphere (10, 2, 0.4)
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
#Locomotive_Basic
Locomotive Basic
10 mode 1:defint a-y:deg 20 input "Current time (HH:MM)";t$ 30 h=val(mid$(t$,1,2)) 40 m=val(mid$(t$,4,2)) 50 cls 60 r=150:s=-1 70 ph=0:pm=0 80 origin 320,200 90 for a=0 to 360 step 6 100 if a mod 30>0 then z=.9 else z=.8 110 move z*r*sin(a),z*r*cos(a) 120 draw r*sin(a),r*cos(a) 130 next 140 move 0,r 150 for a=0 to 360 step 6 160 draw r*sin(a),r*cos(a) 170 next 180 every 50 gosub 220 190 ' ENDLESS_LOOP 200 goto 200 210 ' NEW_SEC 220 s=s+1 230 if s=60 then s=0:m=m+1 240 if m=60 then m=0:h=h+1 250 if h=24 then h=0 260 if s=0 then gosub 300 270 if s>0 then gosub 420 280 return 290 ' DRAW_ALL 300 locate 1,1 310 print using "##";h; 320 print ":"; 330 print using "##";m; 340 frame:move 0,0:draw .5*r*sin(ph),.5*r*cos(ph),0,0 350 frame:move 0,0:draw .7*r*sin(pm),.7*r*cos(pm),0,0 360 frame:move 0,0:draw .8*r*sin(6*59),.8*r*cos(6*59),0,0 370 pm=6*m 380 frame:move 0,0:draw .7*r*sin(pm),.7*r*cos(pm),1,0 390 ph=30*h+.5*m 400 frame:move 0,0:draw .5*r*sin(ph),.5*r*cos(ph),1,0 410 ' DRAW_SEC 420 a=6*s 430 ' uses "frame" and XOR ink mode for drawing -- requires BASIC 1.1 440 if a>0 then frame:move 0,0:draw .8*r*sin(a-6),.8*r*cos(a-6),3,1 450 frame:move 0,0:draw .8*r*sin(a),.8*r*cos(a),3,1 460 return
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)
#Wren
Wren
import "random" for Random import "/sort" for Sort Β  var colors = ["Red", "White", "Blue"] var colorMap = { "Red": 0, "White": 1, "Blue": 2 } var colorCmp = Fn.new { |c1, c2| (colorMap[c1] - colorMap[c2]).sign } var NUM_BALLS = 9 var r = Random.new() var balls = List.filled(NUM_BALLS, colors[0]) Β  while (true) { for (i in 0...NUM_BALLS) balls[i] = colors[r.int(3)] if (!Sort.isSorted(balls, colorCmp)) break } Β  System.print("Before sortingΒ :Β %(balls)") Sort.insertion(balls, colorCmp) System.print("After sorting Β :Β %(balls)")
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
#Processing
Processing
size(500, 500, P3D); background(0); // position translate(width/2, height/2, -width/2); rotateZ(radians(15)); rotateY(radians(-30)); rotateX(radians(-25)); // optional fill and lighting colors noStroke(); fill(192, 255, 192); pointLight(255, 255, 255, 400, -400, 400); // draw box box(200, 300, 400);
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.
#FreeBASIC
FreeBASIC
Const pi As Double = 4 * Atn(1) Dim Shared As Double angulo = 0 Β  Sub giro (grados As Double) angulo += grados*pi/180 End Sub Β  Sub dragon (longitud As Double, division As Integer, d As Double) If division = 0 Then Line - Step (Cos(angulo)*longitud, Sin(angulo)*longitud), Int(Rnd * 7) Else giro d*45 dragon longitud/1.4142136, division-1, 1 giro -d*90 dragon longitud/1.4142136, division-1, -1 giro d*45 End If End Sub Β  '--- Programa Principal --- Screen 12 Pset (150,180), 0 dragon 400, 12, 1 Bsave "Dragon_curve_FreeBASIC.bmp",0 Sleep
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#M2000_Interpreter
M2000 Interpreter
Β  Module CheckIt { Er$="Pset is a new statement" If Version<9.4 Then Error Er$ If Version=9.4 then If revision<26 then Error Er$ Form 60, 40 Cls 0 ' Black Gradient 0,1 Pen 14 ' Yellow Set FastΒ ! Refresh 500 Module Sphere (R as long, X0 as long, Y0 as long, fun){ R2 = R * R Def Long X, Y, D2 Let Scale=twipsx/R*13.5 For Y = -R To R step twipsx { Move X0-R, Y+Y0 For X = -R To R step twipsy { D2 = X **2 + Y **2 IF R2>D2 THEN Pset Fun(Max.Data(Min.Data((Sqrt(R2 - D2) - ( X + Y) / 2 )*Scale ,255),0)) Step twipsx } } } Blue=lambda (c)->{ c1=c/4+192 =Color(c,c,c1) } Blue1=lambda (c)->{ c1=c/4+Random(150,192) =Color(c,c,c1) } Mystery=lambda m=1 (c)->{ c1=c/4+m m+=10 if m>192 then m=1 =Color(c,c,c1) } Mystery2=lambda m=1, p=true (c)->{ c1=c/4+m if p then m+=10 Else m=-10 if m>192 then m-=10Β : p=false If m<0 then m+=10: p=true =Color(c,c,c1) } Buffer Alfa as byte*8 Trans =lambda Alfa (c) -> { Return Alfa, 0:=-point as long Return Alfa, 4:=-color(c,c, c/4+192) as long for i=0 to 2: Return Alfa, i:=(Eval(Alfa, i)+Eval(Alfa, i+4))/2: Next i =-Eval(Alfa, 0 as long) } Sphere 2400, 9000,7000, Blue Sphere 800, 6000, 7000, Blue1 Sphere 1200, 5000,5000, Mystery Sphere 1200, 10000,6000, Mystery2 Sphere 1200, 8000,5000, trans } Checkit Β 
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
#Lua
Lua
Dynamic[ClockGauge[], UpdateInterval -> 1]
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order: Β  red Β  Β  (top) Β  then white, Β  and Β  lastly blue Β  (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national 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)
#zkl
zkl
const RED=0, WHITE=1, BLUE=2; var BALLS=T(RED,WHITE,BLUE); fcn colorBalls(balls){ balls.apply(T("red","white","blue").get).concat(", "); } Β  reg balls, sortedBalls; do{ balls=(0).pump(12,List,fcn{ BALLS[(0).random(3)] }); // create list of 12 random balls sortedBalls=balls.sort(); // balls is read only, sort creates new list }while(balls==sortedBalls); // make sure sort does something println("Original ball order:\n", colorBalls(balls)); println("\nSorted ball order:\n", colorBalls(sortedBalls));
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
#Prolog
Prolog
cuboid(D1,D2,D3) :- W is D1 * 50, H is D2 * 50, D is D3 * 50, Β  new(C, window(cuboid)), Β  % compute the size of the window Width is W + ceiling(sqrt(H * 48)) + 50, Height is H + ceiling(sqrt(H * 48)) + 50, send(C, size, new(_,size(Width,Height))), Β  %compute the top-left corner of the front face of the cuboid PX is 25, PY is 25 + ceiling(sqrt(H * 48)), Β  % colors of the faces new(C1, colour(@default, 65535, 0, 0)), new(C2, colour(@default, 0, 65535, 0)), new(C3, colour(@default, 0, 0, 65535)), Β  % the front face new(B1, box(W, H)), send(B1, fill_pattern, C1), send(C, display,B1, point(PX, PY)), Β  % the top face new(B2, hpara(point(PX,PY), W, D, C2)), send(C, display, B2), Β  % the left face PX1 is PX + W, new(B3, vpara(point(PX1,PY), H, D, C3)), send(C, display, B3), Β  send(C, open). Β  Β  Β  :- pce_begin_class(hpara, path, "drawing of a horizontal parallelogram"). Β  initialise(P, Pos, Width, Height, Color) :-> send(P, send_super, initialise), send(P, append, Pos), H is ceiling(sqrt(Height * 48)), get(Pos, x, X), get(Pos, y, Y), X1 is X + H, Y1 is Y - H, send(P, append, point(X1, Y1)), X2 is X1 + Width, send(P, append, point(X2, Y1)), X3 is X2 - H, send(P, append, point(X3, Pos?y)), send(P, append, Pos), send(P, fill_pattern, Color). Β  :- pce_end_class. Β  :- pce_begin_class(vpara, path, "drawing of a vertical parallelogram"). Β  initialise(P, Pos, Height, Depth, Color) :-> send(P, send_super, initialise), send(P, append, Pos), H is ceiling(sqrt(Depth * 48)), get(Pos, x, X), get(Pos, y, Y), X1 is X + H, Y1 is Y - H, send(P, append, point(X1, Y1)), Y2 is Y1 + Height, send(P, append, point(X1, Y2)), Y3 is Y2 + H, send(P, append, point(X, Y3)), send(P, append, Pos), send(P, fill_pattern, Color). Β  :- pce_end_class.
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.
#Gnuplot
Gnuplot
# Return the position of the highest 1-bit in n. # The least significant bit is position 0. # For example n=13 is binary "1101" and the high bit is pos=3. # If n==0 then the return is 0. # Arranging the test as n>=2 avoids infinite recursion if n==NaN (any # comparison involving NaN is always false). # high_bit_pos(n) = (n>=2Β ? 1+high_bit_pos(int(n/2)) : 0) Β  # Return 0 or 1 for the bit at position "pos" in n. # pos==0 is the least significant bit. # bit(n,pos) = int(n / 2**pos) & 1 Β  # dragon(n) returns a complex number which is the position of the # dragon curve at integer point "n". n=0 is the first point and is at # the origin {0,0}. Then n=1 is at {1,0} which is x=1,y=0, etc. If n # is not an integer then the point returned is for int(n). # # The calculation goes by bits of n from high to low. Gnuplot doesn't # have iteration in functions, but can go recursively from # pos=high_bit_pos(n) down to pos=0, inclusive. # # mul() rotates by +90 degrees (complex "i") at bit transitions 0->1 # or 1->0. add() is a vector (i+1)**pos for each 1-bit, but turned by # factor "i" when in a "reversed" section of curve, which is when the # bit above is also a 1-bit. # dragon(n) = dragon_by_bits(n, high_bit_pos(n)) dragon_by_bits(n,pos) \ = (pos>=0Β ? add(n,pos) + mul(n,pos)*dragon_by_bits(n,pos-1) : 0) Β  add(n,pos) = (bit(n,pos)Β ? (bit(n,pos+1)Β ? {0,1} * {1,1}**pos \ : {1,1}**pos) \ : 0) mul(n,pos) = (bit(n,pos) == bit(n,pos+1)Β ? 1 : {0,1}) Β  # Plot the dragon curve from 0 to "length" with line segments. # "trange" and "samples" are set so the parameter t runs through # integers t=0 to t=length inclusive. # # Any trange works, it doesn't have to start at 0. But must have # enough "samples" that all integers t in the range are visited, # otherwise vertices in the curve would be missed. # length=256 set trange [0:length] set samples length+1 set parametric set key off plot real(dragon(t)),imag(dragon(t)) with lines
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
#Maple
Maple
plots[display](plottools[sphere](), axes = none, style = surface);
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Dynamic[ClockGauge[], UpdateInterval -> 1]
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order: Β  red Β  Β  (top) Β  then white, Β  and Β  lastly blue Β  (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national 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)
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET r$="Red": LET w$="White": LET b$="Blue" 20 LET c$="RWB" 30 DIM b(10) 40 PRINT "Random:" 50 FOR n=1 TO 10 60 LET b(n)=INT (RND*3)+1 70 PRINT VAL$ (c$(b(n))+"$");" "; 80 NEXT n 90 PRINT ''"Sorted:" 100 FOR i=1 TO 3 110 FOR j=1 TO 10 120 IF b(j)=i THEN PRINT VAL$ (c$(i)+"$");" "; 130 NEXT j 140 NEXT i
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
#Pure_Data
Pure Data
Β  #N canvas 1 51 450 300 10; #X obj 66 67 gemwin; #X obj 239 148 cuboid 2 3 4; #X obj 239 46 gemhead; #X obj 239 68 scale 0.3; #X msg 66 45 lighting 1 \, create \, 1; #X obj 61 118 gemhead; #X obj 61 140 world_light; #X msg 294 90 1; #X obj 239 90 t a b; #X obj 239 118 accumrotate; #X connect 2 0 3 0; #X connect 3 0 8 0; #X connect 4 0 0 0; #X connect 5 0 6 0; #X connect 7 0 9 1; #X connect 7 0 9 2; #X connect 7 0 9 3; #X connect 8 0 9 0; #X connect 8 1 7 0; #X connect 9 0 1 0; Β 
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.
#Go
Go
package main Β  import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) Β  // separation of the the two endpoints // make this a power of 2 for prettiest output const sep = 512 // depth of recursion. adjust as desired for different visual effects. const depth = 14 Β  var s = math.Sqrt2 / 2 var sin = []float64{0, s, 1, s, 0, -s, -1, -s} var cos = []float64{1, s, 0, -s, -1, -s, 0, s} var p = color.NRGBA{64, 192, 96, 255} var b *image.NRGBA Β  func main() { width := sep * 11 / 6 height := sep * 4 / 3 bounds := image.Rect(0, 0, width, height) b = image.NewNRGBA(bounds) draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src) dragon(14, 0, 1, sep, sep/2, sep*5/6) f, err := os.Create("dragon.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, b); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } } Β  func dragon(n, a, t int, d, x, y float64) { if n <= 1 { // Go packages used here do not have line drawing functions // so we implement a very simple line drawing algorithm here. // We take advantage of knowledge that we are always drawing // 45 degree diagonal lines. x1 := int(x + .5) y1 := int(y + .5) x2 := int(x + d*cos[a] + .5) y2 := int(y + d*sin[a] + .5) xInc := 1 if x1 > x2 { xInc = -1 } yInc := 1 if y1 > y2 { yInc = -1 } for x, y := x1, y1; ; x, y = x+xInc, y+yInc { b.Set(x, y, p) if x == x2 { break } } return } d *= s a1 := (a - t) & 7 a2 := (a + t) & 7 dragon(n-1, a1, 1, d, x, y) dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1]) }
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Graphics3D[Sphere[{0,0,0},1]]
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
#MATLAB_.2F_Octave
MATLAB / Octave
u = [0:360]*pi/180; while(1) s = mod(now*60*24,1)*2*pi; plot([0,sin(s)],[0,cos(s)],'-',sin(u),cos(u),'k-'); pause(1); 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
#PureBasic
PureBasic
Procedure Draw_a_Cuboid(Window, X,Y,Z) w=WindowWidth(Window) h=WindowHeight(Window) diag.f=1.9 If Not (w And h): ProcedureReturn: EndIf xscale.f = w/(x+z/diag)*0.98 yscale.f = h/(y+z/diag)*0.98 If xscale<yscale Scale.f = xscale Else Scale = yscale EndIf x*Scale: Y*Scale: Z*Scale CreateImage(0,w,h) If StartDrawing(ImageOutput(0)) c= RGB(250, 40, 5) Β  ;- Calculate the cones in the Cuboid xk = w/50 Β : yk = h/50 x0 = Z/2 + xkΒ : y0 = yk x1 = x0 + X Β : y1 = y0 x2 = xk Β : y2 = y0 + Z/2 x3 = x2 + X Β : y3 = y2 x4 = x2 Β : y4 = y2 + Y x5 = x4 + X Β : y5 = y4 x6 = x5 + Z/2Β : y6 = y5 - Z/2 Β  ;- Draw it LineXY(x0,y0,x1,y1,c) LineXY(x0,y0,x2,y2,c) LineXY(x2,y2,x3,y3,c) LineXY(x1,y1,x3,y3,c) LineXY(x2,y2,x4,y4,c) LineXY(x4,y4,x5,y5,c) LineXY(x5,y5,x4,y4,c) LineXY(x5,y5,x6,y6,c) LineXY(x5,y5,x3,y3,c) LineXY(x6,y6,x1,y1,c) Β  ;- Fill the areas FillArea(x,y,-1,RGB(255, 0, 0)) FillArea(x,y-z/2,-1,RGB(0, 0, 255)) FillArea(x+z/2,y,-1,RGB(0, 255, 0)) StopDrawing() EndIf ;- Update the graphic ImageGadget(0,0,0,w,h,ImageID(0)) EndProcedure Β  #WFlags = #PB_Window_SystemMenu|#PB_Window_SizeGadget #title = "PureBasic Cuboid" MyWin = OpenWindow(#PB_Any, 0, 0, 200, 250, #title, #WFlags) Β  Repeat WEvent = WaitWindowEvent() If WEvent = #PB_Event_SizeWindow Draw_a_Cuboid(MyWin, 2, 3, 4) EndIf Until WEvent = #PB_Event_CloseWindow Β  ;- Save the image? UsePNGImageEncoder() respons = MessageRequester("Question","Save the image?",#PB_MessageRequester_YesNo) If respons=#PB_MessageRequester_Yes SaveImage(0, SaveFileRequester("","","",0),#PB_ImagePlugin_PNG,9) EndIf
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.
#Gri
Gri
`Draw Dragon [ from .x1. .y1. to .x2. .y2. [level .level.] ]' Draw a dragon curve going from .x1. .y1. to .x2. .y2. with recursion depth .level. Β  The total number of line segments for the recursion is 2^level. level=0 is a straight line from x1,y1 to x2,y2. Β  The default for x1,y1 and x2,y2 is to draw horizontally from 0,0 to 1,0. { new .x1. .y1. .x2. .y2. .level. .x1. = \.word3. .y1. = \.word4. .x2. = \.word6. .y2. = \.word7. .level. = \.word9. Β  if {rpn \.words. 5 >=} .x2. = 1 .y2. = 0 end if if {rpn \.words. 7 >=} .level. = 6 end if Β  if {rpn 0 .level. <=} draw line from .x1. .y1. to .x2. .y2. else .level. = {rpn .level. 1 -} Β  # xmid,ymid is half way between x1,y1 and x2,y2 and up at # right angles away. # # xmid,ymid xmid = (x1+x2 + y2-y1)/2 # ^ ^ ymid = (x1-x2 + y1+y2)/2 # / . \ # / . \ # x1,y1 ........... x2,y2 # new .xmid. .ymid. .xmid. = {rpn .x1. .x2. + .y2. .y1. - + 2 /} .ymid. = {rpn .x1. .x2. - .y1. .y2. + + 2 /} Β  # The recursion is a level-1 dragon from x1,y1 to the midpoint # and the same from x2,y2 to the midpoint (the latter # effectively being a revered dragon.) # Draw Dragon from .x1. .y1. to .xmid. .ymid. level .level. Draw Dragon from .x2. .y2. to .xmid. .ymid. level .level. Β  delete .xmid. .ymid. end if Β  delete .x1. .y1. .x2. .y2. .level. } Β  # Dragon curve from 0,0 to 1,0 extends out by 1/3 at the ends, so # extents -0.5 to +1.5 for a bit of margin. The Y extent is the same # size 2 to make the graph square. set x axis -0.5 1.5 .25 set y axis -1 1 .25 Β  Draw 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
#MATLAB
MATLAB
figure; sphere
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
#MiniScript
MiniScript
// draw a clock hand, then copy it to an image gfx.clear color.clear gfx.fillPoly [[60,5], [64,10], [128,5], [64,0]], color.yellow handImg = gfx.getImage(0,0, 128,10) Β  clear // clear all displays Β  // prepare the face sprite faceImg = file.loadImage("/sys/pics/shapes/CircleThinInv.png") face = new Sprite face.image = faceImg face.scale = 2 face.x = 480; face.y = 320 display(4).sprites.push face Β  // prepare the hand sprite (from previously created image) hand = new Sprite hand.image = handImg hand.x = face.x; hand.y = face.y display(4).sprites.push hand Β  // main loop while true hand.rotation = 90 - floor(time)Β % 60 * 6 wait end while
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
#Python
Python
def _pr(t, x, y, z): txt = '\n'.join(''.join(t[(n,m)] for n in range(3+x+z)).rstrip() for m in reversed(range(3+y+z))) return txt Β  def cuboid(x,y,z): t = {(n,m):' ' for n in range(3+x+z) for m in range(3+y+z)} xrow = ['+'] + ['%i'Β % (iΒ % 10) for i in range(x)] + ['+'] for i,ch in enumerate(xrow): t[(i,0)] = t[(i,1+y)] = t[(1+z+i,2+y+z)] = ch if _debug: print(_pr(t, x, y, z)) ycol = ['+'] + ['%i'Β % (jΒ % 10) for j in range(y)] + ['+'] for j,ch in enumerate(ycol): t[(0,j)] = t[(x+1,j)] = t[(2+x+z,1+z+j)] = ch zdepth = ['+'] + ['%i'Β % (kΒ % 10) for k in range(z)] + ['+'] if _debug: print(_pr(t, x, y, z)) for k,ch in enumerate(zdepth): t[(k,1+y+k)] = t[(1+x+k,1+y+k)] = t[(1+x+k,k)] = ch Β  return _pr(t, x, y, z) Β  Β  _debug = False if __name__ == '__main__': for dim in ((2,3,4), (3,4,2), (4,2,3)): print("CUBOID%r"Β % (dim,), cuboid(*dim), sep='\n')
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.
#Haskell
Haskell
import Data.List import Graphics.Gnuplot.Simple Β  -- diamonds -- pl = [[0,1],[1,0]] Β  pl = [[0,0],[0,1]] r_90 = [[0,1],[-1,0]] Β  ip :: [Int] -> [Int] -> Int ip xs = sum . zipWith (*) xs matmul xss yss = map (\xs -> map (ip xs ). transpose $ yss) xss Β  vmoot xs = (xs++).map (zipWith (+) lxs). flip matmul r_90. map (flip (zipWith (-)) lxs) .reverse . init $ xs where lxs = last xs Β  dragoncurve = iterate vmoot pl
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
#Maxima
Maxima
/* Two solutions */ plot3d(1, [theta, 0,Β %pi], [phi, 0, 2 *Β %pi], [transform_xy, spherical_to_xyz], [grid, 30, 60], [box, false], [legend, false])$ Β  load(draw)$ draw3d(xu_grid=30, yv_grid=60, surface_hide=true, parametric_surface(cos(phi)*sin(theta), sin(phi)*sin(theta), cos(theta), theta, 0,Β %pi, phi, 0, 2 *Β %pi))$
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary Β  import javax.swing.Timer Β  -- .+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8 class RClockSwing public extends JFrame -- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . properties constant K_TITLE = String "Clock" isTrue = boolean (1 == 1) isFalse = \isTrue properties inheritable content = Container Β  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method RClockSwing() public this(K_TITLE) return Β  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method RClockSwing(title = String) public super(title) initFrame() return Β  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method initFrame() private content = getContentPane() content.setLayout(BorderLayout()) content.add(RClockSwing.Panel(), BorderLayout.CENTER) setResizable(isFalse) pack() return Β  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method main(args = String[]) public static clockFace = JFrame clockFace = RClockSwing() clockFace.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) clockFace.setVisible(isTrue) return Β  --..+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8 class RClockSwing.Panel shared extends JPanel implements ActionListener properties constant degrees450 = double Math.PI * 2.5 degrees006 = double Math.PI / 30.0 degrees030 = double degrees006 * 5 size = int 350 spacing = int 10 diameter = int size - 2 * spacing x1 = int diameter / 2 + spacing y1 = int diameter / 2 + spacing Β  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method Panel() public super() initPanel() return Β  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method initPanel() public setPreferredSize(Dimension(size, size)) setBackground(Color.WHITE) ptimer = Timer(1000, this) ptimer.start() return Β  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method paintComponent(gr = Graphics) public super.paintComponent(gr) g2 = Graphics2D gr g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) gr.setColor(Color.black) gr.drawOval(spacing, spacing, diameter, diameter) cdate = Calendar.getInstance() hours = cdate.get(Calendar.HOUR) minutes = cdate.get(Calendar.MINUTE) seconds = cdate.get(Calendar.SECOND) angle = double degrees450 - (degrees006 * seconds) drawHand(gr, angle, int (diameter / 2 - 10), Color.red) minsecs = double (minutes + seconds / 60.0) angle = degrees450 - (degrees006 * minsecs) drawHand(gr, angle, int (diameter / 3), Color.black) hourmins = double (hours + minsecs / 60.0) angle = degrees450 - (degrees030 * hourmins) drawHand(gr, angle, int (diameter / 4), Color.black) return Β  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method drawHand(gr = Graphics, angle = double, radius = int, color = Color) public x2 = x1 + (int (radius * Math.cos(angle))) y2 = y1 + (int (radius * Math.sin(-angle))) gr.setColor(color) gr.drawLine(x1, y1, x2, y2) return Β  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method actionPerformed(evt = ActionEvent) public repaint() return Β 
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
#Racket
Racket
#lang racket/gui (require sgl/gl) Β  ; Macro to delimit and automatically end glBegin - glEnd contexts. (define-syntax-rule (gl-begin-end Vertex-Mode statement ...) (let () (glBegin Vertex-Mode) statement ... (glEnd))) Β  (define (resize w h) (glViewport 0 0 w h)) Β  (define (draw-opengl x y z) (glClearColor 0.0 0.0 0.0 0.0) (glEnable GL_DEPTH_TEST) (glClear GL_COLOR_BUFFER_BIT) (glClear GL_DEPTH_BUFFER_BIT) Β  (define max-axis (add1 (max x y z))) Β  (glMatrixMode GL_PROJECTION) (glLoadIdentity) (glOrtho (/ (- max-axis) 2) max-axis (/ (- max-axis) 2) max-axis (/ (- max-axis) 2) max-axis) (glMatrixMode GL_MODELVIEW) (glLoadIdentity) (glRotatef -45 1.0 0.0 0.0) (glRotatef 45 0.0 1.0 0.0) Β  (gl-begin-end GL_QUADS (glColor3f 0 0 1) (glVertex3d x 0.0 z) (glVertex3d x y z) (glVertex3d x y 0.0) (glVertex3d x 0.0 0.0)) (gl-begin-end GL_QUADS (glColor3f 1 0 0) (glVertex3d x 0.0 0.0) (glVertex3d x y 0.0) (glVertex3d 0.0 y 0.0) (glVertex3d 0.0 0.0 0.0)) (gl-begin-end GL_QUADS (glColor3f 0 1 0) (glVertex3d x y 0.0) (glVertex3d x y z) (glVertex3d 0.0 y z) (glVertex3d 0.0 y 0.0))) Β  (define my-canvas% (class* canvas% () (inherit with-gl-context swap-gl-buffers) (init-field (x 2) (y 3) (z 4)) Β  (define/override (on-paint) (with-gl-context (lambda () (draw-opengl x y z) (swap-gl-buffers)))) Β  (define/override (on-size width height) (with-gl-context (lambda () (resize width height)))) Β  (super-instantiate () (style '(gl))))) Β  (define win (new frame% (label "Racket Draw a cuboid") (min-width 300) (min-height 300))) (define gl (new my-canvas% (parent win) (x 2) (y 3) (z 4))) Β  (send win show #t)
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.
#HicEst
HicEst
CHARACTER dragon Β  1 DLG(NameEdit=orders,DNum, Button='&OK', TItle=dragon) ! input orders WINDOW(WINdowhandle=wh, Height=1, X=1, TItle='Dragon curves up to order '//orders) Β  IF( LEN(dragon) < 2^orders) ALLOCATE(dragon, 2^orders) Β  AXIS(WINdowhandle=wh, Xaxis=2048, Yaxis=2048) ! 2048: black, linear, noGrid, noScales dragon = ' ' NorthEastSouthWest = 0 x = 0 y = 1 LINE(PenUp, Color=1, x=0, y=0, x=x, y=y) last = 1 Β  DO order = 1, orders changeRtoL = LEN_TRIM(dragon) + 1 + (LEN_TRIM(dragon) + 1)/2 dragon = TRIM(dragon) // 'R' // TRIM(dragon) IF(changeRtoL > 2) dragon(changeRtoL) = 'L' Β  DO last = last, LEN_TRIM(dragon) NorthEastSouthWest = MOD( NorthEastSouthWest-2*(dragon(last)=='L')+5, 4 ) x = x + (NorthEastSouthWest==1) - (NorthEastSouthWest==3) y = y + (NorthEastSouthWest==0) - (NorthEastSouthWest==2) LINE(Color=order, X=x, Y=y) ENDDO ENDDO GOTO 1 ! this is to stimulate a discussion Β  END
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
#Nim
Nim
import math Β  type Point = tuple[x,y,z: float] Β  const shades = ".:!*oe&#%@" Β  proc normalize(x, y, z: float): Point = let len = sqrt(x*x + y*y + z*z) (x / len, y / len, z / len) Β  proc dot(a, b: Point): float = result = max(0, - a.x*b.x - a.y*b.y - a.z*b.z) Β  let light = normalize(30.0, 30.0, -50.0) Β  proc drawSphere(r: int; k, ambient: float) = for i in -r .. r: let x = i.float + 0.5 for j in -2*r .. 2*r: let y = j.float / 2.0 + 0.5 if x*x + y*y <= float r*r: let v = normalize(x, y, sqrt(float(r*r) - x*x - y*y)) b = pow(dot(light, v), k) + ambient i = clamp(int((1.0 - b) * shades.high.float), 0, shades.high) stdout.write shades[i] else: stdout.write ' ' stdout.write "\n" Β  drawSphere 20, 4.0, 0.1 drawSphere 10, 2.0, 0.4
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
#Nim
Nim
import times, os Β  const t = ["β‘Žβ’‰β’΅","β €β’Ίβ €","β Šβ ‰β‘±","β Šβ£‰β‘±","⒀⠔⑇","⣏⣉⑉","β£Žβ£‰β‘","β Šβ’‰β ","β’Žβ£‰β‘±","β‘Žβ ‰β’±","β €β Άβ €"] b = ["⒗⣁⑸","β’€β£Έβ£€","⣔⣉⣀","β’„β£€β‘Έ","⠉⠉⑏","β’„β£€β‘Έ","β’‡β£€β‘Έ","⒰⠁⠀","β’‡β£€β‘Έ","β’ˆβ£‰β‘Ή","β €β Ά "] Β  while true: let x = getClockStr() stdout.write "\e[H\e[J" for c in x: stdout.write t[c.ord - '0'.ord] echo "" for c in x: stdout.write b[c.ord - '0'.ord] echo "" sleep 1000
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
#Raku
Raku
sub braille-graphics (%a) { my ($ylo, $yhi, $xlo, $xhi); for %a.keys -> $y { $ylo min= +$y; $yhi max= +$y; for %a{$y}.keys -> $x { $xlo min= +$x; $xhi max= +$x; } } Β  for $ylo, $ylo + 4 ...^ * > $yhi -> \y { for $xlo, $xlo + 2 ...^ * > $xhi -> \x { my $cell = 0x2800; $cell += 1 if %a{y + 0}{x + 0}; $cell += 2 if %a{y + 1}{x + 0}; $cell += 4 if %a{y + 2}{x + 0}; $cell += 8 if %a{y + 0}{x + 1}; $cell += 16 if %a{y + 1}{x + 1}; $cell += 32 if %a{y + 2}{x + 1}; $cell += 64 if %a{y + 3}{x + 0}; $cell += 128 if %a{y + 3}{x + 1}; print chr($cell); } print "\n"; } } Β  sub cuboid ( [$x, $y, $z] ) { my \x = $x * 4; my \y = $y * 4; my \z = $z * 2; my %t; sub horz ($X, $Y) { %t{$Y }{$X + $_} = True for 0 .. x } sub vert ($X, $Y) { %t{$Y + $_}{$X } = True for 0 .. y } sub diag ($X, $Y) { %t{$Y - $_}{$X + $_} = True for 0 .. z } Β  horz(0, z); horz(z, 0); horz( 0, z+y); vert(0, z); vert(x, z); vert(z+x, 0); diag(0, z); diag(x, z); diag( x, z+y); Β  say "[$x, $y, $z]"; braille-graphics %t; } Β  cuboid $_ for [2,3,4], [3,4,2], [4,2,3], [1,1,1], [8,1,1], [1,8,1], [1,1,8];
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.
#Icon_and_Unicon
Icon and Unicon
link linddraw,wopen Β  procedure main() gener := 12 # generations w := h := 800 # window size rewrite := table() # L rewrite rules rewrite["X"] := "X+YF+" rewrite["Y"] := "-FX-Y" every (C := '') ++:= !!rewrite every /rewrite[c := !C] := c # map all rule characters Β  WOpen("size=" || w || "," || h, "dx=" || (w / 2), "dy=" || (h / 2)) | stop("*** cannot open window") WAttrib("fg=blue") Β  linddraw(0, 0, "FX", rewrite, 5, 90.0, gener, 0) # x,y, axiom, rules, length, angle, generations, delay Β  WriteImage("dragon-unicon" || ".gif") # save the image WDone() end
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
#Ol
Ol
Β  (import (lib gl)) (import (OpenGL version-1-0)) Β  ; init (glClearColor 0.3 0.3 0.3 1) (glPolygonMode GL_FRONT_AND_BACK GL_FILL) Β  (define quadric (gluNewQuadric)) Β  ; draw loop (gl:set-renderer (lambda (mouse) (glClear GL_COLOR_BUFFER_BIT) Β  (glColor3f 0.7 0.7 0.7) (gluSphere quadric 0.4 32 10) )) Β 
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
#OCaml
OCaml
#!/usr/bin/env ocaml #load "unix.cma" #load "graphics.cma" open Graphics Β  let pi = 4.0 *. atan 1.0 let angle v max = float v /. max *. 2.0 *. pi Β  let () = open_graph ""; set_window_title "OCaml Clock"; resize_window 256 256; auto_synchronize false; let w = size_x () and h = size_y () in let rec loop () = clear_graph (); Β  let point radius r a = let x = int_of_float (radius *. sin a) and y = int_of_float (radius *. cos a) in fill_circle (w/2+x) (h/2+y) r; in set_color (rgb 192 192 192); point 84.0 8 0.0; point 84.0 8 (angle 90 360.0); point 84.0 8 (angle 180 360.0); point 84.0 8 (angle 270 360.0); set_color (rgb 224 224 224); point 84.0 6 (angle 30 360.0); point 84.0 6 (angle 60 360.0); point 84.0 6 (angle 120 360.0); point 84.0 6 (angle 150 360.0); point 84.0 6 (angle 210 360.0); point 84.0 6 (angle 240 360.0); point 84.0 6 (angle 300 360.0); point 84.0 6 (angle 330 360.0); Β  set_line_width 9; set_color (rgb 192 192 192); draw_circle (w/2) (h/2) 100; Β  let tm = Unix.localtime (Unix.gettimeofday ()) in let sec = angle tm.Unix.tm_sec 60.0 in let min = angle tm.Unix.tm_min 60.0 in let hour = angle (tm.Unix.tm_hour * 60 + tm.Unix.tm_min) (24.0 *. 60.0) in let hour = hour *. 2.0 in Β  let hand t radius width color = let x = int_of_float (radius *. sin t) and y = int_of_float (radius *. cos t) in set_line_width width; set_color color; moveto (w/2) (h/2); rlineto x y; in hand sec 90.0 2 (rgb 0 128 255); hand min 82.0 4 (rgb 0 0 128); hand hour 72.0 6 (rgb 255 0 128); Β  synchronize (); Unix.sleep 1; loop () in try loop () with _ -> close_graph ()
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
#Retro
Retro
3 elements d h w Β  : spaces ( n- ) &space timesΒ ; : --- ( - ) '+ putc @w 2 * [ '- putc ] times '+ putcΒ ; :Β ? ( n- ) @h <> [ '| ] [ '+ ] ifΒ ; : slice ( n- ) '/ putc @w 2 * spaces '/ putc @d swap - dup spacesΒ ? putc crΒ ; : |...|/ ( - ) @h [ '| putc @w 2 * spaces '| putc 1- spaces '/ putc cr ] iterdΒ ; : face ( - ) --- @w 1+ spaces '/ putc cr |...|/ --- crΒ ; Β  : cuboid ( whd- ) Β !dΒ !hΒ !w cr @d 1+ spaces --- cr @d [ dup spaces slice ] iterd faceΒ ; Β  2 3 4 cuboid
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.
#J
J
require 'plot' start=: 0 0,: 1 0 step=: ],{: +"1 (0 _1,: 1 0) +/ .*~ |.@}: -"1 {: plot <"1 |: step^:13 start
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
#Openscad
Openscad
// This will produce a sphere of radius 5 sphere(5);
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
#ooRexx
ooRexx
/* REXX --------------------------------------------------------------- * 09.02.2014 Walter Pachl with a little, well considerable, help from * a friend (Mark Miesfeld) * 1) downstripped an example contained in the ooRexx distribution * 2) constructed the squares for seconds, minutes, and hours * 3) constructed second-, minute- and hour hand * 5) removed lots of unnecessary code (courtesy mark Miesfeld again) * 6) painted the background white * 7) display date as well as time as text * 21.02.2014 Attempts to add a minimize icon keep failing *--------------------------------------------------------------------*/ d = .drawDlg~new if d~initCode <> 0 then do say 'The Draw dialog was not created correctly. Aborting.' return d~initCode end d~execute("SHOWTOP") return 0 Β  ::requires "ooDialog.cls" ::requires 'rxmath' library Β  ::class 'drawDlg' subclass UserDialog Β  ::attribute interrupted unguarded Β  ::method init expose walterFont Β  forward class (super) continue -- colornames: -- 1 dark red 7 light grey 13 red -- 2 dark green 8 pale green 14 light green -- 3 dark yellow 9 light blue 15 yellow -- 4 dark blue 10 white 16 blue -- 5 purple 11 grey 17 pink -- 6 blue grey 12 dark grey 18 turquoise Β  self~interrupted = .true Β  -- Create a font to write the nice big letters and digits opts = .directory~new opts~weight = 700 walterFont = self~createFontEx("Arial",14,opts) Β  -- if \self~createcenter(200, 230,"Walter's Clock","MINIMIZEBOX", ,"System",14) then if \self~createcenter(200, 230,"Walter's Clock",,,"System",14) then self~initCode = 1 -- self~connectDraw(100, "clock", .true) Β  ::method defineDialog -- self~createPushButton(/*IDC_PB_DRAW*/100,0,0,240,200,"NOTAB OWNERDRAW") -- The drawing surface. -- self~createPushButton(/*IDC_PB_DRAW*/100,0,0,240,180,"DISABLED NOTAB") -- better.Β ??? self~createPushButton(/*IDC_PB_DRAW*/100,0,0,200,200,"DISABLED NOTAB") -- better.Β ??? Β  self~createPushButton(IDCANCEL,160,212, 35, 12,,"&Cancel") Β  ::method initDialog unguarded expose x y dc myPen change change = 0 x = self~factorx y = self~factory dc = self~getButtonDC(100) --+ myPen = self~createPen(1,'solid',0) t = .TimeSpan~fromMicroSeconds(500000) -- .5 seconds msg = .Message~new(self, 'clock') alrm = .Alarm~new(t, msg) Β  ::method interrupt unguarded Β  self~interrupted = .true Β  ::method cancel unguarded -- Stop the drawing program and quit. expose x y self~hide self~interrupted = .true return self~cancel:super Β  ::method leaving unguarded -- Best place to clean up resources expose dc myPen walterFont Β  --+ self~deleteObject(myPen) self~freeButtonDC(/*IDC_PB_DRAW*/100,dc) self~deleteFont(walterFont) Β  ::method clock unguarded /* draw individual pixels */ expose x y dc myPen change walterFont -- Say 'clock started' mx = trunc(20*x); my = trunc(20*y); size = 400 Β  --+ curPen = self~objectToDC(dc, myPen) Β  -- Select the nice big letters and digits into the device context to use to -- to write with: curFont = self~fontToDC(dc, walterFont) Β  -- Create a white brush and select it into the device to paint with. whiteBrush = self~createBrush(10) curBrush = self~objectToDC(dc, whiteBrush) Β  -- Paint the drawing area surface with the white brush -- self~rectangle(dc, 1, 1, 500, 450, 'FILL') -- how does that relate to the 180 aboveΒ ??? -- self~rectangle(dc, 1, 1, 480, 400, 'FILL') -- how does that relate to the 180 aboveΒ ??? Β  button = self~newPushButton(100) clRect = button~clientRect; -- Say clRect self~rectangle(dc, clRect~left+10, clRect~top+10, clRect~right-10, clRect~bottom-10, 'FILL') Β  self~transparentText(dc) self~writeDirect(dc, 55,20*y,"Walter's Clock") self~writeDirect(dc,236, 56,'12') self~writeDirect(dc,428,220,'3') self~writeDirect(dc,245,375,'6') self~writeDirect(dc, 60,220,'9') self~opaqueText(dc) Β  -- These 5 lines just have the effect of showing "Walter's Clock" first -- for a brief instant before the other drawing shows. If you want it all -- to show at once, then remove this. /* if change \= 2 then do call msSleep 1000 change = 2 end */ self~interrupted = .false Β  sec=0 min=0 hhh=0 fact=rxCalcPi()/180 Parse Value '-1 -1 -1 -1' With hho mmo sso hopo Β  do dalpha=0 To 359 by 30 until self~interrupted alpha = dalpha*fact zxa=trunc(250+124*rxCalcSin(alpha,,'R')) zya=trunc(230-110*rxCalcCos(alpha,,'R')) hhh=right(hhh,2,0) hhh.hhh=right(zxa,3) right(zya,3) hhh+=1 self~draw_square(dc,zxa,zya,3,5) self~draw_square(dc,zxa,zya,2,10) End Do a=0 To 59 a=right(a,2,0) alpha=a*6*fact sin.a=rxCalcSin(alpha,,'R') cos.a=rxCalcCos(alpha,,'R') sin.0mhh.a=sin.a cos.0mhh.a=cos.a End Do hoi=0 To 12*60-1 hoi=right(hoi,3,0) alpha=(hoi/2)*fact sin.0hoh.hoi=rxCalcSin(alpha,,'R') cos.0hoh.hoi=rxCalcCos(alpha,,'R') End do dalpha=0 To 359 by 6 until self~interrupted alpha = dalpha*fact zxa=trunc(250+165*rxCalcSin(alpha,,'R')) zya=trunc(230-140*rxCalcCos(alpha,,'R')) sec=right(min,2,0) sec.sec=right(zxa,3) right(zya,3) sec+=1 self~draw_square(dc,zxa,zya,3,5) self~draw_square(dc,zxa,zya,2,10) zxa=trunc(250+140*rxCalcSin(alpha,,'R')) zya=trunc(230-125*rxCalcCos(alpha,,'R')) min=right(min,2,0) min.min=right(zxa,3) right(zya,3) --Call lineout 'pos.xxx',right(min,2) 'min='min.min min+=1 self~draw_square(dc,zxa,zya,3,5) self~draw_square(dc,zxa,zya,2,10) End Β  do dalpha=0 by 6 until self~interrupted alpha=dalpha*fact zxa=trunc(250+165*rxCalcSin(alpha,,'R')) zya=trunc(230-140*rxCalcCos(alpha,,'R')) time=time() parse Var time hh ':' mm ':' ss If hh>=12 Then hh=right(hh-12,2,0) self~writeDirect(dc, 355,40,time) date=date() self~writeDirect(dc, 355,60,date) If hh<>hho Then Do If hho>=0 Then Do Parse Var hhh.hho hx hy self~draw_square(dc,hx,hy,2,10) End Parse Var hhh.hh hx hy self~draw_square(dc,hx,hy,2,2) End If mm<>mmo Then Do If mmo>=0 Then Do Parse Var min.mmo mx my self~draw_square(dc,mx,my,2,10) End Parse Var min.mm mx my self~draw_square(dc,mx,my,2,2) End If ss<>sso Then Do If sso>=0 Then Do Parse Var sec.sso sx sy self~draw_square(dc,sx,sy,2,10) self~draw_second_hand(dc,sso,sin.,cos.,10) End Parse Var sec.ss sx sy self~draw_square(dc,sx,sy,2, 2) self~draw_second_hand(dc,ss,sin.,cos.,16) self~draw_square(dc,250,230,4,1) hop=right(hh*60+mm,3,0) self~draw_hour_hand(dc,hop,sin.,cos.,13) self~draw_minute_hand(dc,mm,sin.,cos.,14) End If mm<>mmo Then Do If hopo>=0 Then self~draw_hour_hand(dc,hopo,sin.,cos.,10) hop=right(hh*60+mm,3,0) self~draw_hour_hand(dc,hop,sin.,cos.,13) hopo=hop If mmo>=0 Then self~draw_minute_hand(dc,mmo,sin.,cos.,10) self~draw_minute_hand(dc,mm,sin.,cos.,14) End self~draw_square(dc,250,230,4,1) hho=hh mmo=mm sso=ss Β  call msSleep 100 self~pause end -- if kpix >= size then kpix = 1 Β  self~interrupted = .true --+ self~objectToDC(dc, curPen) self~objectToDC(dc, curBrush) Β  ::method pause j = msSleep(10) Β  ::method draw_square Use Arg dc, x, y, d, c Do zx=x-d to x+d Do zy=y-d to y+d self~drawPixel(dc, zx, zy, c) End End Β  ::method draw_hour_hand Use Arg dc, hp, sin., cos., color Do p=1 To 60 zx=trunc(250+p*sin.0hoh.hp) zy=trunc(230-p*cos.0hoh.hp) self~draw_square(dc, zx, zy, 2, color) End Β  ::method draw_minute_hand Use Arg dc, mp, sin., cos., color Do p=1 To 80 zx=trunc(250+p*sin.0mhh.mp) zy=trunc(230-p*cos.0mhh.mp) self~draw_square(dc, zx, zy, 1, color) End Β  ::method draw_second_hand Use Arg dc, sp, sin., cos., color Do p=1 To 113 zx=trunc(250+p*sin.sp) zy=trunc(230-p*(140/165)*cos.sp) self~draw_square(dc, zx, zy, 0, color) End Β  ::method quot Parse Arg x,y If y=0 Then Return '??' Else Return x/y
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
#REXX
REXX
/*REXX program displays a cuboid (dimensions, if specified, must be positive integers).*/ parse arg x y z indent . /*x, y, z: dimensions and indentation.*/ x=p(x 2); y=p(y 3); z=p(z 4); in=p(indent 0) /*use the defaults if not specified. */ pad=left('', in) /*indentation must be non-negative. */ call show y+2 , , "+-" do j=1 for y; call show y-j+2, j-1, "/ |" Β ; end /*j*/ call show , y , "+-|" do z-1; call show , y , "| |" Β ; end /*z-1*/ call show , y , "| +" do j=1 for y; call show , y-j, "| /" Β ; end /*j*/ call show , , "+-" exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ p: return word( arg(1), 1) /*pick the first number or word in list*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: parse arg #,$,a 2 b 3 c 4 /*get the arguments (or parts thereof).*/ say pad || right(a, p(# 1) )copies(b, 4*x)a || right(c, p($ 0) + 1); return
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#Java
Java
import java.awt.Color; import java.awt.Graphics; import java.util.*; import javax.swing.JFrame; Β  public class DragonCurve extends JFrame { Β  private List<Integer> turns; private double startingAngle, side; Β  public DragonCurve(int iter) { super("Dragon Curve"); setBounds(100, 100, 800, 600); setDefaultCloseOperation(EXIT_ON_CLOSE); turns = getSequence(iter); startingAngle = -iter * (Math.PI / 4); side = 400 / Math.pow(2, iter / 2.); } Β  public List<Integer> getSequence(int iterations) { List<Integer> turnSequence = new ArrayList<Integer>(); for (int i = 0; i < iterations; i++) { List<Integer> copy = new ArrayList<Integer>(turnSequence); Collections.reverse(copy); turnSequence.add(1); for (Integer turn : copy) { turnSequence.add(-turn); } } return turnSequence; } Β  @Override public void paint(Graphics g) { g.setColor(Color.BLACK); double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int) (Math.cos(angle) * side); int y2 = y1 + (int) (Math.sin(angle) * side); g.drawLine(x1, y1, x2, y2); x1 = x2; y1 = y2; for (Integer turn : turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int) (Math.cos(angle) * side); y2 = y1 + (int) (Math.sin(angle) * side); g.drawLine(x1, y1, x2, y2); x1 = x2; y1 = y2; } } Β  public static void main(String[] args) { new DragonCurve(14).setVisible(true); } }
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
#OxygenBasic
OxygenBasic
Β  Β % Title "Sphere" '% Animated Β % PlaceCentral uses ConsoleG Β  sub main ======== cls 0.0, 0.2, 0.7 shading scale 10 pushstate GoldMaterial.act go sphere popstate end sub Β  EndScript Β 
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
#Perl
Perl
use utf8; # interpret source code as UTF8 binmode STDOUT, ':utf8'; # allow printing wide chars without warning $|++; # disable output buffering Β  my ($rows, $cols) = split /\s+/, `stty size`; my $x = int($rows / 2 - 1); my $y = int($cols / 2 - 16); Β  my @chars = map {[ /(...)/g ]} ("β”Œβ”€β” ╷╢─┐╢─┐╷ β•·β”Œβ”€β•΄β”Œβ”€β•΄β•Άβ”€β”β”Œβ”€β”β”Œβ”€β” ", "β”‚ β”‚ β”‚β”Œβ”€β”˜β•Άβ”€β”€β””β”€β”€β””β”€β”β”œβ”€β” β”‚β”œβ”€β”€β””β”€β”€Β : ", "β””β”€β”˜ β•΅β””β”€β•΄β•Άβ”€β”˜ β•΅β•Άβ”€β”˜β””β”€β”˜ β•΅β””β”€β”˜β•Άβ”€β”˜ "); Β  while (1) { my @indices = map { ord($_) - ord('0') } split //, sprintf("%02d:%02d:%02d", (localtime(time))[2,1,0]); Β  clear(); for (0 .. $#chars) { position($x + $_, $y); print "@{$chars[$_]}[@indices]"; } position(1, 1); Β  sleep 1; } Β  sub clear { print "\e[H\e[J" } sub position { printf "\e[%d;%dH", shift, shift }
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
#Ring
Ring
Β  # ProjectΒ : Draw a cuboid Β  load "guilib.ring" Β  paint = null Β  new qapp { win1 = new qwidget() { setwindowtitle("Draw a cuboid") setgeometry(100,100,500,600) label1 = new qlabel(win1) { setgeometry(10,10,400,400) settext("") } new qpushbutton(win1) { setgeometry(150,500,100,30) settext("draw") setclickevent("draw()") } show() } exec() } Β  func draw p1 = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(1) } paint = new qpainter() { begin(p1) setpen(pen) Β  color = new qcolor() color.setrgb(255,0,0,255) mybrush = new qbrush() {setstyle(1) setcolor(color)} setbrush(mybrush) paint.drawPolygon([[200,200],[300,200],[300,100],[200,100]], 0) color = new qcolor() color.setrgb(0,255,0,255) mybrush = new qbrush() {setstyle(1) setcolor(color)} setbrush(mybrush) paint.drawPolygon([[200,100],[250,50],[350,50],[300,100]], 0) color = new qcolor() color.setrgb(0, 0, 255,255) mybrush = new qbrush() {setstyle(1) setcolor(color)} setbrush(mybrush) paint.drawPolygon([[350,50],[350,150],[300,200],[300,100]], 0) Β  endpaint() } label1 { setpicture(p1) show() } return Β 
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#JavaScript
JavaScript
var DRAGON = (function () { // MATRIX MATH // ----------- Β  var matrix = { mult: function ( m, v ) { return [ m[0][0] * v[0] + m[0][1] * v[1], m[1][0] * v[0] + m[1][1] * v[1] ]; }, Β  minus: function ( a, b ) { return [ a[0]-b[0], a[1]-b[1] ]; }, Β  plus: function ( a, b ) { return [ a[0]+b[0], a[1]+b[1] ]; } }; Β  Β  // SVG STUFF // --------- Β  // Turn a pair of points into an SVG path like "M1 1L2 2". var toSVGpath = function (a, b) { // type system fail return "M" + a[0] + " " + a[1] + "L" + b[0] + " " + b[1]; }; Β  Β  // DRAGON MAKING // ------------- Β  // Make a dragon with a better fractal algorithm var fractalMakeDragon = function (svgid, ptA, ptC, state, lr, interval) { Β  // make a new <path> var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute( "class", "dragon"); path.setAttribute( "d", toSVGpath(ptA, ptC) ); Β  // append the new path to the existing <svg> var svg = document.getElementById(svgid); // call could be eliminated svg.appendChild(path); Β  // if we have more iterations to go... if (state > 1) { Β  // make a new point, either to the left or right var growNewPoint = function (ptA, ptC, lr) { var left = [[ 1/2,-1/2 ], [ 1/2, 1/2 ]]; Β  var right = [[ 1/2, 1/2 ], [-1/2, 1/2 ]]; Β  return matrix.plus(ptA, matrix.mult( lr ? left : right, matrix.minus(ptC, ptA) )); }; Β  var ptB = growNewPoint(ptA, ptC, lr, state); Β  // then recurse using each new line, one left, one right var recurse = function () { // when recursing deeper, delete this svg path svg.removeChild(path); Β  // then invoke again for new pair, decrementing the state fractalMakeDragon(svgid, ptB, ptA, state-1, lr, interval); fractalMakeDragon(svgid, ptB, ptC, state-1, lr, interval); }; Β  window.setTimeout(recurse, interval); } }; Β  Β  // Export these functions // ---------------------- return { fractal: fractalMakeDragon Β  // ARGUMENTS // --------- // svgid id of <svg> element // ptA first point [x,y] (from top left) // ptC second point [x,y] // state number indicating how many steps to recurse // lr true/false to make new point on left or right Β  // CONFIG // ------ // CSS rules should be made for the following // svg#fractal // svg path.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
#Pascal
Pascal
use strict; use warnings; Β  my $x = my $y = 255; $x |= 1; # must be odd my $depth = 255; Β  my $light = Vector->new(rand, rand, rand)->normalized; Β  print "P2\n$x $y\n$depth\n"; Β  my ($r, $ambient) = (($x - 1)/2, 0); my ($r2) = $r ** 2; { for my $x (-$r .. $r) { my $x2 = $x**2; for my $y (-$r .. $r) { my $y2 = $y**2; my $pixel = 0; if ($x2 + $y2 < $r2) { my $v = Vector->new($x, $y, sqrt($r2 - $x2 - $y2))->normalized; my $I = $light . $v + $ambient; $I = $I < 0 ? 0 : $I > 1 ? 1 : $I; $pixel = int($I * $depth); } print $pixel; print $y == $r ? "\n" : " "; } } } Β  package Vector { sub new { my $class = shift; bless ref($_[0]) eq 'Array' ? $_[0] : [ @_ ], $class; } sub normalized { my $this = shift; my $norm = sqrt($this . $this); ref($this)->new( map $_/$norm, @$this ); } use overload q{.} => sub { my ($a, $b) = @_; my $sum = 0; for (0 .. @$a - 1) { $sum += $a->[$_] * $b->[$_] } return $sum; }, q{""} => sub { sprintf "Vector:[%s]", join ' ', @{shift()} }; }
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
#Phix
Phix
-- -- demo\rosetta\Clock.exw -- ====================== -- with javascript_semantics include pGUI.e Ihandle dlg, canvas, hTimer cdCanvas cd_canvas procedure draw_hand(atom degrees, atom r, baseangle, baselen, cx, cy) atom a = PI-(degrees+90)*PI/180, -- tip x1 = cos(a)*(r), y1 = sin(a)*(r), -- base x2 = cos(a+PI-baseangle)*baselen, y2 = sin(a+PI-baseangle)*baselen, x3 = cos(a+PI+baseangle)*baselen, y3 = sin(a+PI+baseangle)*baselen cdCanvasSetLineWidth(cd_canvas,1) cdCanvasLine(cd_canvas,cx+x1,cy+y1,cx+x2,cy+y2) cdCanvasLine(cd_canvas,cx+x2,cy+y2,cx+x3,cy+y3) cdCanvasLine(cd_canvas,cx+x3,cy+y3,cx+x1,cy+y1) cdCanvasBegin(cd_canvas,CD_FILL) cdCanvasVertex(cd_canvas,cx+x1,cy+y1) cdCanvasVertex(cd_canvas,cx+x2,cy+y2) cdCanvasVertex(cd_canvas,cx+x3,cy+y3) cdCanvasEnd(cd_canvas) end procedure procedure draw_clock(atom cx, cy, d) atom w = 2+floor(d/25) cdCanvasFont(cd_canvas, "Helvetica", CD_PLAIN, floor(d/15)) cdCanvasSetLineWidth(cd_canvas, w) cdCanvasArc(cd_canvas, cx, cy, d, d, 0, 360) d -= w+8 w = 1+floor(d/50) for i=6 to 360 by 6 do integer h = remainder(i,30)=0 cdCanvasSetLineWidth(cd_canvas, max(floor(w*(1+h)/3),1)) atom a = PI-(i+90)*PI/180, x1 = cos(a)*d/2, x2 = cos(a)*(d/2-w*(2+h)*.66), y1 = sin(a)*d/2, y2 = sin(a)*(d/2-w*(2+h)*.66) cdCanvasLine(cd_canvas, cx+x1, cy+y1, cx+x2, cy+y2) if h then x1 = cos(a)*(d/2-w*4.5) y1 = sin(a)*(d/2-w*4.5) cdCanvasText(cd_canvas,cx+x1,cy+y1,sprintf("%d",{i/30})) end if end for atom {hour,mins,secs,msecs} = date(true)[DT_HOUR..DT_MSEC] if IupGetInt(hTimer,"TIME")<1000 then -- (if showing once a second, always land on exact -- seconds, ie completely ignore msecs, otherwise -- show smooth running (fractional) second hand.) secs += msecs/1000 end if mins += secs/60 hour += mins/60 atom r = d/2 draw_hand(hour*360/12,r-w*9,0.3,d/20,cx,cy) draw_hand(mins*360/60,r-w*2,0.2,d/16,cx,cy) cdCanvasSetForeground(cd_canvas, CD_RED) draw_hand(secs*360/60,r-w*2,0.05,d/16,cx,cy) cdCanvasSetForeground(cd_canvas, CD_BLACK) end procedure function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE"), r = floor(min(width,height)*0.9), cx = floor(width/2), cy = floor(height/2) cdCanvasActivate(cd_canvas) cdCanvasClear(cd_canvas) draw_clock(cx,cy,r) cdCanvasFlush(cd_canvas) return IUP_DEFAULT end function function timer_cb(Ihandle /*ih*/) IupUpdate(canvas) return IUP_IGNORE end function function map_cb(Ihandle ih) IupGLMakeCurrent(canvas) if platform()=JS then cd_canvas = cdCreateCanvas(CD_IUP, canvas) else atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cd_canvas = cdCreateCanvas(CD_GL, "10x10Β %g", {res}) end if cdCanvasSetBackground(cd_canvas, CD_WHITE) cdCanvasSetForeground(cd_canvas, CD_BLACK) cdCanvasSetTextAlignment(cd_canvas, CD_CENTER) return IUP_DEFAULT end function function canvas_resize_cb(Ihandle /*canvas*/) integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cdCanvasSetAttribute(cd_canvas, "SIZE", "%dx%dΒ %g", {canvas_width, canvas_height, res}) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupGLCanvas("RASTERSIZE=350x350") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb"), "RESIZE_CB", Icallback("canvas_resize_cb")}) hTimer = IupTimer(Icallback("timer_cb"), 40) -- smooth secs -- hTimer = IupTimer(Icallback("timer_cb"), 1000) -- tick seconds dlg = IupDialog(canvas, "TITLE=Clock") IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()