task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#zkl
zkl
fcn egyptianDivmod(dividend,divisor){ table:=[0..].pump(List, 'wrap(n){ // (2^n,divisor*2^n) r:=T( p:=(2).pow(n), s:=divisor*p); (s<=dividend) and r or Void.Stop }); accumulator:=0; foreach p2,d in (table.reverse()){ if(dividend>=d){ accumulator+=p2; dividend-=d; } } return(accumulator,dividend); }
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics Imports System.Text   Module Module1   Function Gcd(a As BigInteger, b As BigInteger) As BigInteger If b = 0 Then If a < 0 Then Return -a Else Return a End If Else Return Gcd(b, a Mod b) End If End Function   Function Lcm(a As BigInteger, b As BigInteger) As BigInteger Return a / Gcd(a, b) * b End Function   Public Class Rational Dim num As BigInteger Dim den As BigInteger   Public Sub New(n As BigInteger, d As BigInteger) Dim c = Gcd(n, d) num = n / c den = d / c If den < 0 Then num = -num den = -den End If End Sub   Public Sub New(n As BigInteger) num = n den = 1 End Sub   Public Function Numerator() As BigInteger Return num End Function   Public Function Denominator() As BigInteger Return den End Function   Public Overrides Function ToString() As String If den = 1 Then Return num.ToString() Else Return String.Format("{0}/{1}", num, den) End If End Function   'Arithmetic operators Public Shared Operator +(lhs As Rational, rhs As Rational) As Rational Return New Rational(lhs.num * rhs.den + rhs.num * lhs.den, lhs.den * rhs.den) End Operator   Public Shared Operator -(lhs As Rational, rhs As Rational) As Rational Return New Rational(lhs.num * rhs.den - rhs.num * lhs.den, lhs.den * rhs.den) End Operator   'Comparison operators   Public Shared Operator =(lhs As Rational, rhs As Rational) As Boolean Return lhs.num = rhs.num AndAlso lhs.den = rhs.den End Operator   Public Shared Operator <>(lhs As Rational, rhs As Rational) As Boolean Return lhs.num <> rhs.num OrElse lhs.den <> rhs.den End Operator   Public Shared Operator <(lhs As Rational, rhs As Rational) As Boolean 'a/b < c/d 'ad < bc Dim ad = lhs.num * rhs.den Dim bc = lhs.den * rhs.num Return ad < bc End Operator   Public Shared Operator >(lhs As Rational, rhs As Rational) As Boolean 'a/b > c/d 'ad > bc Dim ad = lhs.num * rhs.den Dim bc = lhs.den * rhs.num Return ad > bc End Operator   Public Shared Operator <=(lhs As Rational, rhs As Rational) As Boolean Return lhs < rhs OrElse lhs = rhs End Operator   Public Shared Operator >=(lhs As Rational, rhs As Rational) As Boolean Return lhs > rhs OrElse lhs = rhs End Operator   'Conversion operators Public Shared Widening Operator CType(ByVal bi As BigInteger) As Rational Return New Rational(bi) End Operator Public Shared Widening Operator CType(ByVal lo As Long) As Rational Return New Rational(lo) End Operator End Class   Function Egyptian(r As Rational) As List(Of Rational) Dim result As New List(Of Rational)   If r >= 1 Then If r.Denominator() = 1 Then result.Add(r) result.Add(New Rational(0)) Return result End If result.Add(New Rational(r.Numerator / r.Denominator)) r -= result(0) End If   Dim modFunc = Function(m As BigInteger, n As BigInteger) Return ((m Mod n) + n) Mod n End Function   While r.Numerator() <> 1 Dim q = (r.Denominator() + r.Numerator() - 1) / r.Numerator() result.Add(New Rational(1, q)) r = New Rational(modFunc(-r.Denominator(), r.Numerator()), r.Denominator * q) End While   result.Add(r) Return result End Function   Function FormatList(Of T)(col As List(Of T)) As String Dim iter = col.GetEnumerator() Dim sb As New StringBuilder   sb.Append("[") If iter.MoveNext() Then sb.Append(iter.Current) End If While iter.MoveNext() sb.Append(", ") sb.Append(iter.Current) End While sb.Append("]") Return sb.ToString() End Function   Sub Main() Dim rs = {New Rational(43, 48), New Rational(5, 121), New Rational(2014, 59)} For Each r In rs Console.WriteLine("{0} => {1}", r, FormatList(Egyptian(r))) Next   Dim lenMax As Tuple(Of ULong, Rational) = Tuple.Create(0UL, New Rational(0)) Dim denomMax As Tuple(Of BigInteger, Rational) = Tuple.Create(New BigInteger(0), New Rational(0))   Dim query = (From i In Enumerable.Range(1, 100) From j In Enumerable.Range(1, 100) Select New Rational(i, j)).Distinct().ToList() For Each r In query Dim e = Egyptian(r) Dim eLen As ULong = e.Count Dim eDenom = e.Last().Denominator() If eLen > lenMax.Item1 Then lenMax = Tuple.Create(eLen, r) End If If eDenom > denomMax.Item1 Then denomMax = Tuple.Create(eDenom, r) End If Next   Console.WriteLine("Term max is {0} with {1} terms", lenMax.Item2, lenMax.Item1) Dim dStr = denomMax.Item1.ToString() Console.WriteLine("Denominator max is {0} with {1} digits {2}...{3}", denomMax.Item2, dStr.Length, dStr.Substring(0, 5), dStr.Substring(dStr.Length - 5, 5)) End Sub   End Module
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func Halve(N); \Return half of N int N; return N>>1;   func Double(N); \Return N doubled int N; return N<<1;   func IsEven(N); \Return 'true' if N is an even number int N; return (N&1)=0;   func EthiopianMul(A, B); \Multiply A times B using Ethiopian method int A, B; int I, J, S, Left(100), Right(100); [Left(0):= A; Right(0):= B; \1. write numbers to be multiplied I:= 1; \2. repeatedly halve number on left repeat A:= Halve(A); Left(I):= A; I:= I+1; until A=1; J:= 1; \3. repeatedly double number on right repeat B:= Double(B); Right(J):= B; J:= J+1; until J=I; \stop where left column = 1 for J:= 0 to I-1 do \4. discard right value if left is even if IsEven(Left(J)) then Right(J):= 0; S:= 0; \5. sum remaining values on right for J:= 0 to I-1 do S:= S + Right(J); for J:= 0 to I-1 do \show this insanity [IntOut(0, Left(J)); ChOut(0, 9\tab\); IntOut(0, Right(J)); CrLf(0)]; Text(0, " -------- "); return S; \sum = product ];   int Product; [Product:= EthiopianMul(17, 34); ChOut(0, 9); IntOut(0, Product); CrLf(0); CrLf(0); Product:= EthiopianMul(1234, 5678); ChOut(0, 9); IntOut(0, Product); CrLf(0); ]
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Zig
Zig
  const stdout = @import("std").io.getStdOut().outStream();   pub fn factorial(comptime Num: type, n: i8) ?Num { return if (@typeInfo(Num) != .Int) @compileError("factorial called with num-integral type: " ++ @typeName(Num)) else if (n < 0) null else calc: { var i: i8 = 1; var fac: Num = 1; while (i <= n) : (i += 1) { if (@mulWithOverflow(Num, fac, i, &fac)) break :calc null; } else break :calc fac; }; }   pub fn main() !void { try stdout.print("-1! = {}\n", .{factorial(i32, -1)}); try stdout.print("0! = {}\n", .{factorial(i32, 0)}); try stdout.print("5! = {}\n", .{factorial(i32, 5)}); try stdout.print("33!(64 bit) = {}\n", .{factorial(i64, 33)}); // not vailid i64 factorial try stdout.print("33! = {}\n", .{factorial(i128, 33)}); // biggest facorial possible try stdout.print("34! = {}\n", .{factorial(i128, 34)}); // will overflow }  
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Tcl
Tcl
# How to handle an incoming new connection proc acceptEcho {chan host port} { puts "opened connection from $host:$port" fconfigure $chan -blocking 0 -buffering line -translation crlf fileevent $chan readable [list echo $chan $host $port] }   # How to handle an incoming message on a connection proc echo {chan host port} { if {[gets $chan line] >= 0} { puts $chan $line } elseif {[eof $chan]} { close $chan puts "closed connection from $host:$port" } # Other conditions causing a short read need no action }   # Make the server socket and wait for connections socket -server acceptEcho -myaddr localhost 12321 vwait forever
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#PostScript
PostScript
%!PS-Adobe-3.0 %%BoundingBox: 0 0 400 400   /ed { exch def } def /roty { dup sin /s ed cos /c ed [[c 0 s neg] [0 1 0] [s 0 c]] } def /rotz { dup sin /s ed cos /c ed [[c s neg 0] [s c 0] [0 0 1]] } def /dot { /a ed /b ed a 0 get b 0 get mul a 1 get b 1 get mul a 2 get b 2 get mul add add } def   /mmul { /v ed [exch {v dot} forall] } def /transall { /m ed [exch {m exch mmul}forall] } def   /vt [[1 1 1] [-1 1 1] [1 -1 1] [-1 -1 1] [1 1 -1] [-1 1 -1] [1 -1 -1] [-1 -1 -1]] -45 roty transall 2 sqrt 1 atan rotz transall def   /xy { exch get {} forall pop } def /page { /a ed /v vt a roty transall def 0 setlinewidth 100 100 scale 2 2 translate /edge { v xy moveto v xy lineto stroke } def   0 1 2 3 4 5 6 7 0 2 1 3 4 6 5 7 0 4 1 5 2 6 3 7 1 1 12 { pop edge } for showpage } def   0 {3.2 add dup page } loop %%EOF
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Sidef
Sidef
var m1 = [[3,1,4],[1,5,9]] var m2 = [[2,7,1],[8,2,2]]   say ":: Matrix-matrix operations" say (m1 ~W+ m2) say (m1 ~W- m2) say (m1 ~W* m2) say (m1 ~W/ m2) say (m1 ~W// m2) say (m1 ~W** m2) say (m1 ~W% m2)   say "\n:: Matrix-scalar operations" say (m1 ~S+ 42) say (m1 ~S- 42) say (m1 ~S/ 42) say (m1 ~S** 10) # ...   say "\n:: Scalar-matrix operations" say (m1 ~RS+ 42) say (m1 ~RS- 42) say (m1 ~RS/ 42) say (m1 ~RS** 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.
#Asymptote
Asymptote
DIM SHARED angle AS DOUBLE   SUB turn (degrees AS DOUBLE) angle = angle + degrees*3.14159265/180 END SUB   SUB forward (length AS DOUBLE) LINE - STEP (COS(angle)*length, SIN(angle)*length), 7 END SUB   SUB dragon (length AS DOUBLE, split AS INTEGER, d AS DOUBLE) IF split=0 THEN forward length ELSE turn d*45 dragon length/1.4142136, split-1, 1 turn -d*90 dragon length/1.4142136, split-1, -1 turn d*45 END IF END SUB   ' Main program   SCREEN 12 angle = 0 PSET (150,180), 0 dragon 400, 12, 1 SLEEP
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Common_Lisp
Common Lisp
;; * Loading the cairo bindings (eval-when (:compile-toplevel :load-toplevel) (ql:quickload '("cl-cairo2" "cl-cairo2-xlib")))   ;; * The package definition (defpackage :sphere (:use :common-lisp :cl-cairo2)) (in-package :sphere)   (defparameter *context* nil) (defparameter *size* 400) (defparameter *middle* (/ *size* 2))   ;; Opening a display and draw a sphere (let ((width *size*) (height *size*)) ;; Draw to a X-Window (setf *context* (create-xlib-image-context width height :window-name "Sphere")) ;; Clear the whole canvas with gray (rectangle 0 0 width height) (set-source-rgb 127 127 127) (fill-path) ;; Draw a the sphere as circa with a radial pattern (with-patterns ((pat (create-radial-pattern (* 0.9 *middle*) (* 0.8 *middle*) (* 0.2 *middle*) (* 0.8 *middle*) (* 0.8 *middle*) *middle*))) (pattern-add-color-stop-rgba pat 0 1 1 1 1) (pattern-add-color-stop-rgba pat 1 0 0 0 1) (set-source pat) (arc *middle* *middle* 180 0 (* 2 pi)) (fill-path)) ;; Draw to a png file (with-png-file ("sphere.png" :rgb24 width height) ;; Clear the whole canvas with gray (rectangle 0 0 width height) (set-source-rgb 127 127 127) (fill-path) ;; Draw a the sphere as circa with a radial pattern (with-patterns ((pat (create-radial-pattern (* 0.9 *middle*) (* 0.8 *middle*) (* 0.2 *middle*) (* 0.8 *middle*) (* 0.8 *middle*) *middle*))) (pattern-add-color-stop-rgba pat 0 1 1 1 1) (pattern-add-color-stop-rgba pat 1 0 0 0 1) (set-source pat) (arc *middle* *middle* 180 0 (* 2 pi)) (fill-path))))
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Perl
Perl
my %node_model = ( data => 'something', prev => undef, next => undef, );   sub insert { my ($anchor, $newlink) = @_; $newlink->{next} = $anchor->{next}; $newlink->{prev} = $anchor; $newlink->{next}->{prev} = $newlink; $anchor->{next} = $newlink; }   # create the list {A,B} my $node_a = { %node_model }; my $node_b = { %node_model };   $node_a->{next} = $node_b; $node_b->{prev} = $node_a;   # insert element C into a list {A,B}, between elements A and B. my $node_c = { %node_model }; insert($node_a, $node_c);
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Phix
Phix
enum NEXT,PREV,DATA constant empty_dll = {{1,1}} sequence dll = deep_copy(empty_dll) procedure insert_after(object data, integer pos=1) integer prv = dll[pos][PREV] dll = append(dll,{pos,prv,data}) if prv!=0 then dll[prv][NEXT] = length(dll) end if dll[pos][PREV] = length(dll) end procedure insert_after("ONE") insert_after("TWO") insert_after("THREE") ?dll
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h>   #define PI 3.14159265 const char * shades = " .:-*ca&#%@";   /* distance of (x, y) from line segment (0, 0)->(x0, y0) */ double dist(double x, double y, double x0, double y0) { double l = (x * x0 + y * y0) / (x0 * x0 + y0 * y0);   if (l > 1) { x -= x0; y -= y0; } else if (l >= 0) { x -= l * x0; y -= l * y0; } return sqrt(x * x + y * y); }   enum { sec = 0, min, hur }; // for subscripts   void draw(int size) { # define for_i for(int i = 0; i < size; i++) # define for_j for(int j = 0; j < size * 2; j++)   double angle, cx = size / 2.; double sx[3], sy[3], sw[3]; double fade[] = { 1, .35, .35 }; /* opacity of each arm */ struct timeval tv; struct tm *t;   /* set width of each arm */ sw[sec] = size * .02; sw[min] = size * .03; sw[hur] = size * .05;   every_second: gettimeofday(&tv, 0); t = localtime(&tv.tv_sec);   angle = t->tm_sec * PI / 30; sy[sec] = -cx * cos(angle); sx[sec] = cx * sin(angle);   angle = (t->tm_min + t->tm_sec / 60.) / 30 * PI; sy[min] = -cx * cos(angle) * .8; sx[min] = cx * sin(angle) * .8;   angle = (t->tm_hour + t->tm_min / 60.) / 6 * PI; sy[hur] = -cx * cos(angle) * .6; sx[hur] = cx * sin(angle) * .6;   printf("\033[s"); /* save cursor position */ for_i { printf("\033[%d;0H", i); /* goto row i, col 0 */ double y = i - cx; for_j { double x = (j - 2 * cx) / 2;   int pix = 0; /* calcs how far the "pixel" is from each arm and set * shade, with some anti-aliasing. It's ghetto, but much * easier than a real scanline conversion. */ for (int k = hur; k >= sec; k--) { double d = dist(x, y, sx[k], sy[k]); if (d < sw[k] - .5) pix = 10 * fade[k]; else if (d < sw[k] + .5) pix = (5 + (sw[k] - d) * 10) * fade[k]; } putchar(shades[pix]); } } printf("\033[u"); /* restore cursor pos so you can bg the job -- value unclear */   fflush(stdout); sleep(1); /* sleep 1 can at times miss a second, but will catch up next update */ goto every_second; }   int main(int argc, char *argv[]) { int s; if (argc <= 1 || (s = atoi(argv[1])) <= 0) s = 20; draw(s); return 0; }
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Lua
Lua
-------------- -- TRAVERSAL: -------------- List.iterateForward = function(self) local function iter(self, node) if node then return node.next else return self.head end end return iter, self, nil end List.iterateReverse = function(self) local function iter(self, node) if node then return node.prev else return self.tail end end return iter, self, nil end   --------- -- TEST: --------- local list = List() for i = 1, 5 do list:insertTail(i) end io.write("Forward: ") for node in list:iterateForward() do io.write(node.data..",") end print() io.write("Reverse: ") for node in list:iterateReverse() do io.write(node.data..",") end print()
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Liberty_BASIC
Liberty BASIC
  struct block,nxt as ulong,prev as ulong,nm as char[20],age as long'Our structure of the blocks in our list.   global hHeap global hFirst global hLast global blockCount global blockSize blockSize=len(block.struct)     call Init if hHeap=0 then print "Error occured! Could not create heap, exiting..." end end if   FirstUser=New("David",20) notImportant=New("Jessica",35) notImportant=New("Joey",38) MiddleUser=New("Jack",56) notImportant=New("Amy",17) notImportant=New("Bob",28) LastUser=New("Kenny",56)     print "-Traversing the list forwards"   hCurrent=hFirst while hCurrent<>0 print tab(2);dechex$(hCurrent);" ";Block.name$(hCurrent);" ";Block.age(hCurrent) hCurrent=Block.next(hCurrent) wend   print print "-Deleting first, middle, and last person."   call Delete FirstUser'1 call Delete MiddleUser'2 call Delete LastUser'3   print print "-Traversing the list backwards" hCurrent=hLast while hCurrent<>0 print tab(2);dechex$(hCurrent);" ";Block.name$(hCurrent);" ";Block.age(hCurrent) hCurrent=Block.prev(hCurrent) wend   call Uninit   end     function Block.next(hBlock) calldll #kernel32,"RtlMoveMemory",block as struct,hBlock as ulong,blockSize as long,ret as void Block.next=block.nxt.struct end function   function Block.prev(hBlock) calldll #kernel32,"RtlMoveMemory",block as struct,hBlock as ulong,blockSize as long,ret as void Block.prev=block.prev.struct end function   function Block.age(hBlock) calldll #kernel32,"RtlMoveMemory",block as struct,hBlock as ulong,blockSize as long,ret as void Block.age=block.age.struct end function   function Block.name$(hBlock) calldll #kernel32,"RtlMoveMemory",block as struct,hBlock as ulong,blockSize as long,ret as void Block.name$=block.nm.struct end function   sub Block.age hBlock,age calldll #kernel32,"RtlMoveMemory",block as struct,hBlock as ulong,blockSize as long,ret as void block.age.struct=age calldll #kernel32,"RtlMoveMemory",hBlock as ulong,block as struct,blockSize as long,ret as void end sub   sub Block.name hBlock,name$ calldll #kernel32,"RtlMoveMemory",block as struct,hBlock as ulong,blockSize as long,ret as void block.nm.struct=name$ calldll #kernel32,"RtlMoveMemory",hBlock as ulong,block as struct,blockSize as long,ret as void end sub   sub Block.next hBlock,nxt calldll #kernel32,"RtlMoveMemory",block as struct,hBlock as ulong,blockSize as long,ret as void block.nxt.struct=nxt calldll #kernel32,"RtlMoveMemory",hBlock as ulong,block as struct,blockSize as long,ret as void end sub   sub Block.prev hBlock,prev calldll #kernel32,"RtlMoveMemory",block as struct,hBlock as ulong,blockSize as long,ret as void block.prev.struct=prev calldll #kernel32,"RtlMoveMemory",hBlock as ulong,block as struct,blockSize as long,ret as void end sub   function New(name$,age) calldll #kernel32,"HeapAlloc",hHeap as ulong,_HEAP_ZERO_MEMORY as ulong,blockSize as long,New as ulong if New<>0 then blockCount=blockCount+1 if hFirst=0 then hFirst=New hLast=New else call Block.next hLast,New call Block.prev New,hLast hLast=New end if call Block.name New,name$ call Block.age New,age end if end function   sub Delete hBlock if hBlock<>0 then blockCount=blockCount-1 if blockCount=0 then hFirst=0 hLast=0 else if hBlock=hFirst then hFirst=Block.next(hBlock) call Block.prev hFirst,0 else if hBlock=hLast then hLast=Block.prev(hBlock) call Block.next hLast,0 else call Block.next Block.prev(hBlock),Block.next(hBlock) call Block.prev Block.next(hBlock),Block.prev(hBlock) end if end if end if calldll #kernel32,"HeapFree",hHeap as ulong,0 as long,hBlock as ulong,ret as void end if end sub     sub Init calldll #kernel32,"HeapCreate",0 as long,10000 as long,0 as long,hHeap as ulong end sub   sub Uninit calldll #kernel32,"HeapDestroy",hHeap as ulong,ret as void end sub  
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
CreateDataStructure["DoublyLinkedList"]
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Modula-2
Modula-2
TYPE Link = POINTER TO LinkRcd; LinkRcd = RECORD Prev, Next: Link; Data: INTEGER END;
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Nim
Nim
type Node[T] = ref TNode[T]   TNode[T] = object next, prev: Node[T] data: T
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Oberon-2
Oberon-2
  MODULE Box; TYPE Object* = POINTER TO ObjectDesc; ObjectDesc* = (* ABSTRACT *) RECORD END;   (* ... *) END Box.   MODULE Collections; TYPE Node* = POINTER TO NodeDesc; NodeDesc* = (* ABSTRACT *) RECORD prev-,next-: Node; value-: Box.Object; END;   (* ... *) END Collections.  
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)
#Haskell
Haskell
import Data.List (sort) import System.Random (randomRIO) import System.IO.Unsafe (unsafePerformIO)   data Color = Red | White | Blue deriving (Show, Eq, Ord, Enum)   dutch :: [Color] -> [Color] dutch = sort   isDutch :: [Color] -> Bool isDutch x = x == dutch x   randomBalls :: Int -> [Color] randomBalls 0 = [] randomBalls n = toEnum (unsafePerformIO (randomRIO (fromEnum Red, fromEnum Blue))) : randomBalls (n - 1)   main :: IO () main = do let a = randomBalls 20 case isDutch a of True -> putStrLn $ "The random sequence " ++ show a ++ " is already in the order of the Dutch national flag!" False -> do putStrLn $ "The starting random sequence is " ++ show a ++ "\n" putStrLn $ "The ordered sequence is " ++ show (dutch 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
#FreeBASIC
FreeBASIC
#include once "GL/gl.bi" #include once "GL/glu.bi"   dim rquad as single   screen 18, 16, , 2   glViewport 0, 0, 640, 480 '' Reset The Current Viewport glMatrixMode GL_PROJECTION '' Select The Projection Matrix glLoadIdentity '' Reset The Projection Matrix gluPerspective 45.0, 640.0/480.0, 0.1, 100.0 '' Calculate The Aspect Ratio Of The Window glMatrixMode GL_MODELVIEW '' Select The Modelview Matrix glLoadIdentity '' Reset The Modelview Matrix glShadeModel GL_SMOOTH '' Enable Smooth Shading glClearColor 0.0, 0.0, 0.0, 0.5 '' Black Background glClearDepth 1.0 '' Depth Buffer Setup glEnable GL_DEPTH_TEST '' Enables Depth Testing glDepthFunc GL_LEQUAL '' The Type Of Depth Testing To Do glHint GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST '' Really Nice Perspective Calculations do glClear GL_COLOR_BUFFER_BIT OR GL_DEPTH_BUFFER_BIT '' Clear Screen And Depth Buffer glLoadIdentity '' Reset The Current Modelview Matrix   glLoadIdentity '' Reset The Current Modelview Matrix glTranslatef 0.0, 0.0, -7.0 '' Move Right 1.5 Into The Screen 7.0 glRotatef rquad,1.0, 1.0, 1.0 '' Rotate The Quad On The X axis ( NEW )   glBegin GL_QUADS '' Draw A Quad glColor3f 0.0, 1.0, 0.0 '' Set The Color To Blue glVertex3f 1.0, 1.5, -2.0 '' Top Right Of The Quad (Top) glVertex3f -1.0, 1.5, -2.0 '' Top Left Of The Quad (Top) glVertex3f -1.0, 1.5, 2.0 '' Bottom Left Of The Quad (Top) glVertex3f 1.0, 1.5, 2.0 '' Bottom Right Of The Quad (Top)   glColor3f 1.0, 0.5, 0.0 '' Set The Color To Orange glVertex3f 1.0, -1.5, 2.0 '' Top Right Of The Quad (Bottom) glVertex3f -1.0, -1.5, 2.0 '' Top Left Of The Quad (Bottom) glVertex3f -1.0, -1.5, -2.0 '' Bottom Left Of The Quad (Bottom) glVertex3f 1.0, -1.5, -2.0 '' Bottom Right Of The Quad (Bottom)   glColor3f 1.0, 0.0, 0.0 '' Set The Color To Red glVertex3f 1.0, 1.5, 2.0 '' Top Right Of The Quad (Front) glVertex3f -1.0, 1.5, 2.0 '' Top Left Of The Quad (Front) glVertex3f -1.0, -1.5, 2.0 '' Bottom Left Of The Quad (Front) glVertex3f 1.0, -1.5, 2.0 '' Bottom Right Of The Quad (Front)   glColor3f 1.0, 1.0, 0.0 '' Set The Color To Yellow glVertex3f 1.0, -1.5, -2.0 '' Top Right Of The Quad (Back) glVertex3f -1.0, -1.5, -2.0 '' Top Left Of The Quad (Back) glVertex3f -1.0, 1.5, -2.0 '' Bottom Left Of The Quad (Back) glVertex3f 1.0, 1.5, -2.0 '' Bottom Right Of The Quad (Back)   glColor3f 0.0, 0.0, 1.0 '' Set The Color To Blue glVertex3f -1.0, 1.5, 2.0 '' Top Right Of The Quad (Left) glVertex3f -1.0, 1.5, -2.0 '' Top Left Of The Quad (Left) glVertex3f -1.0, -1.5, -2.0 '' Bottom Left Of The Quad (Left) glVertex3f -1.0, -1.5, 2.0 '' Bottom Right Of The Quad (Left)   glColor3f 1.0, 0.0, 1.0 '' Set The Color To Violet glVertex3f 1.0, 1.5, -2.0 '' Top Right Of The Quad (Right) glVertex3f 1.0, 1.5, 2.0 '' Top Left Of The Quad (Right) glVertex3f 1.0, -1.5, 2.0 '' Bottom Left Of The Quad (Right) glVertex3f 1.0, -1.5, -2.0 '' Bottom Right Of The Quad (Right) glEnd '' Done Drawing The Quad   rquad -= 0.15   flip loop while inkey = ""
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Stata
Stata
display "Name?" _request(s) scalar $s=10 display $s
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Tcl
Tcl
puts "Enter a variable name:" gets stdin varname set $varname 42 puts "I have set variable $varname to [set $varname]"
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#TI-89_BASIC
TI-89 BASIC
Local varName,value InputStr "Variable name", varName Prompt value value → #varName
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Ring
Ring
# Project  : Draw a pixel   load "guilib.ring"   new qapp { win1 = new qwidget() { setwindowtitle("Drawing Pixels") setgeometry(100,100,320,240) label1 = new qlabel(win1) { setgeometry(10,10,300,200) settext("") } new qpushbutton(win1) { setgeometry(200,200,100,30) settext("draw") setclickevent("draw()") } show() } exec() }   func draw() p1 = new qpicture() color = new qcolor() { setrgb(255,0,0,255) } pen = new qpen() { setcolor(color) setwidth(5) } new qpainter() { begin(p1) setpen(pen) drawpoint(100,100) endpaint() } label1 { setpicture(p1) show() }
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Robotic
Robotic
  . "Set the sprite's reference character located at the" . "upper-left corner of the board (char 0)" set "SPR0_REFX" to 0 set "SPR0_REFY" to 0   . "Offset that reference by 256, leading to the first character" . "in the extended character set" set "SPR0_OFFSET" to 256   . "Set the width and height of the sprite" set "SPR0_WIDTH" to 1 set "SPR0_HEIGHT" to 1   . "Unbound the sprite, removing the grid restriction" set "SPR0_UNBOUND" to 1   . "Mark the sprite for display on the overlay (this may not be necessary)" set "SPR0_OVERLAY" to 1   set "xPos" to 100 set "yPos" to 100   . "Display the sprite at the given location" put c0c Sprite p00 at "('xPos')" "('yPos')"  
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#Wren
Wren
import "/big" for BigInt, BigRat   var toEgyptianHelper // recursive toEgyptianHelper = Fn.new { |n, d, fracs| if (n == BigInt.zero) return var divRem = d.divMod(n) var div = divRem[0] if (divRem[1] > BigInt.zero) div = div.inc fracs.add(BigRat.new(BigInt.one, div)) var n2 = (-d) % n if (n2 < BigInt.zero) n2 = n2 + n var d2 = d * div var f = BigRat.new(n2, d2) if (f.num == BigInt.one) { fracs.add(f) return } toEgyptianHelper.call(f.num, f.den, fracs) }   var toEgyptian = Fn.new { |r| if (r.num == BigInt.zero) return [r] var fracs = [] if (r.num.abs >= r.den.abs) { var div = BigRat.new(r.num/r.den, BigInt.one) var rem = r - div fracs.add(div) toEgyptianHelper.call(rem.num, rem.den, fracs) } else { toEgyptianHelper.call(r.num, r.den, fracs) } return fracs }   BigRat.showAsInt = true var fracs = [BigRat.new(43, 48), BigRat.new(5, 121), BigRat.new(2014, 59)] for (frac in fracs) { var list = toEgyptian.call(frac) System.print("%(frac) -> %(list.join(" + "))") }   for (r in [98, 998]) { if (r == 98) { System.print("\nFor proper fractions with 1 or 2 digits:") } else { System.print("\nFor proper fractions with 1, 2 or 3 digits:") } var maxSize = 0 var maxSizeFracs = [] var maxDen = BigInt.zero var maxDenFracs = [] var sieve = List.filled(r + 1, null) // to eliminate duplicates for (i in 0..r) sieve[i] = List.filled(r + 2, false) for (i in 1..r) { for (j in (i + 1)..(r + 1)) { if (!sieve[i][j]) { var f = BigRat.new(i, j) var list = toEgyptian.call(f) var listSize = list.count if (listSize > maxSize) { maxSize = listSize maxSizeFracs.clear() maxSizeFracs.add(f) } else if (listSize == maxSize) { maxSizeFracs.add(f) } var listDen = list[-1].den if (listDen > maxDen) { maxDen = listDen maxDenFracs.clear() maxDenFracs.add(f) } else if (listDen == maxDen) { maxDenFracs.add(f) } if (i < r / 2) { var k = 2 while (true) { if (j * k > r + 1) break sieve[i * k][j * k] = true k = k + 1 } } } } } System.print(" largest number of items = %(maxSize)") System.print(" fraction(s) with this number : %(maxSizeFracs)") var md = maxDen.toString System.write(" largest denominator = %(md.count) digits, ") System.print("%(md[0...20])...%(md[-20..-1])") System.print(" fraction(s) with this denominator : %(maxDenFracs)") }
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#zkl
zkl
fcn ethiopianMultiply(l,r){ // l is a non-negative integer halve  :=fcn(n){ n/2 }; double :=fcn(n){ n+n }; lr:=List(T(l,r)); // ( (l,r) .. (1,r*n) ) while(l>1){ lr.write( T(l=halve(l),r=double(r)) ) } lr.filter(fcn([(l,r)]){ (not l.isEven) }); // strike out even left rows .reduce(fcn(sum,[(l,r)]){ sum + r },0); // sum right column }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#zkl
zkl
fcn fact(n){[2..n].reduce('*,1)} fcn factTail(n,N=1) { // tail recursion if (n == 0) return(N); return(self.fcn(n-1,n*N)); }
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#X86_Assembly
X86 Assembly
    ; x86_64 Linux NASM   global _start   %define af_inet 2 %define sock_stream 1 %define default_proto 0 %define sol_sock 1 %define reuse_addr 2 %define reuse_port 15 %define server_port 9001 %define addr_any 0 %define family_offset 0 %define port_offset 2 %define addr_offset 4 %define unused_offset 8 %define addr_len 16 %define buffer_len 64 %define max_connections 3     section .text   ; rdi - 16 bit value to be byte swapped ; return - byte swapped value htn_swap16:   xor rax, rax mov rdx, 0x000000ff   mov rsi, rdi and rsi, rdx shl rsi, 8 or rax, rsi shl rdx, 8   mov rsi, rdi and rsi, rdx shr rsi, 8 or rax, rsi ret   ; return - server socket create_server_socket:   mov rax, 41 mov rdi, af_inet mov rsi, sock_stream mov rdx, default_proto syscall push rax   mov rax, 54 mov rdi, qword [rsp] mov rsi, sol_sock mov rdx, reuse_addr mov qword [rsp - 16], 1 lea r10, [rsp - 16] mov r8, 4 syscall   mov rax, 54 mov rdi, qword [rsp] mov rsi, sol_sock mov rdx, reuse_port mov qword [rsp - 16], 1 lea r10, [rsp - 16] mov r8, 4 syscall     pop rax ret   ; rdi - socket ; rsi - port ; rdx - connections ; return - void bind_and_listen:   push rdi push rdx   mov rdi, rsi call htn_swap16   lea rsi, [rsp - 16] mov word [rsi + family_offset], af_inet mov word [rsi + port_offset], ax mov dword [rsi + addr_offset], addr_any mov qword [rsi + unused_offset], 0   mov rax, 49 mov rdi, qword [rsp + 8] mov rdx, addr_len syscall   mov rax, 50 pop rsi pop rdi syscall ret   ; rdi - server socket ; return - client socket accept:   mov rax, 43 lea rsi, [rsp - 16] lea rdx, [rsp - 24] syscall ret   ; rdi - client socket ; return - void echo:   push rdi mov rax, 0 lea rsi, [rsp - 104] mov rdx, buffer_len syscall   pop rdi mov rdx, rax lea rsi, [rsp - 112] mov rax, 1 syscall ret     _start:   call create_server_socket mov r14, rax   mov rdi, rax mov rsi, server_port mov rdx, max_connections call bind_and_listen   accept_connection:   mov rdi, r14 call accept   mov r15, rax mov rax, 57 syscall   test rax, rax jz handle_connection    ; close client socket mov rax, 3 mov rdi, r15 syscall jmp accept_connection   handle_connection:   mov rdi, r15 call echo   close_client: mov rax, 3 mov rdi, r15 syscall   close_server: mov rax, 3 mov rdi, r14 syscall   exit: mov rax, 60 xor rdi, rdi syscall  
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Wren
Wren
/* echo_server.wren */   var MAX_ENQUEUED = 20 var BUF_LEN = 256 var PORT_STR = "12321"   var AF_UNSPEC = 0 var SOCK_STREAM = 1 var AI_PASSIVE = 1   foreign class AddrInfo { foreign static getAddrInfo(name, service, req, pai)   construct new() {}   foreign family   foreign family=(f)   foreign sockType   foreign sockType=(st)   foreign flags   foreign flags=(f)   foreign protocol   foreign addr   foreign addrLen }   foreign class AddrInfoPtr { construct new() {}   foreign deref   foreign free() }   class Socket { foreign static create(domain, type, protocol)   foreign static bind(fd, addr, len)   foreign static listen(fd, n)   foreign static accept(fd, addr, addrLen) }   foreign class SockAddrPtr { construct new() {}   foreign size }   class SigAction { foreign static cleanUpProcesses() }   foreign class Buffer { construct new(size) {} }   class Posix { foreign static read(fd, buf, nbytes)   foreign static write(fd, buf, n)   foreign static fork()   foreign static close(fd) }   // Child process. var echoLines = Fn.new { |csock| var buf = Buffer.new(BUF_LEN) var r while ((r = Posix.read(csock, buf, BUF_LEN)) > 0) { Posix.write(csock, buf, r) } }   // Parent process. var takeConnectionsForever = Fn.new { |ssock| while (true) { var addr = SockAddrPtr.new() var addrSize = addr.size   /* Block until we take one connection to the server socket */ var csock = Socket.accept(ssock, addr, addrSize)   /* If it was a successful connection, spawn a worker process to service it. */ if (csock == -1) { System.print("Error accepting socket.") } else if (Posix.fork() == 0) { Posix.close(ssock) echoLines.call(csock) return } else { Posix.close(csock) } } }   /* Look up the address to bind to. */ var hints = AddrInfo.new() hints.family = AF_UNSPEC hints.sockType = SOCK_STREAM hints.flags = AI_PASSIVE var addrInfoPtr = AddrInfoPtr.new() if (AddrInfo.getAddrInfo("", PORT_STR, hints, addrInfoPtr) != 0) { Fiber.abort("Failed to get pointer to addressinfo.") }   /* Make a socket. */ var res = addrInfoPtr.deref var sock = Socket.create(res.family, res.sockType, res.protocol) if (sock == -1) Fiber.abort("Failed to make a socket.")   /* Arrange to clean up child processes (the workers). */ SigAction.cleanUpProcesses()   /* Associate the socket with its address. */ if (Socket.bind(sock, res.addr, res.addrLen) != 0) { Fiber.abort("Failed to bind socket.") }   addrInfoPtr.free()   /* State that we've opened a server socket and are listening for connections. */ if (Socket.listen(sock, MAX_ENQUEUED) != 0) { Fiber.abort("Failed to listen for connections.") }   /* Serve the listening socket until killed */ takeConnectionsForever.call(sock)
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#Processing
Processing
void setup() { size(500, 500, P3D); } void draw() { background(0); // position translate(width/2, height/2, -width/2); // optional fill and lighting colors noStroke(); strokeWeight(4); fill(192, 255, 192); pointLight(255, 255, 255, 0, -500, 500); // rotation driven by built-in timer rotateY(millis()/1000.0); // draw box box(300, 300, 300); }
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#Python
Python
from visual import * scene.title = "VPython: Draw a rotating cube"   scene.range = 2 scene.autocenter = True   print "Drag with right mousebutton to rotate view." print "Drag up+down with middle mousebutton to zoom."   deg45 = math.radians(45.0) # 0.785398163397   cube = box() # using defaults, see http://www.vpython.org/contents/docs/defaults.html cube.rotate( angle=deg45, axis=(1,0,0) ) cube.rotate( angle=deg45, axis=(0,0,1) )   while True: # Animation-loop rate(50) cube.rotate( angle=0.005, axis=(0,1,0) )  
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Standard_ML
Standard ML
structure Matrix = struct local open Array2 fun mapscalar f (x, scalar) = tabulate RowMajor (nRows x, nCols x, fn (i,j) => f(sub(x,i,j),scalar)) fun map2 f (x, y) = tabulate RowMajor (nRows x, nCols x, fn (i,j) => f(sub(x,i,j),sub(y,i,j))) in infix splus sminus stimes val op splus = mapscalar Int.+ val op sminus = mapscalar Int.- val op stimes = mapscalar Int.* val op + = map2 Int.+ val op - = map2 Int.- val op * = map2 Int.* val fromList = fromList fun toList a = List.tabulate(nRows a, fn i => List.tabulate(nCols a, fn j => sub(a,i,j))) end end;   (* example *) let open Matrix infix splus sminus stimes val m1 = fromList [[1,2],[3,4]] val m2 = fromList [[4,3],[2,1]] val s = 2 in List.map toList [m1+m2, m1-m2, m1*m2, m1 splus s, m1 sminus s, m1 stimes s] end;
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Stata
Stata
mata a = rnormal(5,5,0,1) b = 2 a:+b a:-b a:*b a:/b a:^b   a = rnormal(5,5,0,1) b = rnormal(5,1,0,1) a:+b a:-b a:*b a:/b a:^b end
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree 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.
#AutoHotkey
AutoHotkey
DIM SHARED angle AS DOUBLE   SUB turn (degrees AS DOUBLE) angle = angle + degrees*3.14159265/180 END SUB   SUB forward (length AS DOUBLE) LINE - STEP (COS(angle)*length, SIN(angle)*length), 7 END SUB   SUB dragon (length AS DOUBLE, split AS INTEGER, d AS DOUBLE) IF split=0 THEN forward length ELSE turn d*45 dragon length/1.4142136, split-1, 1 turn -d*90 dragon length/1.4142136, split-1, -1 turn d*45 END IF END SUB   ' Main program   SCREEN 12 angle = 0 PSET (150,180), 0 dragon 400, 12, 1 SLEEP
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#ContextFree
ContextFree
  startshape SPHERE   shape SPHERE { CIRCLE[] SPHERE[x 0.1% y 0.1%s 0.99 0.99 b 0.05] }  
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PicoLisp
PicoLisp
# Insert an element X at position Pos (de 2insert (X Pos DLst) (let (Lst (nth (car DLst) (dec (* 2 Pos))) New (cons X (cadr Lst) Lst)) (if (cadr Lst) (con (cdr @) New) (set DLst New) ) (if (cdr Lst) (set @ New) (con DLst New) ) ) )   (setq *DL (2list 'A 'B)) # Build a two-element doubly-linked list (2insert 'C 2 *DL) # Insert C at position 2
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PL.2FI
PL/I
  define structure 1 Node, 2 value fixed decimal, 2 back_pointer handle(Node), 2 fwd_pointer handle(Node);   /* Given that 'Current" points at some node in the linked list : */   P = NEW (: Node :); /* Create a node. */ get (P => value); P => fwd_pointer = Current => fwd_pointer; /* Points the new node at the next one. */ Current => fwd_pinter = P; /* Points the current node at the new one. */ P => back_pointer = Current; /* Points the new node back at the current one. */ Q = P => fwd_pointer; Q => back_pointer = P; /* Points the next node to the new one. */  
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pop11
Pop11
define insert_double(list, element); lvars tmp; if list == [] then  ;;; Insertion into empty list, return element element else next(list) -> tmp; list -> prev(element); tmp -> next(element); element -> next(list); if tmp /= [] then element -> prev(tmp) endif;  ;;; return original list list endif; enddefine;   lvars A = newLink(), B = newLink(), C = newLink(); ;;; Build the list of A and B insert_double(A, B) -> _; ;;; insert C between A and b insert_double(A, C) -> _;
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PureBasic
PureBasic
Structure node *prev.node *next.node value.c ;use character type for elements in this example EndStructure   Procedure insertAfter(element.c, *c.node) ;insert new node *n after node *c and set it's value to element Protected *n.node = AllocateMemory(SizeOf(node)) If *n *n\value = element *n\prev = *c If *c *n\next = *c\next *c\next = *n EndIf EndIf ProcedureReturn *n EndProcedure   Procedure displayList(*dl.node) Protected *n.node = *dl Repeat Print(Chr(*n\Value) + " ") *n = *n\next Until *n = #Null EndProcedure   If OpenConsole() Define dl.node, *n.node   *n = insertAfter('A',dl) insertAfter('B',*n) insertAfter('C',*n)   displayList(dl)   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
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
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms;   public class Clock : Form { static readonly float degrees06 = (float)Math.PI / 30; static readonly float degrees30 = degrees06 * 5; static readonly float degrees90 = degrees30 * 3;   readonly int margin = 20;   private Point p0;   public Clock() { Size = new Size(500, 500); StartPosition = FormStartPosition.CenterScreen; Resize += (sender, args) => ResetSize(); ResetSize(); var timer = new Timer() { Interval = 1000, Enabled = true }; timer.Tick += (sender, e) => Refresh(); DoubleBuffered = true; }   private void ResetSize() { p0 = new Point(ClientRectangle.Width / 2, ClientRectangle.Height / 2); Refresh(); }   protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;   drawFace(e.Graphics);   var time = DateTime.Now; int second = time.Second; int minute = time.Minute; int hour = time.Hour;   float angle = degrees90 - (degrees06 * second); DrawHand(e.Graphics, Pens.Red, angle, 0.95);   float minsecs = (minute + second / 60.0F); angle = degrees90 - (degrees06 * minsecs); DrawHand(e.Graphics, Pens.Black, angle, 0.9);   float hourmins = (hour + minsecs / 60.0F); angle = degrees90 - (degrees30 * hourmins); DrawHand(e.Graphics, Pens.Black, angle, 0.6); }   private void drawFace(Graphics g) { int radius = Math.Min(p0.X, p0.Y) - margin; g.FillEllipse(Brushes.White, p0.X - radius, p0.Y - radius, radius * 2, radius * 2);   for (int h = 0; h < 12; h++) DrawHand(g, Pens.LightGray, h * degrees30, -0.05);   for (int m = 0; m < 60; m++) DrawHand(g, Pens.LightGray, m * degrees06, -0.025); }   private void DrawHand(Graphics g, Pen pen, float angle, double size) { int radius = Math.Min(p0.X, p0.Y) - margin;   int x0 = p0.X + (size > 0 ? 0 : Convert.ToInt32(radius * (1 + size) * Math.Cos(angle))); int y0 = p0.Y + (size > 0 ? 0 : Convert.ToInt32(radius * (1 + size) * Math.Sin(-angle)));   int x1 = p0.X + Convert.ToInt32(radius * (size > 0 ? size : 1) * Math.Cos(angle)); int y1 = p0.Y + Convert.ToInt32(radius * (size > 0 ? size : 1) * Math.Sin(-angle));   g.DrawLine(pen, x0, y0, x1, y1); }   [STAThread] static void Main() { Application.Run(new Clock()); } }
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Nim
Nim
type List[T] = object head, tail: Node[T]   Node[T] = ref TNode[T]   TNode[T] = object next, prev: Node[T] data: T   proc initList[T](): List[T] = discard   proc newNode[T](data: T): Node[T] = new(result) result.data = data   proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.head != nil: l.head.prev = n l.head = n if l.tail == nil: l.tail = n   proc append[T](l: var List[T], n: Node[T]) = n.next = nil n.prev = l.tail if l.tail != nil: l.tail.next = n l.tail = n if l.head == nil: l.head = n   proc insertAfter[T](l: var List[T], r, n: Node[T]) = n.prev = r n.next = r.next n.next.prev = n r.next = n if r == l.tail: l.tail = n   proc remove[T](l: var List[T], n: Node[T]) = if n == l.tail: l.tail = n.prev if n == l.head: l.head = n.next if n.next != nil: n.next.prev = n.prev if n.prev != nil: n.prev.next = n.next   proc `$`[T](l: var List[T]): string = result = "" var n = l.head while n != nil: if result.len > 0: result.add(" -> ") result.add($n.data) n = n.next   iterator traverseForward[T](l: List[T]): T = var n = l.head while n != nil: yield n.data n = n.next   iterator traverseBackward[T](l: List[T]): T = var n = l.tail while n != nil: yield n.data n = n.prev   var l = initList[int]() var n = newNode(12) var m = newNode(13) var i = newNode(14) var j = newNode(15) l.append(n) l.prepend(m) l.insertAfter(m, i) l.prepend(j) l.remove(m)   for i in l.traverseForward(): echo "> ", i   for i in l.traverseBackward(): echo "< ", i
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Oberon-2
Oberon-2
  MODULE Collections; IMPORT Box;   TYPE Action = PROCEDURE (o: Box.Object);   PROCEDURE (dll: DLList) GoForth*(do: Action); VAR iter: Node; BEGIN iter := dll.first; WHILE iter # NIL DO do(iter.value); iter := iter.next END END GoForth;   PROCEDURE (dll: DLList) GoBack*(do: Action); VAR iter: Node; BEGIN ASSERT(dll.last # NIL); iter := dll.last; WHILE iter # NIL DO do(iter.value); iter := iter.prev END END GoBack;   END Collections.  
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Objeck
Objeck
class ListNode { @value : Base; @next : ListNode; @previous: ListNode;   New(value : Base) { @value := value; }   method : public : Set(value : Base) ~ Nil { @value := value; }   method : public : Get() ~ Base { return @value; }   method : public : SetNext(next : Collection.ListNode) ~ Nil { @next := next; }   method : public : GetNext() ~ ListNode { return @next; }   method : public : SetPrevious(previous : Collection.ListNode) ~ Nil { @previous := previous; }   method : public : GetPrevious() ~ ListNode { return @previous; } }
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#OCaml
OCaml
type 'a dlink = { mutable data: 'a; mutable next: 'a dlink option; mutable prev: 'a dlink option; }   let dlink_of_list li = let f prev_dlink x = let dlink = { data = x; prev = None; next = prev_dlink } in begin match prev_dlink with | None -> () | Some prev_dlink -> prev_dlink.prev <- Some dlink end; Some dlink in List.fold_left f None (List.rev li) ;;   let list_of_dlink = let rec aux acc = function | None -> List.rev acc | Some{ data = d; prev = _; next = next } -> aux (d::acc) next in aux [] ;;   let iter_forward_dlink f = let rec aux = function | None -> () | Some{ data = d; prev = _; next = next } -> f d; aux next in aux ;;
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)
#Icon_and_Unicon
Icon and Unicon
procedure main(a) n := integer(!a) | 20 every (nr|nw|nb) := ?n-1 sIn := repl("r",nw)||repl("w",nb)||repl("b",nr) write(sRand := bestShuffle(sIn)) write(sOut := map(csort(map(sRand,"rwb","123")),"123","rwb")) if sIn ~== sOut then write("Eh? Not in correct order!") end   procedure bestShuffle(s) # (Taken from the Best Shuffle task) t := s every !t :=: ?t # Uncommented to get a random best shuffling every i := 1 to *t do every j := (1 to i-1) | (i+1 to *t) do if (t[i] ~== s[j]) & (s[i] ~== t[j]) then break t[i] :=: t[j] return t end   procedure csort(w) every (s := "") ||:= (find(c := !cset(w),w),c) return s 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
#Frink
Frink
res = 254 / in s = 1/2 inch res v = callJava["frink.graphics.VoxelArray", "cube", [-s, s, -s, s, -s, s, true]]   v.projectX[undef].show["X"] v.projectY[undef].show["Y"] v.projectZ[undef].show["Z"]   filename = "cube.stl" print["Writing $filename..."] w = new Writer[filename] w.println[v.toSTLFormat["cube", 1/(res mm)]] w.close[] println["done."]
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT ASK "Enter variablename": name="" ASK "Enter value": value="" TRACE +@name @name=$value PRINT @name  
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#UNIX_Shell
UNIX Shell
read name declare $name=42 echo "${name}=${!name}"
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Wren
Wren
import "io" for Stdin, Stdout   var userVars = {} System.print("Enter three variables:") for (i in 0..2) { System.write("\n name : ") Stdout.flush() var name = Stdin.readLine() System.write(" value: ") Stdout.flush() var value = Num.fromString(Stdin.readLine()) userVars[name] = value }   System.print("\nYour variables are:\n") for (kv in userVars) { System.print("  %(kv.key) = %(kv.value)") }
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Ruby
Ruby
require 'gtk3'   Width, Height = 320, 240 PosX, PosY = 100, 100   window = Gtk::Window.new window.set_default_size(Width, Height) window.title = 'Draw a pixel'   window.signal_connect(:draw) do |widget, context| context.set_antialias(Cairo::Antialias::NONE) # paint out bg with white # context.set_source_rgb(1.0, 1.0, 1.0) # context.paint(1.0) # draw a rectangle context.set_source_rgb(1.0, 0.0, 0.0) context.fill do context.rectangle(PosX, PosY, 1, 1) end end   window.signal_connect(:destroy) { Gtk.main_quit }   window.show Gtk.main  
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Rust
Rust
extern crate piston_window; extern crate image;   use piston_window::*;   fn main() { let (width, height) = (320, 240);   let mut window: PistonWindow = WindowSettings::new("Red Pixel", [width, height]) .exit_on_esc(true).build().unwrap();   // Since we cant manipulate pixels directly, we need to manipulate the pixels on a canvas. // Only issue is that sub-pixels exist (which is probably why the red pixel looks like a smear on the output image) let mut canvas = image::ImageBuffer::new(width, height); canvas.put_pixel(100, 100, image::Rgba([0xff, 0, 0, 0xff]));   // Transform into a texture so piston can use it. let texture: G2dTexture = Texture::from_image( &mut window.factory, &canvas, &TextureSettings::new() ).unwrap();   // The window event loop. while let Some(event) = window.next() { window.draw_2d(&event, |context, graphics| { clear([1.0; 4], graphics); image(&texture, context.transform, graphics); }); } }  
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#zkl
zkl
# Just compute the denominator terms, as the numerators are always 1 fcn egyptian(num,denom){ result,t := List(),Void; t,num=num.divr(denom); // reduce fraction if(t) result.append(T(t)); // signal t isn't a denominator while(num){ # Compute ceil($denom/$num) without floating point inaccuracy term:=denom/num + (denom/num*num < denom); result.append(term); z:=denom%num; num=(if(z) num-z else 0); denom*=term; } result } fcn efrac(fraction){ // list to string, format list of denominators fraction.pump(List,fcn(denom){ if(denom.isType(List)) denom[0] else String("1/",denom); }).concat(" + ") }
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Z80_Assembly
Z80 Assembly
org &8000   ld hl,17 call Halve_Until_1   push bc ld hl,34 call Double_Until_1 pop bc   call SumOddEntries ;returns Ethiopian product in IX.   call NewLine   call Primm byte "0x",0   push ix pop hl   ld a,H call ShowHex ;Output should be in decimal but hex is easier. ld a,L call ShowHex   ret     Halve_Until_1: ;input: HL = number you wish to halve. HL is unsigned. ld de,Column_1 ld a,1 ld (Column_1),HL inc de inc de loop_HalveUntil_1: SRL H RR L inc b push af ld a,L ld (de),a inc de ld a,H ld (de),a inc de pop af CP L jr nz,loop_HalveUntil_1 ;b tracks how many times to double the second factor. ret   Double_Until_1: ;doubles second factor B times. B is calculated by Halve_until_1 ld de,Column_2 ld (Column_2),HL inc de inc de loop_double_until_1: SLA L RL H PUSH AF LD A,L LD (DE),A INC DE LD A,H LD (DE),A INC DE POP AF DJNZ loop_double_until_1 ret     SumOddEntries: sla b ;double loop counter, this is also the offset to the "last" entry of ;each table ld h,>Column_1 ld d,>Column_2 ;aligning the tables lets us get away with this. ld l,b ld e,b ld ix,0 loop: ld a,(hl) rrca ;we only need the result of the odd/even test. jr nc,skipEven push hl push de ld a,(de) ld L,a inc de ld a,(de) ld H,a ex de,hl add ix,de pop de pop hl skipEven: dec de dec de dec hl dec hl djnz loop ret ;ix should contain the answer     align 8 ;aligns Column_1 to the nearest 256 byte boundary. This makes offsetting easier. Column_1: ds 16,0   align 8 ;aligns Column_2 to the nearest 256 byte boundary. This makes offsetting easier. Column_2: ds 16,0
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET x=5: GO SUB 1000: PRINT "5! = ";r 999 STOP 1000 REM ************* 1001 REM * FACTORIAL * 1002 REM ************* 1010 LET r=1 1020 IF x<2 THEN RETURN 1030 FOR i=2 TO x: LET r=r*i: NEXT i 1040 RETURN
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#zkl
zkl
const PORT=12321; pipe:=Thread.Pipe(); // how server tells thread to connect to user   fcn echo(socket){ // a thread, one per connection text:=Data(); while(t:=socket.read()){ text.append(t); if(text.find("\n",text.cursor)){ text.readln().print(); } } // socket was closed }   // Set up the server socket. server:=Network.TCPServerSocket.open(PORT); println("Listening on %s:%s".fmt(server.hostname,server.port)); server.listen(echo.launch); // Main event loop
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#Racket
Racket
#lang racket/gui (require math/matrix math/array)   (define (Rx θ) (matrix [[1.0 0.0 0.0] [0.0 (cos θ) (- (sin θ))] [0.0 (sin θ) (cos θ)]]))   (define (Ry θ) (matrix [[ (cos θ) 0.0 (sin θ)] [ 0.0 1.0 0.0 ] [(- (sin θ)) 0.0 (cos θ)]]))   (define (Rz θ) (matrix [[(cos θ) (- (sin θ)) 0.0] [(sin θ) (cos θ) 0.0] [ 0.0 0.0 1.0]]))   (define base-matrix (matrix* (identity-matrix 3 100.0) (Rx (- (/ pi 2) (atan (sqrt 2)))) (Rz (/ pi 4.0))))   (define (current-matrix) (matrix* (Ry (/ (current-inexact-milliseconds) 1000.)) base-matrix))   (define corners (for*/list ([x '(-1.0 1.0)] [y '(-1.0 1.0)] [z '(-1.0 1.0)]) (matrix [[x] [y] [z]])))   (define lines '((0 1) (0 2) (0 4) (1 3) (1 5) (2 3) (2 6) (3 7) (4 5) (4 6) (5 7) (6 7)))   (define ox 200.) (define oy 200.)   (define (draw-line dc a b) (send dc draw-line (+ ox (array-ref a #(0 0))) (+ oy (array-ref a #(1 0))) (+ ox (array-ref b #(0 0))) (+ oy (array-ref b #(1 0)))))   (define (draw-cube c dc) (define-values (w h) (send dc get-size)) (set! ox (/ w 2)) (set! oy (/ h 2)) (define cs (for/vector ([c (in-list corners)]) (matrix* (current-matrix) c))) (for ([l (in-list lines)]) (match-define (list i j) l) (draw-line dc (vector-ref cs i) (vector-ref cs j))))   (define f (new frame% [label "cube"])) (define c (new canvas% [parent f] [min-width 400] [min-height 400] [paint-callback draw-cube])) (send f show #t)   (send* (send c get-dc) (set-pen "black" 1 'solid) (set-smoothing 'smoothed))   (define (refresh) (send c refresh))   (define t (new timer% [notify-callback refresh] [interval 35] [just-once? #f]))
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#Raku
Raku
use Terminal::Caca; given my $canvas = Terminal::Caca.new { .title('Rosetta Code - Rotating cube - Press any key to exit');   sub scale-and-translate($x, $y, $z) { $x * 5 / ( 5 + $z ) * 15 + 40, $y * 5 / ( 5 + $z ) * 7 + 15, $z; }   sub rotate3d-x( $x, $y, $z, $angle ) { my ($cosθ, $sinθ) = cis( $angle * π / 180.0 ).reals; $x, $y * $cosθ - $z * $sinθ, $y * $sinθ + $z * $cosθ; }   sub rotate3d-y( $x, $y, $z, $angle ) { my ($cosθ, $sinθ) = cis( $angle * π / 180.0 ).reals; $x * $cosθ - $z * $sinθ, $y, $x * $sinθ + $z * $cosθ; }   sub rotate3d-z( $x, $y, $z, $angle ) { my ($cosθ, $sinθ) = cis( $angle * π / 180.0 ).reals; $x * $cosθ - $y * $sinθ, $x * $cosθ + $y * $sinθ, $z; }   # Unit cube from polygon mesh, aligned to axes my @mesh = [ [1, 1, -1], [-1, -1, -1], [-1, 1, -1] ], # far face [ [1, 1, -1], [-1, -1, -1], [ 1, -1, -1] ], [ [1, 1, 1], [-1, -1, 1], [-1, 1, 1] ], # near face [ [1, 1, 1], [-1, -1, 1], [ 1, -1, 1] ]; @mesh.push: [$_».rotate( 1)».Array] for @mesh[^4]; # positive and @mesh.push: [$_».rotate(-1)».Array] for @mesh[^4]; # negative rotations   # Rotate to correct orientation for task for ^@mesh X ^@mesh[0] -> ($i, $j) { @(@mesh[$i;$j]) = rotate3d-x |@mesh[$i;$j], 45; @(@mesh[$i;$j]) = rotate3d-z |@mesh[$i;$j], 40; }   my @colors = red, blue, green, cyan, magenta, yellow;   loop { for ^359 -> $angle { .color( white, white ); .clear;   # Flatten 3D into 2D and rotate for all faces my @faces-z; my $c-index = 0; for @mesh -> @triangle { my @points; my $sum-z = 0; for @triangle -> @node { my ($px, $py, $z) = scale-and-translate |rotate3d-y |@node, $angle; @points.append: $px.Int, $py.Int; $sum-z += $z; }   @faces-z.push: %( color => @colors[$c-index++ div 2], points => @points, avg-z => $sum-z / +@points; ); }   # Draw all faces # Sort by z to draw farthest first for @faces-z.sort( -*.<avg-z> ) -> %face { # Draw filled triangle .color( %face<color>, %face<color> ); .fill-triangle( |%face<points> ); # And frame .color( black, black ); .thin-triangle( |%face<points> ); }   .refresh; exit if .wait-for-event(key-press); } }   # Cleanup on scope exit LEAVE { .cleanup; } }
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Tcl
Tcl
package require Tcl 8.5 proc alias {name args} {uplevel 1 [list interp alias {} $name {} {*}$args]}   # Engine for elementwise operations between matrices proc elementwiseMatMat {lambda A B} { set C {} foreach rA $A rB $B { set rC {} foreach vA $rA vB $rB { lappend rC [apply $lambda $vA $vB] } lappend C $rC } return $C } # Lift some basic math ops alias m+ elementwiseMatMat {{a b} {expr {$a+$b}}} alias m- elementwiseMatMat {{a b} {expr {$a-$b}}} alias m* elementwiseMatMat {{a b} {expr {$a*$b}}} alias m/ elementwiseMatMat {{a b} {expr {$a/$b}}} alias m** elementwiseMatMat {{a b} {expr {$a**$b}}}   # Engine for elementwise operations between a matrix and a scalar proc elementwiseMatSca {lambda A b} { set C {} foreach rA $A { set rC {} foreach vA $rA { lappend rC [apply $lambda $vA $b] } lappend C $rC } return $C } # Lift some basic math ops alias .+ elementwiseMatSca {{a b} {expr {$a+$b}}} alias .- elementwiseMatSca {{a b} {expr {$a-$b}}} alias .* elementwiseMatSca {{a b} {expr {$a*$b}}} alias ./ elementwiseMatSca {{a b} {expr {$a/$b}}} alias .** elementwiseMatSca {{a b} {expr {$a**$b}}}
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.
#BASIC
BASIC
DIM SHARED angle AS DOUBLE   SUB turn (degrees AS DOUBLE) angle = angle + degrees*3.14159265/180 END SUB   SUB forward (length AS DOUBLE) LINE - STEP (COS(angle)*length, SIN(angle)*length), 7 END SUB   SUB dragon (length AS DOUBLE, split AS INTEGER, d AS DOUBLE) IF split=0 THEN forward length ELSE turn d*45 dragon length/1.4142136, split-1, 1 turn -d*90 dragon length/1.4142136, split-1, -1 turn d*45 END IF END SUB   ' Main program   SCREEN 12 angle = 0 PSET (150,180), 0 dragon 400, 12, 1 SLEEP
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#D
D
import std.stdio, std.math, std.algorithm, std.numeric;   alias V3 = double[3]; immutable light = normalize([30.0, 30.0, -50.0]);   V3 normalize(V3 v) pure @nogc { v[] /= dotProduct(v, v) ^^ 0.5; return v; }   double dot(in ref V3 x, in ref V3 y) pure nothrow @nogc { immutable double d = dotProduct(x, y); return d < 0 ? -d : 0; }   void drawSphere(in double R, in double k, in double ambient) @nogc { enum shades = ".:!*oe&#%@"; foreach (immutable i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) { immutable double x = i + 0.5; foreach (immutable j; cast(int)floor(-2 * R) .. cast(int)ceil(2 * R) + 1) { immutable double y = j / 2. + 0.5; if (x ^^ 2 + y ^^ 2 <= R ^^ 2) { immutable vec = [x, y, (R^^2 - x^^2 - y^^2) ^^ 0.5] .normalize; immutable double b = dot(light, vec) ^^ k + ambient; int intensity = cast(int)((1 - b) * (shades.length-1)); intensity = min(shades.length - 1, max(intensity, 0)); shades[intensity].putchar; } else ' '.putchar; } '\n'.putchar; } }   void main() { drawSphere(20, 4, 0.1); drawSphere(10, 2, 0.4); }
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Python
Python
def insert(anchor, new): new.next = anchor.next new.prev = anchor anchor.next.prev = new anchor.next = new
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Racket
Racket
role DLElem[::T] { has DLElem[T] $.prev is rw; has DLElem[T] $.next is rw; has T $.payload = T;   method pre-insert(T $payload) { die "Can't insert before beginning" unless $!prev; my $elem = ::?CLASS.new(:$payload); $!prev.next = $elem; $elem.prev = $!prev; $elem.next = self; $!prev = $elem; $elem; }   method post-insert(T $payload) { die "Can't insert after end" unless $!next; my $elem = ::?CLASS.new(:$payload); $!next.prev = $elem; $elem.next = $!next; $elem.prev = self; $!next = $elem; $elem; }   method delete { die "Can't delete a sentinel" unless $!prev and $!next; $!next.prev = $!prev; $!prev.next = $!next; # conveniently returns next element } }   role DLList[::DLE] { has DLE $.first; has DLE $.last;   submethod BUILD { $!first = DLE.new; $!last = DLE.new; $!first.next = $!last; $!last.prev = $!first; }   method list { ($!first.next, *.next ...^ !*.next).map: *.payload } method reverse { ($!last.prev, *.prev ...^ !*.prev).map: *.payload } }   class DLElem_Str does DLElem[Str] {} class DLList_Str does DLList[DLElem_Str] {}   my $sdll = DLList_Str.new; my $b = $sdll.first.post-insert('A').post-insert('B'); $b.pre-insert('C'); say $sdll.list; # A C B
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <math.h>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int BMP_SIZE = 300, MY_TIMER = 987654, CENTER = BMP_SIZE >> 1, SEC_LEN = CENTER - 20, MIN_LEN = SEC_LEN - 20, HOUR_LEN = MIN_LEN - 20; const float PI = 3.1415926536f;   //-------------------------------------------------------------------------------------------------- class vector2 { public: vector2() { x = y = 0; } vector2( int a, int b ) { x = a; y = b; } void set( int a, int b ) { x = a; y = b; } void rotate( float angle_r ) { float _x = static_cast<float>( x ), _y = static_cast<float>( y ), s = sinf( angle_r ), c = cosf( angle_r ), a = _x * c - _y * s, b = _x * s + _y * c;   x = static_cast<int>( a ); y = static_cast<int>( b ); } int x, y; }; //-------------------------------------------------------------------------------------------------- class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); }   bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;   hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc );   width = w; height = h; return true; }   void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); }   void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); }   void setPenColor( DWORD c ) { clr = c; createPen(); }   void setPenWidth( int w ) { wid = w; createPen(); }   void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;   GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];   ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; }   HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; }   private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); }   HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; //-------------------------------------------------------------------------------------------------- class clock { public: clock() { _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear( 100 ); _bmp.setPenWidth( 2 ); _ang = DegToRadian( 6 ); }   void setNow() { GetLocalTime( &_sysTime ); draw(); }   float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }   void setHWND( HWND hwnd ) { _hwnd = hwnd; }   private: void drawTicks( HDC dc ) { vector2 line; _bmp.setPenWidth( 1 ); for( int x = 0; x < 60; x++ ) { line.set( 0, 50 ); line.rotate( static_cast<float>( x + 30 ) * _ang ); MoveToEx( dc, CENTER - static_cast<int>( 2.5f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.5f * static_cast<float>( line.y ) ), NULL ); LineTo( dc, CENTER - static_cast<int>( 2.81f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.81f * static_cast<float>( line.y ) ) ); }   _bmp.setPenWidth( 3 ); for( int x = 0; x < 60; x += 5 ) { line.set( 0, 50 ); line.rotate( static_cast<float>( x + 30 ) * _ang ); MoveToEx( dc, CENTER - static_cast<int>( 2.5f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.5f * static_cast<float>( line.y ) ), NULL ); LineTo( dc, CENTER - static_cast<int>( 2.81f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.81f * static_cast<float>( line.y ) ) ); } }   void drawHands( HDC dc ) { float hp = DegToRadian( ( 30.0f * static_cast<float>( _sysTime.wMinute ) ) / 60.0f ); int h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5;   _bmp.setPenWidth( 3 ); _bmp.setPenColor( RGB( 0, 0, 255 ) ); drawHand( dc, HOUR_LEN, ( _ang * static_cast<float>( 30 + h ) ) + hp );   _bmp.setPenColor( RGB( 0, 128, 0 ) ); drawHand( dc, MIN_LEN, _ang * static_cast<float>( 30 + _sysTime.wMinute ) );   _bmp.setPenWidth( 2 ); _bmp.setPenColor( RGB( 255, 0, 0 ) ); drawHand( dc, SEC_LEN, _ang * static_cast<float>( 30 + _sysTime.wSecond ) ); }   void drawHand( HDC dc, int len, float ang ) { vector2 line; line.set( 0, len ); line.rotate( ang ); MoveToEx( dc, CENTER, CENTER, NULL ); LineTo( dc, line.x + CENTER, line.y + CENTER ); }   void draw() { HDC dc = _bmp.getDC();   _bmp.setBrushColor( RGB( 250, 250, 250 ) ); Ellipse( dc, 0, 0, BMP_SIZE, BMP_SIZE ); _bmp.setBrushColor( RGB( 230, 230, 230 ) ); Ellipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 );   drawTicks( dc ); drawHands( dc );   _bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 ); Ellipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 );   _wdc = GetDC( _hwnd ); BitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, _wdc ); }   myBitmap _bmp; HWND _hwnd; HDC _wdc; SYSTEMTIME _sysTime; float _ang; }; //-------------------------------------------------------------------------------------------------- class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); SetTimer( _hwnd, MY_TIMER, 1000, NULL ); _clock.setHWND( _hwnd );   ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd );   MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } return UnregisterClass( "_MY_CLOCK_", _hInst ); } private: void wnd::doPaint( HDC dc ) { _clock.setNow(); } void wnd::doTimer() { _clock.setNow(); } static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_PAINT: { PAINTSTRUCT ps; HDC dc = BeginPaint( hWnd, &ps ); _inst->doPaint( dc ); EndPaint( hWnd, &ps ); return 0; } case WM_TIMER: _inst->doTimer(); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; }   HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_CLOCK_";   RegisterClassEx( &wcex );   RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_CLOCK_", ".: Clock -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); }   static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; clock _clock; }; wnd* wnd::_inst = 0; //-------------------------------------------------------------------------------------------------- int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { wnd myWnd; return myWnd.Run( hInstance ); } //--------------------------------------------------------------------------------------------------  
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Objeck
Objeck
  class Traverse { function : Main(args : String[]) ~ Nil { list := Collection.IntList->New(); list->Insert(100); list->Insert(50); list->Insert(25); list->Insert(10); list->Insert(5);   "-- forward --"->PrintLine(); list->Rewind(); while(list->More()) { list->Get()->PrintLine(); list->Next(); };   "-- backward --"->PrintLine(); list->Forward(); while(list->More()) { list->Get()->PrintLine(); list->Previous(); }; } }  
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Oforth
Oforth
DList method: forEachNext dup ifNull: [ drop @head ifNull: [ false ] else: [ @head @head true] return ] next dup ifNull: [ drop false ] else: [ dup true ] ;   DList method: forEachPrev dup ifNull: [ drop @tail ifNull: [ false ] else: [ @tail @tail true] return ] prev dup ifNull: [ drop false ] else: [ dup true ] ;   : test | dl n | DList new ->dl dl insertFront("A") dl insertBack("B") dl head insertAfter(DNode new("C", null , null))   "Traversal (beginning to end) : " println dl forEach: n [ n . ]   "\nTraversal (end to beginning) : " println dl revEach: n [ n . ] ;
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Oforth
Oforth
Object Class new: DNode(value, mutable prev, mutable next)
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Oz
Oz
fun {CreateNewNode Value} node(prev:{NewCell _} next:{NewCell _} value:Value) end
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pascal
Pascal
type link_ptr = ^link; data_ptr = ^data; (* presumes that type 'data' is defined above *) link = record prev: link_ptr; next: link_ptr; data: data_ptr; end;
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Perl
Perl
my %node = ( data => 'say what', next => \%foo_node, prev => \%bar_node, ); $node{next} = \%quux_node; # mutable
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national 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)
#J
J
i2b=: {&(;:'red white blue')
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national 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)
#Java
Java
import java.util.Arrays; import java.util.Random;   public class DutchNationalFlag { enum DutchColors { RED, WHITE, BLUE }   public static void main(String[] args){ DutchColors[] balls = new DutchColors[12]; DutchColors[] values = DutchColors.values(); Random rand = new Random();   for (int i = 0; i < balls.length; i++) balls[i]=values[rand.nextInt(values.length)]; System.out.println("Before: " + Arrays.toString(balls));   Arrays.sort(balls); System.out.println("After: " + Arrays.toString(balls));   boolean sorted = true; for (int i = 1; i < balls.length; i++ ){ if (balls[i-1].compareTo(balls[i]) > 0){ sorted=false; break; } } System.out.println("Correctly sorted: " + sorted); } }
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Go
Go
package main   import "fmt"   func cuboid(dx, dy, dz int) { fmt.Printf("cuboid %d %d %d:\n", dx, dy, dz) cubLine(dy+1, dx, 0, "+-") for i := 1; i <= dy; i++ { cubLine(dy-i+1, dx, i-1, "/ |") } cubLine(0, dx, dy, "+-|") for i := 4*dz - dy - 2; i > 0; i-- { cubLine(0, dx, dy, "| |") } cubLine(0, dx, dy, "| +") for i := 1; i <= dy; i++ { cubLine(0, dx, dy-i, "| /") } cubLine(0, dx, 0, "+-\n") }   func cubLine(n, dx, dy int, cde string) { fmt.Printf("%*s", n+1, cde[:1]) for d := 9*dx - 1; d > 0; d-- { fmt.Print(cde[1:2]) } fmt.Print(cde[:1]) fmt.Printf("%*s\n", dy+1, cde[2:]) }   func main() { cuboid(2, 3, 4) cuboid(1, 1, 1) cuboid(6, 2, 1) }
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Z80_Assembly
Z80 Assembly
org &8000 WaitChar equ &BB06 ;Amstrad CPC BIOS call, loops until user presses a key. That key's ASCII value is returned in A. PrintChar equ &BB5A ;Amstrad CPC BIOS call, A is treated as an ASCII value and is printed to the screen.   getInput: call WaitChar ;returns key press in A     or a ;set flags according to accumulator jp m,getInput ;most keyboards aren't capable of going over ascii 127 ;but just in case they can prevent it. ;IX/IY offsets are signed, thus a key press outside of 7-bit ASCII would index out of bounds   push af call PrintChar ;prints the user variable name to the screen. pop af   call NewLine   ld (LoadFromUserNamedVariable+2),a ;offset byte is at addr+2 ld (StoreToUserNamedVariable+2),a   ; This self-modifying code turns both instances of (IX+0) into (IX+varname)     ld a,&42 ;set the value of the dynamically named variable ; to &42   ld ix,ExtraRam ;storage location of dynamically named variables   StoreToUserNamedVariable: ld (IX+0),a ;store 42 at the named offset ;"+0" is overwritten with the dynamic user ram name   xor a dec a ;just to prove that the value is indeed stored where the code ; is intending to, set A to 255 so that the next section of ; code will show that the variable is indeed retrieved and ; is shown to the screen   LoadFromUserNamedVariable: ld a,(IX+0) ;retrieve the value at the stored offset. The "+0" was overwritten with the user-defined offset.   call ShowHex ;prints to the terminal the value stored at the dynamically named user variable     ReturnToBasic RET   ShowHex: ;credit to Keith S. of Chibiakumas push af and %11110000 rrca rrca rrca rrca call PrintHexChar pop af and %00001111 ;call PrintHexChar ;execution flows into it naturally. PrintHexChar: or a ;Clear Carry Flag daa add a,&F0 adc a,&40 jp PrintChar ;ret   NewLine: push af ld a,13 ;Carriage return call PrintChar ld a,10 ;Line Feed call PrintChar pop af ret     org &9000 ExtraRam: ds 256,0 ;256 bytes of ram, each initialized to zero
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Scala
Scala
import java.awt.image.BufferedImage import java.awt.Color import scala.language.reflectiveCalls   object RgbBitmap extends App {   class RgbBitmap(val dim: (Int, Int)) { def width = dim._1 def height = dim._2   private val image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)   def apply(x: Int, y: Int) = new Color(image.getRGB(x, y))   def update(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB)   def fill(c: Color) = { val g = image.getGraphics g.setColor(c) g.fillRect(0, 0, width, height) } }   object RgbBitmap { def apply(width: Int, height: Int) = new RgbBitmap(width, height) }   /** Even Javanese style testing is still possible. */ private val img0 = new RgbBitmap(50, 60) { // Wrappers to enable adhoc Javanese style def getPixel(x: Int, y: Int) = this(x, y) def setPixel(x: Int, y: Int, c: Color) = this(x, y) = c }   img0.fill(Color.CYAN) img0.setPixel(5, 6, Color.BLUE) // Testing in Java style assert(img0.getPixel(0, 1) == Color.CYAN) assert(img0.getPixel(5, 6) == Color.BLUE) assert(img0.width == 50) assert(img0.height == 60) println("Tests successfully completed with no errors found.")   }
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DEF FN e(a)=a-INT (a/2)*2-1 20 DEF FN h(a)=INT (a/2) 30 DEF FN d(a)=2*a 40 LET x=17: LET y=34: LET tot=0 50 IF x<1 THEN GO TO 100 60 PRINT x;TAB (4); 70 IF FN e(x)=0 THEN LET tot=tot+y: PRINT y: GO TO 90 80 PRINT "---" 90 LET x=FN h(x): LET y=FN d(y): GO TO 50 100 PRINT TAB (4);"===",TAB (4);tot
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#Ring
Ring
  #===================================================================# # Based on Original Sample from RayLib (https://www.raylib.com/) # Ported to RingRayLib by Ring Team #===================================================================#   load "raylib.ring"   screenWidth = 800 screenHeight = 450   InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d picking")   camera = Camera3D( 10, 10, 10, 0, 0, 0 , 0, 1, 0 , 45, CAMERA_PERSPECTIVE )   cubePosition = Vector3( 0, 1, 0 ) cubeSize = Vector3( 2, 2, 2 )   ray = Ray(0,0,0,0,0,0)   collision = false   SetCameraMode(camera, CAMERA_FREE)   SetTargetFPS(60)   while !WindowShouldClose()   UpdateCamera(camera)   if IsMouseButtonPressed(MOUSE_LEFT_BUTTON) if !collision ray = GetMouseRay(GetMousePosition(), camera)   collision = CheckCollisionRayBox(ray, BoundingBox( cubePosition.x - cubeSize.x/2, cubePosition.y - cubeSize.y/2, cubePosition.z - cubeSize.z/2, cubePosition.x + cubeSize.x/2, cubePosition.y + cubeSize.y/2, cubePosition.z + cubeSize.z/2 ) ) else collision = false ok ok   BeginDrawing()   ClearBackground(RAYWHITE)   BeginMode3D(camera)   if collision DrawCube(cubePosition, cubeSize.x, cubeSize.y, cubeSize.z, RED) DrawCubeWires(cubePosition, cubeSize.x, cubeSize.y, cubeSize.z, MAROON)   DrawCubeWires(cubePosition, cubeSize.x + 0.2f, cubeSize.y + 0.2f, cubeSize.z + 0.2f, GREEN) else DrawCube(cubePosition, cubeSize.x, cubeSize.y, cubeSize.z, GRAY) DrawCubeWires(cubePosition, cubeSize.x, cubeSize.y, cubeSize.z, DARKGRAY) ok   DrawRay(ray, MAROON) DrawGrid(10, 1)   EndMode3D()   DrawText("Try selecting the box with mouse!", 240, 10, 20, DARKGRAY)   if collision DrawText("BOX SELECTED", (screenWidth - MeasureText("BOX SELECTED", 30)) / 2, screenHeight * 0.1f, 30, GREEN) ok   DrawFPS(10, 10)   EndDrawing() end   CloseWindow()  
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#Scala
Scala
import java.awt.event.ActionEvent import java.awt._   import javax.swing.{JFrame, JPanel, Timer}   import scala.math.{Pi, atan, cos, sin, sqrt}   object RotatingCube extends App {   class RotatingCube extends JPanel { private val vertices: Vector[Array[Double]] = Vector(Array(-1, -1, -1), Array(-1, -1, 1), Array(-1, 1, -1), Array(-1, 1, 1), Array(1, -1, -1), Array(1, -1, 1), Array(1, 1, -1), Array(1, 1, 1))   private val edges: Vector[(Int, Int)] = Vector((0, 1), (1, 3), (3, 2), (2, 0), (4, 5), (5, 7), (7, 6), (6, 4), (0, 4), (1, 5), (2, 6), (3, 7))   setPreferredSize(new Dimension(640, 640)) setBackground(Color.white) scale(100) rotateCube(Pi / 4, atan(sqrt(2)))   new Timer(17, (_: ActionEvent) => { rotateCube(Pi / 180, 0) repaint() }).start()   override def paintComponent(gg: Graphics): Unit = { def drawCube(g: Graphics2D): Unit = { g.translate(getWidth / 2, getHeight / 2) for {edge <- edges xy1: Array[Double] = vertices(edge._1) xy2: Array[Double] = vertices(edge._2) } { g.drawLine(xy1(0).toInt, xy1(1).toInt, xy2(0).toInt, xy2(1).toInt) g.fillOval(xy1(0).toInt -4, xy1(1).toInt - 4, 8, 8) g.setColor(Color.black) } }   super.paintComponent(gg) val g: Graphics2D = gg.asInstanceOf[Graphics2D] g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawCube(g) }   private def scale(s: Double): Unit = { for {node <- vertices i <- node.indices } node(i) *= s }   private def rotateCube(angleX: Double, angleY: Double): Unit = { def sinCos(x: Double) = (sin(x), cos(x))   val ((sinX, cosX), (sinY, cosY)) = (sinCos(angleX), sinCos(angleY))   for { node <- vertices x: Double = node(0) y: Double = node(1) } { def f(p: Double, q: Double)(a: Double, b: Double) = a * p + b * q   def fx(a: Double, b: Double) = f(cosX, sinX)(a, b)   def fy(a: Double, b: Double) = f(cosY, sinY)(a, b)   node(0) = fx(x, -node(2)) val z = fx(node(2), x) node(1) = fy(y, -z) node(2) = fy(z, y) } }   }   new JFrame("Rotating Cube") { add(new RotatingCube(), BorderLayout.CENTER) pack() setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE) setLocationRelativeTo(null) setResizable(false) setVisible(true) }   }
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Vlang
Vlang
import math   struct Matrix { mut: ele []f64 stride int }   fn matrix_from_rows(rows [][]f64) Matrix { if rows.len == 0 { return Matrix{[], 0} } mut m := Matrix{[]f64{len: rows.len*rows[0].len}, rows[0].len} for rx, row in rows { m.ele = m.ele[..rx*m.stride] m.ele << row m.ele << m.ele[(rx+1)*m.stride..] } return m }   fn like(m Matrix) Matrix { return Matrix{[]f64{len: m.ele.len}, m.stride} }   fn (m Matrix) str() string { mut s := "" for e := 0; e < m.ele.len; e += m.stride { s += "${m.ele[e..e+m.stride]} \n" } return s }   type BinaryFunc64 = fn(f64, f64) f64   fn element_wise_mm(m1 Matrix, m2 Matrix, f BinaryFunc64) Matrix { mut z := like(m1) for i, m1e in m1.ele { z.ele[i] = f(m1e, m2.ele[i]) } return z }   fn element_wise_ms(m Matrix, s f64, f BinaryFunc64) Matrix { mut z := like(m) for i, e in m.ele { z.ele[i] = f(e, s) } return z }   fn add(a f64, b f64) f64 { return a + b } fn sub(a f64, b f64) f64 { return a - b } fn mul(a f64, b f64) f64 { return a * b } fn div(a f64, b f64) f64 { return a / b } fn exp(a f64, b f64) f64 { return math.pow(a, b) }   fn add_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, add) } fn sub_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, sub) } fn mul_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, mul) } fn div_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, div) } fn exp_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, exp) }   fn add_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, add) } fn sub_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, sub) } fn mul_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, mul) } fn div_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, div) } fn exp_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, exp) }   fn h(heading string, m Matrix) { println(heading) print(m) }   fn main() { m1 := matrix_from_rows([[f64(3), 1, 4], [f64(1), 5, 9]]) m2 := matrix_from_rows([[f64(2), 7, 1], [f64(8), 2, 8]]) h("m1:", m1) h("m2:", m2) println('') h("m1 + m2:", add_matrix(m1, m2)) h("m1 - m2:", sub_matrix(m1, m2)) h("m1 * m2:", mul_matrix(m1, m2)) h("m1 / m2:", div_matrix(m1, m2)) h("m1 ^ m2:", exp_matrix(m1, m2)) println('') s := .5 println("s: $s") h("m1 + s:", add_scalar(m1, s)) h("m1 - s:", sub_scalar(m1, s)) h("m1 * s:", mul_scalar(m1, s)) h("m1 / s:", div_scalar(m1, s)) h("m1 ^ s:", exp_scalar(m1, s)) }
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Wren
Wren
import "/fmt" for Fmt import "/matrix" for Matrix   // matrix-matrix element wise ops class MM { static add(m1, m2) { m1 + m2 } static sub(m1, m2) { m1 - m2 }   static mul(m1, m2) { if (!m1.sameSize(m2)) Fiber.abort("Matrices must be of the same size.") var m = Matrix.new(m1.numRows, m1.numCols) for (i in 0...m.numRows) { for (j in 0...m.numCols) m[i, j] = m1[i, j] * m2[i, j] } return m }   static div(m1, m2) { if (!m1.sameSize(m2)) Fiber.abort("Matrices must be of the same size.") var m = Matrix.new(m1.numRows, m1.numCols) for (i in 0...m.numRows) { for (j in 0...m.numCols) m[i, j] = m1[i, j] / m2[i, j] } return m }   static pow(m1, m2) { if (!m1.sameSize(m2)) Fiber.abort("Matrices must be of the same size.") var m = Matrix.new(m1.numRows, m1.numCols) for (i in 0...m.numRows) { for (j in 0...m.numCols) m[i, j] = m1[i, j].pow(m2[i, j]) } return m } }   // matrix-scalar element wise ops class MS { static add(m, s) { m + s } static sub(m, s) { m - s } static mul(m, s) { m * s } static div(m, s) { m / s } static pow(m, s) { m.apply { |e| e.pow(s) } } }   // scalar-matrix element wise ops class SM { static add(s, m) { m + s } static sub(s, m) { -m + s } static mul(s, m) { m * s }   static div(s, m) { var n = Matrix.new(m.numRows, m.numCols) for (i in 0...n.numRows) { for (j in 0...n.numCols) n[i, j] = s / m[i, j] } return n }   static pow(s, m) { var n = Matrix.new(m.numRows, m.numCols) for (i in 0...n.numRows) { for (j in 0...n.numCols) n[i, j] = s.pow(m[i, j]) } return n } }   var m = Matrix.new([ [3, 5, 7], [1, 2, 3], [2, 4, 6] ]) System.print("m:") Fmt.mprint(m, 2, 0) System.print("\nm + m:") Fmt.mprint(MM.add(m, m), 2, 0) System.print("\nm - m:") Fmt.mprint(MM.sub(m, m), 2, 0) System.print("\nm * m:") Fmt.mprint(MM.mul(m, m), 2, 0) System.print("\nm / m:") Fmt.mprint(MM.div(m, m), 2, 0) System.print("\nm ^ m:") Fmt.mprint(MM.pow(m, m), 6, 0)   var s = 2 System.print("\ns = %(s):") System.print("\nm + s:") Fmt.mprint(MS.add(m, s), 2, 0) System.print("\nm - s:") Fmt.mprint(MS.sub(m, s), 2, 0) System.print("\nm * s:") Fmt.mprint(MS.mul(m, s), 2, 0) System.print("\nm / s:") Fmt.mprint(MS.div(m, s), 3, 1) System.print("\nm ^ s:") Fmt.mprint(MS.pow(m, s), 2, 0)   System.print("\ns + m:") Fmt.mprint(SM.add(s, m), 2, 0) System.print("\ns - m:") Fmt.mprint(SM.sub(s, m), 2, 0) System.print("\ns * m:") Fmt.mprint(SM.mul(s, m), 2, 0) System.print("\ns / m:") Fmt.mprint(SM.div(s, m), 8, 6) System.print("\ns ^ m:") Fmt.mprint(SM.pow(s, m), 3, 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.
#BASIC256
BASIC256
# Version without functions (for BASIC-256 ver. 0.9.6.66)   graphsize 390,270   level = 18 : insize = 247 # initial values x = 92 : y = 94 #   iters = 2^level # total number of iterations qiter = 510/iters # constant for computing colors SQ = sqrt(2) : QPI = pi/4 # constants   rotation = 0 : iter = 0 : rq = 1.0 # state variables dim rqs(level) # stack for rq (rotation coefficient)   color white fastgraphics rect 0,0,graphwidth,graphheight refresh gosub dragon refresh imgsave "Dragon_curve_BASIC-256.png", "PNG" end   dragon: if level<=0 then yn = sin(rotation)*insize + y xn = cos(rotation)*insize + x if iter*2<iters then color 0,iter*qiter,255-iter*qiter else color qiter*iter-255,(iters-iter)*qiter,0 end if line x,y,xn,yn iter = iter + 1 x = xn : y = yn return end if insize = insize/SQ rotation = rotation + rq*QPI level = level - 1 rqs[level] = rq : rq = 1 gosub dragon rotation = rotation - rqs[level]*QPI*2 rq = -1 gosub dragon rq = rqs[level] rotation = rotation + rq*QPI level = level + 1 insize = insize*SQ return
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Delphi
Delphi
  program DrawASphere;   {$APPTYPE CONSOLE}   uses SysUtils, Math;   type TDouble3 = array[0..2] of Double; TChar10 = array[0..9] of Char;   var shades: TChar10 = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'); light: TDouble3 = (30, 30, -50 );   procedure normalize(var v: TDouble3); var len: Double; begin len:= sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] := v[0] / len; v[1] := v[1] / len; v[2] := v[2] / len; end;   function dot(x, y: TDouble3): Double; begin Result:= x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; Result:= IfThen(Result < 0, -Result, 0 ); end;   procedure drawSphere(R, k, ambient: Double); var vec: TDouble3; x, y, b: Double; i, j, intensity: Integer; begin for i:= Floor(-R) to Ceil(R) do begin x := i + 0.5; for j:= Floor(-2*R) to Ceil(2 * R) do begin y:= j / 2 + 0.5; if(x * x + y * y <= R * R) then begin vec[0]:= x; vec[1]:= y; vec[2]:= sqrt(R * R - x * x - y * y); normalize(vec); b:= Power(dot(light, vec), k) + ambient; intensity:= IfThen(b <= 0, Length(shades) - 2, Trunc(max( (1 - b) * (Length(shades) - 1), 0 ))); Write(shades[intensity]); end else Write(' '); end; Writeln; end; end;   begin normalize(light); drawSphere(19, 4, 0.1); drawSphere(10, 2, 0.4); Readln; end.  
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Raku
Raku
role DLElem[::T] { has DLElem[T] $.prev is rw; has DLElem[T] $.next is rw; has T $.payload = T;   method pre-insert(T $payload) { die "Can't insert before beginning" unless $!prev; my $elem = ::?CLASS.new(:$payload); $!prev.next = $elem; $elem.prev = $!prev; $elem.next = self; $!prev = $elem; $elem; }   method post-insert(T $payload) { die "Can't insert after end" unless $!next; my $elem = ::?CLASS.new(:$payload); $!next.prev = $elem; $elem.next = $!next; $elem.prev = self; $!next = $elem; $elem; }   method delete { die "Can't delete a sentinel" unless $!prev and $!next; $!next.prev = $!prev; $!prev.next = $!next; # conveniently returns next element } }   role DLList[::DLE] { has DLE $.first; has DLE $.last;   submethod BUILD { $!first = DLE.new; $!last = DLE.new; $!first.next = $!last; $!last.prev = $!first; }   method list { ($!first.next, *.next ...^ !*.next).map: *.payload } method reverse { ($!last.prev, *.prev ...^ !*.prev).map: *.payload } }   class DLElem_Str does DLElem[Str] {} class DLList_Str does DLList[DLElem_Str] {}   my $sdll = DLList_Str.new; my $b = $sdll.first.post-insert('A').post-insert('B'); $b.pre-insert('C'); say $sdll.list; # A C B
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#ContextFree
ContextFree
  startshape START   TIME_IN_SECONDS = 60   shape START { SECOND_HAND[r (TIME_IN_SECONDS*-6)] CIRCLE[s 50 50] }     shape SECOND_HAND { TRIANGLE [[z 1 s 1 30 y 0.26 b 1]] }    
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Oz
Oz
declare proc {Walk Node Action} case Node of nil then skip [] node(value:V next:N ...) then {Action V} {Walk @N Action} end end   proc {WalkBackwards Node Action} Tail = {GetLast Node} proc {Loop N} case N of nil then skip [] node(value:V prev:P ...) then {Action V} {Loop @P} end end in {Loop Tail} end   fun {GetLast Node} case @(Node.next) of nil then Node [] NextNode=node(...) then {GetLast NextNode} end end   fun {CreateNewNode Value} node(prev:{NewCell nil} next:{NewCell nil} value:Value) end   proc {InsertAfter Node NewNode} Next = Node.next in (NewNode.next) := @Next (NewNode.prev) := Node case @Next of nil then skip [] node(prev:NextPrev ...) then NextPrev := NewNode end Next := NewNode end   A = {CreateNewNode a} B = {CreateNewNode b} C = {CreateNewNode c} in {InsertAfter A B} {InsertAfter A C} {Walk A Show} {WalkBackwards A Show}
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pascal
Pascal
enum NEXT,PREV,DATA constant empty_dll = {{1,1}} sequence dll = deep_copy(empty_dll) procedure insert_after(object data, integer pos=1) integer prv = dll[pos][PREV] dll = append(dll,{pos,prv,data}) if prv!=0 then dll[prv][NEXT] = length(dll) end if dll[pos][PREV] = length(dll) end procedure insert_after("ONE") insert_after("TWO") insert_after("THREE") ?dll procedure show(integer d) integer idx = dll[1][d] while idx!=1 do ?dll[idx][DATA] idx = dll[idx][d] end while end procedure show(NEXT) ?"==" show(PREV)
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Phix
Phix
enum NEXT,PREV,DATA type slnode(object x) return (sequence(x) and length(x)=DATA and <i>udt</i>(x[DATA]) and integer(x[NEXT] and integer(x[PREV])) end type
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PicoLisp
PicoLisp
+-----+-----+ +-----+-----+ | Val | ---+---> | | | ---+---> next +-----+-----+ +--+--+-----+ | prev <---+
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PL.2FI
PL/I
  define structure 1 Node, 2 value fixed decimal, 2 back_pointer handle(Node), 2 fwd_pointer handle(Node);   P = NEW(: Node :); /* Creates a node, and lets P point at it. */ get (P => value); /* Reads in a value to the node we just created. */   /* Assuming that back_pointer and fwd_pointer point at other nodes, */ /* we can say ... */ P = P => fwd_pointer; /* P now points at the next node. */ ... P = P => back_pointer; /* P now points at the previous node. */  
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)
#JavaScript
JavaScript
const dutchNationalFlag = () => {   /** * Return the name of the given number in this way: * 0 = Red * 1 = White * 2 = Blue * @param {!number} e */ const name = e => e > 1 ? 'Blue' : e > 0 ? 'White' : 'Red';   /** * Given an array of numbers return true if each number is bigger than * or the same as the previous * @param {!Array<!number>} arr */ const isSorted = arr => arr.every((e,i) => e >= arr[Math.max(i-1, 0)]);   /** * Generator that keeps yielding a random int between 0(inclusive) and * max(exclusive), up till n times, and then is done. * @param max * @param n */ function* randomGen (max, n) { let i = 0; while (i < n) { i += 1; yield Math.floor(Math.random() * max); } }   /** * An array of random integers between 0 and 3 * @type {[!number]} */ const mixedBalls = [...(randomGen(3, 22))];   /** * Sort the given array into 3 sub-arrays and then concatenate those. */ const sortedBalls = mixedBalls .reduce((p,c) => p[c].push(c) && p, [[],[],[]]) .reduce((p,c) => p.concat(c), []);   /** * A verbatim implementation of the Wikipedia pseudo-code * @param {!Array<!number>} A * @param {!number} mid The value of the 'mid' number. In our case 1 as * low is 0 and high is 2 */ const dutchSort = (A, mid) => { let i = 0; let j = 0; let n = A.length - 1; while(j <= n) { if (A[j] < mid) { [A[i], A[j]] = [A[j], A[i]]; i += 1; j += 1; } else if (A[j] > mid) { [A[j], A[n]] = [A[n], A[j]]; n -= 1 } else { j += 1; } } };   console.log(`Mixed balls : ${mixedBalls.map(name).join()}`); console.log(`Is sorted: ${isSorted(mixedBalls)}`);   console.log(`Sorted balls : ${sortedBalls.map(name).join()}`); console.log(`Is sorted: ${isSorted(sortedBalls)}`);   // Only do the dutch sort now as it mutates the mixedBalls array in place. dutchSort(mixedBalls, 1); console.log(`Dutch Sorted balls: ${mixedBalls.map(name).join()}`); console.log(`Is sorted: ${isSorted(mixedBalls)}`); }; dutchNationalFlag();  
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
#Haskell
Haskell
import Graphics.Rendering.OpenGL import Graphics.UI.GLUT   -- Draw a cuboid. Its vertices are those of a unit cube, which is then scaled -- to the required dimensions. We only specify the visible faces, each of -- which is composed of two triangles. The faces are rotated into position and -- rendered with a perspective transformation.   type Fl = GLfloat   cuboid :: IO () cuboid = do color red  ; render front color green ; render side color blue  ; render top   red,green,blue :: Color4 GLfloat red = Color4 1 0 0 1 green = Color4 0 1 0 1 blue = Color4 0 0 1 1   render :: [(Fl, Fl, Fl)] -> IO () render = renderPrimitive TriangleStrip . mapM_ toVertex where toVertex (x,y,z) = vertex $ Vertex3 x y z   front,side,top :: [(Fl,Fl,Fl)] front = vertices [0,1,2,3] side = vertices [4,1,5,3] top = vertices [3,2,5,6]   vertices :: [Int] -> [(Fl,Fl,Fl)] vertices = map (verts !!)   verts :: [(Fl,Fl,Fl)] verts = [(0,0,1), (1,0,1), (0,1,1), (1,1,1), (1,0,0), (1,1,0), (0,1,0)]   transform :: IO () transform = do translate $ Vector3 0 0 (-10 :: Fl) rotate (-14) $ Vector3 0 0 (1 :: Fl) rotate (-30) $ Vector3 0 1 (0 :: Fl) rotate 25 $ Vector3 1 0 (0 :: Fl) scale 2 3 (4 :: Fl) translate $ Vector3 (-0.5) (-0.5) (-0.5 :: Fl)   display :: IO () display = do clear [ColorBuffer] perspective 40 1 1 (15 :: GLdouble) transform cuboid flush   main :: IO () main = do let name = "Cuboid" initialize name [] createWindow name displayCallback $= display mainLoop
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#zkl
zkl
vname:="foo"; // or vname:=ask("var name = "); klass:=Compiler.Compiler.compileText("var %s=123".fmt(vname))(); // compile & run the constructor klass.vars.println(); klass.foo.println(); klass.setVar(vname).println(); // setVar(name,val) sets the var
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Zsh
Zsh
read name typeset $name=42
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#SmileBASIC
SmileBASIC
XSCREEN 3 DISPLAY 1 GPSET 100, 100, RGB(255, 0, 0) WAIT 60
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Standard_ML
Standard ML
open XWindows ; open Motif ;   val imgWindow = fn () =>   let val shell = XtAppInitialise "" "demo" "top" [] [ XmNwidth 320, XmNheight 240 ] ; val main = XmCreateMainWindow shell "main" [ XmNmappedWhenManaged true ]  ; val canvas = XmCreateDrawingArea main "drawarea" [ XmNwidth 320, XmNheight 240 ] ; val usegc = DefaultGC (XtDisplay canvas) ; val put = fn (w,s,t) => ( XSetForeground usegc 0xff0000 ; XDrawPoint (XtWindow canvas) usegc ( XPoint {x=100,y=100} ) ; t); in   ( XtSetCallbacks canvas [ (XmNexposeCallback , put) ] XmNarmCallback ; XtManageChild canvas ; XtManageChild main ; XtRealizeWidget shell )   end;
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Tcl
Tcl
package require Tcl 8.5 package require Tk   pack [canvas .c -width 320 -height 240 -bg #fff] -anchor nw .c create rectangle 100 100 100 100 -fill #f00 -outline ""
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#Tcl
Tcl
# matrix operation support: package require math::linearalgebra namespace import ::math::linearalgebra::matmul namespace import ::math::linearalgebra::crossproduct namespace import ::math::linearalgebra::dotproduct namespace import ::math::linearalgebra::sub   # returns a cube as a list of faces, # where each face is a list of (3space) points proc make_cube {{radius 1}} { set dirs { A { 1 1 1} B { 1 1 -1} C { 1 -1 -1} D { 1 -1 1} E {-1 1 1} F {-1 1 -1} G {-1 -1 -1} H {-1 -1 1} } set faces { {A B C D} {D C G H} {H G F E} {E F B A} {A D H E} {C B F G} } lmap fa $faces { lmap dir $fa { lmap x [dict get $dirs $dir] { expr {1.0 * $x * $radius} } } } }   # a matrix constructor proc Matrix {m} { tailcall lmap row $m { lmap e $row { expr 1.0*($e) } } }   proc identity {} { Matrix { {1 0 0} {0 1 0} {0 0 1} } }   # some matrices useful for animation: proc rotateZ {theta} { Matrix { { cos($theta) -sin($theta) 0 } { sin($theta) cos($theta) 0 } { 0 0 1 } } } proc rotateY {theta} { Matrix { { sin($theta) 0 cos($theta) } { 0 1 0 } { cos($theta) 0 -sin($theta) } } } proc rotateX {theta} { Matrix { { 1 0 0 } { 0 cos($theta) -sin($theta) } { 0 sin($theta) cos($theta) } } }   proc camera {flen} { Matrix { { $flen 0 0 } { 0 $flen 0 } { 0 0 0 } } }   proc render {canvas object} {   set W [winfo width $canvas] set H [winfo height $canvas]   set fl 1.0 set t [expr {[clock microseconds] / 1000000.0}]   set transform [identity] set transform [matmul $transform [rotateX [expr {atan(1)}]]] set transform [matmul $transform [rotateZ [expr {atan(1)}]]]   set transform [matmul $transform [rotateY $t]] set transform [matmul $transform [camera $fl]]   foreach face $object { # do transformations into screen space: set points [lmap p $face { matmul $p $transform }] # calculate a normal set o [lindex $points 0] set v1 [sub [lindex $points 1] $o] set v2 [sub [lindex $points 2] $o] set normal [crossproduct $v1 $v2]   set cosi [dotproduct $normal {0 0 -1.0}] if {$cosi <= 0} { ;# rear-facing! continue }   set points [lmap p $points { lassign $p x y list [expr {$x + $W/2}] [expr {$y + $H/2}] }] set points [concat {*}$points] $canvas create poly $points -outline black -fill red } }   package require Tk pack [canvas .c] -expand yes -fill both   proc tick {} { .c delete all render .c $::world after 50 tick } set ::world [make_cube 100] tick
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) M:=GSL.Matrix(3,3).set(3,5,7, 1,2,3, 2,4,6); x:=2; println("M = \n%s\nx = %s".fmt(M.format(),x)); foreach op in (T('+,'-,'*,'/)){ println("M %s x:\n%s\n".fmt(op.toString()[3,1],op(M.copy(),x).format())); } foreach op in (T("addElements","subElements","mulElements","divElements")){ println("M %s M:\n%s\n".fmt(op, M.copy().resolve(op)(M).format())); } mSqrd:=M.pump(0,M.copy(),fcn(x){ x*x }); // M element by element println("M square elements:\n%s\n".fmt(mSqrd.format()));
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.
#BBC_BASIC
BBC BASIC
MODE 8 MOVE 800,400 GCOL 11 PROCdragon(512, 12, 1) END   DEF PROCdragon(size, split%, d) PRIVATE angle IF split% = 0 THEN DRAW BY -COS(angle)*size, SIN(angle)*size ELSE angle += d*PI/4 PROCdragon(size/SQR(2), split%-1, 1) angle -= d*PI/2 PROCdragon(size/SQR(2), split%-1, -1) angle += d*PI/4 ENDIF ENDPROC
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#DWScript
DWScript
  type TFloat3 = array[0..2] of Float;   var light : TFloat3 = [ 30, 30, -50 ];   procedure normalize(var v : TFloat3); var len: Float; begin len := sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; end;   function dot(x, y : TFloat3) : Float; begin Result := x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; if Result<0 then Result:=-Result else Result:=0; end;   procedure drawSphere(R, k, ambient : Float); var vec : TFloat3; x, y, b : Float; i, j, size, intensity : Integer; begin size:=Trunc(Ceil(R)-Floor(-R)+1); PrintLn('P2'); PrintLn(IntToStr(size)+' '+IntToStr(size)); PrintLn('255'); for i := Floor(-R) to Ceil(R) do begin x := i + 0.5; for j := Floor(-R) to Ceil(R) do begin y := j + 0.5; if (x * x + y * y <= R * R) then begin vec[0] := x; vec[1] := y; vec[2] := sqrt(R * R - x * x - y * y); normalize(vec); b := Power(dot(light, vec), k) + ambient; intensity := ClampInt( Round(b*255), 0, 255); Print(intensity); Print(' ') end else Print('0 '); end; PrintLn(''); end; end;   normalize(light); drawSphere(19, 4, 0.1);