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/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
#JavaScript
JavaScript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> canvas { background-color: black; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.querySelector("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight;   var g = canvas.getContext("2d");   var nodes = [[-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1], [1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1]];   var edges = [[0, 1], [1, 3], [3, 2], [2, 0], [4, 5], [5, 7], [7, 6], [6, 4], [0, 4], [1, 5], [2, 6], [3, 7]];   function scale(factor0, factor1, factor2) { nodes.forEach(function (node) { node[0] *= factor0; node[1] *= factor1; node[2] *= factor2; }); }   function rotateCuboid(angleX, angleY) {   var sinX = Math.sin(angleX); var cosX = Math.cos(angleX);   var sinY = Math.sin(angleY); var cosY = Math.cos(angleY);   nodes.forEach(function (node) { var x = node[0]; var y = node[1]; var z = node[2];   node[0] = x * cosX - z * sinX; node[2] = z * cosX + x * sinX;   z = node[2];   node[1] = y * cosY - z * sinY; node[2] = z * cosY + y * sinY; }); }   function drawCuboid() { g.save();   g.clearRect(0, 0, canvas.width, canvas.height); g.translate(canvas.width / 2, canvas.height / 2); g.strokeStyle = "#FFFFFF"; g.beginPath();   edges.forEach(function (edge) { var p1 = nodes[edge[0]]; var p2 = nodes[edge[1]]; g.moveTo(p1[0], p1[1]); g.lineTo(p2[0], p2[1]); });   g.closePath(); g.stroke();   g.restore(); }   scale(200, 200, 200); rotateCuboid(Math.PI / 4, Math.atan(Math.sqrt(2)));   setInterval(function() { rotateCuboid(Math.PI / 180, 0); drawCuboid(); }, 17);   </script>   </body> </html>
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.
#Phix
Phix
constant m = {{7, 8, 7},{4, 0, 9}}, m2 = {{4, 5, 1},{6, 2, 1}} ?{m,"+",m2,"=",sq_add(m,m2)} ?{m,"-",m2,"=",sq_sub(m,m2)} ?{m,"*",m2,"=",sq_mul(m,m2)} ?{m,"/",m2,"=",sq_div(m,m2)} ?{m,"^",m2,"=",sq_power(m,m2)} ?{m,"+ 3 =",sq_add(m,3)} ?{m,"- 3 =",sq_sub(m,3)} ?{m,"* 3 =",sq_mul(m,3)} ?{m,"/ 3 =",sq_div(m,3)} ?{m,"^ 3 =",sq_power(m,3)}
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#BASIC
BASIC
clg color white rect 0,0,graphwidth, graphheight for n = 1 to 100 color rgb(2*n,2*n,2*n) circle 150-2*n/3,150-n/2,150-n next n
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#FreeBASIC
FreeBASIC
#define FIL 1 #define DATO 2 #define LPREV 3 #define LNEXT 4   Dim Shared As Integer countNodes, Nodes countNodes = 0 Nodes = 10   Dim Shared As Integer list(Nodes, 4) list(0, LNEXT) = 1   Function searchNode(node As Integer) As Integer Dim As Integer Node11   For i As Integer = 0 To node-1 Node11 = list(Node11, LNEXT) Next i Return Node11 End Function   Sub insertNode(node As Integer, newNode As Integer) Dim As Integer Node11, i   If countNodes = 0 Then node = 2   For i = 1 To Nodes If Not list(i, FIL) Then Exit For Next list(i, FIL) = True list(i, DATO) = newNode   Node11 = searchNode(node)   list(i, LPREV) = list(Node11, LPREV) list(list(i, LPREV), LNEXT) = i If i <> Node11 Then list(i, LNEXT) = Node11 : list(Node11, LPREV) = i   countNodes += 1 If countNodes = Nodes Then Nodes += 10 : Redim list(Nodes, 4) End Sub   Sub removeNode(n As Integer) Dim As Integer Node11 = searchNode(n) list(list(Node11, LPREV), LNEXT) = list(Node11, LNEXT) list(list(Node11, LNEXT), LPREV) = list(Node11, LPREV) list(Node11, LNEXT) = 0 list(Node11, LPREV) = 0 list(Node11, FIL) = False countNodes -= 1 End Sub   Sub printNode(node As Integer) Dim As Integer Node11 = searchNode(node) Print list(Node11, DATO); Print End Sub   Sub traverseList() For i As Integer = 1 To countNodes printNode(i) Next i End Sub   insertNode(1, 1000) insertNode(2, 2000) insertNode(2, 3000)   traverseList()   removeNode(2)   Print traverseList() Sleep
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
#Delphi
Delphi
uses system ;   type   // declare the list pointer type plist = ^List ;   // declare the list type, a generic data pointer prev and next pointers List = record data : pointer ; prev : pList ; next : pList ; end;   // since this task is just showing the traversal I am not allocating the memory and setting up the root node etc. // Note the use of the carat symbol for de-referencing the pointer.   begin   // beginning to end while not (pList^.Next = NIL) do pList := pList^.Next ;   // end to beginning while not (pList^.prev = NIL) do pList := pList^.prev ;   end;
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#E
E
def traverse(list) { var node := list.atFirst() while (true) { println(node[]) if (node.hasNext()) { node := node.next() } else { break } } while (true) { println(node[]) if (node.hasPrev()) { node := node.prev() } else { break } } }
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
#C.23
C#
class Link { public int Item { get; set; } public Link Prev { get; set; } public Link Next { get; set; }   //A constructor is not neccessary, but could be useful public Link(int item, Link prev = null, Link next = null) { Item = item; Prev = prev; Next = next; } }
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C.2B.2B
C++
template <typename T> struct Node { Node* next; Node* prev; T data; };
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)
#Ceylon
Ceylon
import ceylon.random {   DefaultRandom }   abstract class Colour(name, ordinal) of red | white | blue satisfies Comparable<Colour> { shared String name; shared Integer ordinal; string => name; compare(Colour other) => this.ordinal <=> other.ordinal; }   object red extends Colour("red", 0) {} object white extends Colour("white", 1) {} object blue extends Colour("blue", 2) {}   Colour[] allColours = `Colour`.caseValues;   shared void run() {   function ordered({Colour*} colours) => colours.paired.every(([c1, c2]) => c1 <= c2);   value random = DefaultRandom();   function randomBalls(Integer length = 15) { while (true) { value balls = random.elements(allColours).take(length); if (!ordered(balls)) { return balls.sequence(); } } }   function dutchSort({Colour*} balls, Colour mid = white) { value array = Array { *balls }; if (array.empty) { return []; } variable value i = 0; variable value j = 0; variable value n = array.size - 1; while (j <= n) { assert (exists ball = array[j]); if (ball < mid) { array.swap(i, j); i ++; j ++; } else if (ball > mid) { array.swap(n, j); n --; } else { j ++; } } return array; }   function idiomaticSort({Colour*} balls) => balls.sort(increasing);   value initialBalls = randomBalls();   "the initial balls are not randomized" assert (!ordered(initialBalls));   print(initialBalls);   value sortedBalls1 = idiomaticSort(initialBalls); value sortedBalls2 = dutchSort(initialBalls);   "the idiomatic sort didn't work" assert (ordered(sortedBalls1));   "the dutch sort didn't work" assert (ordered(sortedBalls2));   print(sortedBalls1); print(sortedBalls2); }
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)
#Clojure
Clojure
(defn dutch-flag-order [color] (get {:red 1 :white 2 :blue 3} color))   (defn sort-in-dutch-flag-order [balls] (sort-by dutch-flag-order balls))   ;; Get a collection of 'n' balls of Dutch-flag colors (defn random-balls [num-balls] (repeatedly num-balls #(rand-nth [:red :white :blue])))   ;; Get random set of balls and insure they're not accidentally sorted (defn starting-balls [num-balls] (let [balls (random-balls num-balls) in-dutch-flag-order? (= balls (sort-in-dutch-flag-order balls))] (if in-dutch-flag-order? (recur num-balls) balls)))
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#C
C
  #include <stdio.h> #include <stdlib.h> #include <math.h>   const char *shades = ".:!*oe&#%@";   void vsub(double *v1, double *v2, double *s) { s[0] = v1[0] - v2[0]; s[1] = v1[1] - v2[1]; s[2] = v1[2] - v2[2]; }   double normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; return len; }   double dot(double *x, double *y) { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; }   double * cross(double x[3], double y[3], double s[3]) { s[0] = x[1] * y[2] - x[2] * y[1]; s[1] = x[2] * y[0] - x[0] * y[2]; s[2] = x[0] * y[1] - x[1] * y[0]; return s; }   double* madd(double *x, double *y, double d, double *r) { r[0] = x[0] + y[0] * d; r[1] = x[1] + y[1] * d; r[2] = x[2] + y[2] * d; return r; }   double v000[] = { -4, -3, -2 }; double v100[] = { 4, -3, -2 }; double v010[] = { -4, 3, -2 }; double v110[] = { 4, 3, -2 }; double v001[] = { -4, -3, 2 }; double v101[] = { 4, -3, 2 }; double v011[] = { -4, 3, 2 }; double v111[] = { 4, 3, 2 };   typedef struct { double * v[4]; double norm[3]; } face_t;   face_t f[] = { { { v000, v010, v110, v100 }, { 0, 0, -1 } }, { { v001, v011, v111, v101 }, { 0, 0, 1 } }, { { v000, v010, v011, v001 }, { -1, 0, 0 } }, { { v100, v110, v111, v101 }, { 1, 0, 0 } }, { { v000, v100, v101, v001 }, { 0, -1, 0 } }, { { v010, v110, v111, v011 }, { 0, 1, 0 } }, };   int in_range(double x, double x0, double x1) { return (x - x0) * (x - x1) <= 0; }   int face_hit(face_t *face, double src[3], double dir[3], double hit[3], double *d) { int i; double dist; for (i = 0; i < 3; i++) if (face->norm[i]) dist = (face->v[0][i] - src[i]) / dir[i];   madd(src, dir, dist, hit); *d = fabs(dot(dir, face->norm) * dist);   if (face->norm[0]) { return in_range(hit[1], face->v[0][1], face->v[2][1]) && in_range(hit[2], face->v[0][2], face->v[2][2]); } else if (face->norm[1]) { return in_range(hit[0], face->v[0][0], face->v[2][0]) && in_range(hit[2], face->v[0][2], face->v[2][2]); } else if (face->norm[2]) { return in_range(hit[0], face->v[0][0], face->v[2][0]) && in_range(hit[1], face->v[0][1], face->v[2][1]); } return 0; }   int main() { int i, j, k; double eye[3] = { 7, 7, 6 }; double dir[3] = { -1, -1, -1 }, orig[3] = {0, 0, 0}; double hit[3], dx[3], dy[3] = {0, 0, 1}, proj[3]; double d, *norm, dbest, b; double light[3] = { 6, 8, 6 }, ldist[3], decay, strength = 10;   normalize(cross(eye, dy, dx)); normalize(cross(eye, dx, dy));   for (i = -10; i <= 17; i++) { for (j = -35; j < 35; j++) { vsub(orig, orig, proj); madd(madd(proj, dx, j / 6., proj), dy, i/3., proj); vsub(proj, eye, dir); dbest = 1e100; norm = 0; for (k = 0; k < 6; k++) { if (!face_hit(f + k, eye, dir, hit, &d)) continue; if (dbest > d) { dbest = d; norm = f[k].norm; } }   if (!norm) { putchar(' '); continue; }   vsub(light, hit, ldist); decay = normalize(ldist); b = dot(norm, ldist) / decay * strength; if (b < 0) b = 0; else if (b > 1) b = 1; b += .2; if (b > 1) b = 0; else b = 1 - b; putchar(shades[(int)(b * (sizeof(shades) - 2))]); } putchar('\n'); }   return 0; }
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.
#PicoLisp
PicoLisp
(de userVariable () (prin "Enter a variable name: ") (let Var (line T) # Read transient symbol (prin "Enter a value: ") (set Var (read)) # Set symbol's value (println 'Variable Var 'Value (val Var)) ) ) # Print them
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.
#PowerShell
PowerShell
$variableName = Read-Host New-Variable $variableName 'Foo' Get-Variable $variableName
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.
#ProDOS
ProDOS
editvar /newvar /value=a /userinput=1 /title=Enter a variable name: editvar /newvar /value=b /userinput=1 /title=Enter a variable title: editvar /newvar /value=-a- /title=-b-
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Oberon
Oberon
MODULE pixel;   IMPORT XYplane;   BEGIN XYplane.Open; XYplane.Dot(100, 100, XYplane.draw); REPEAT UNTIL XYplane.Key() = "q" END pixel.  
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
#Objeck
Objeck
use Game.SDL2; use Game.Framework;   class DrawPixel { @framework : GameFramework;   function : Main(args : String[]) ~ Nil { DrawPixel->New()->Run(); }   New() { @framework := GameFramework->New(320, 240, "RGB"); @framework->SetClearColor(Color->New(0, 0, 0)); }   method : Run() ~ Nil { if(@framework->IsOk()) { e := @framework->GetEvent();   quit := false; while(<>quit) { @framework->FrameStart(); @framework->Clear();   while(e->Poll() <> 0) { if(e->GetType() = EventType->SDL_QUIT) { quit := true; }; };   @framework->GetRenderer()->SetDrawColor(255, 0, 0, 255); @framework->GetRenderer()->DrawPoint(100, 100);   @framework->Show(); @framework->FrameEnd(); }; } else { "--- Error Initializing Game Environment ---"->ErrorLine(); return; };   leaving { @framework->Quit(); }; } }  
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
#Racket
Racket
#lang racket   (define (quotient/remainder-egyptian dividend divisor (trace? #f)) (define table (for*/list ((power_of_2 (sequence-map (curry expt 2) (in-naturals))) (doubling (in-value (* divisor power_of_2))) #:break (> doubling dividend)) (list power_of_2 doubling)))   (when trace? (displayln "Table\npow_2\tdoubling") (for ((row table)) (printf "~a\t~a~%" (first row) (second row))))   (define-values (answer accumulator) (for*/fold ((answer 0) (accumulator 0)) ((row (reverse table)) (acc′ (in-value (+ accumulator (second row))))) (when trace? (printf "row:~a\tans/acc:~a ~a\t" row answer accumulator)) (cond [(<= acc′ dividend) (define ans′ (+ answer (first row))) (when trace? (printf "~a <= ~a -> ans′/acc′:~a ~a~%" acc′ dividend ans′ acc′)) (values ans′ acc′)] [else (when trace? (printf "~a > ~a [----]~%" acc′ dividend)) (values answer accumulator)])))   (values answer (- dividend accumulator)))   (module+ test (require rackunit) (let-values (([q r] (quotient/remainder-egyptian 580 34))) (check-equal? q 17) (check-equal? r 2))   (let-values (([q r] (quotient/remainder-egyptian 192 3))) (check-equal? q 64) (check-equal? r 0)))   (module+ main (quotient/remainder-egyptian 580 34 #t))
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
#Raku
Raku
sub egyptian-divmod (Real $dividend is copy where * >= 0, Real $divisor where * > 0) { my $accumulator = 0; ([1, $divisor], { [.[0] + .[0], .[1] + .[1]] } … ^ *.[1] > $dividend) .reverse.map: { $dividend -= .[1], $accumulator += .[0] if $dividend >= .[1] } $accumulator, $dividend; }   #TESTING for 580,34, 578,34, 7532795332300578,235117 -> $n, $d { printf "%s divmod %s = %s remainder %s\n", $n, $d, |egyptian-divmod( $n, $d ) }
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that 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
#Raku
Raku
role Egyptian { method gist { join ' + ', ("[{self.floor}]" if self.abs >= 1), map {"1/$_"}, self.denominators; } method denominators { my ($x, $y) = self.nude; $x %= $y; my @denom = gather ($x, $y) = -$y % $x, $y * take ($y / $x).ceiling while $x; } }   say .nude.join('/'), " = ", $_ but Egyptian for 43/48, 5/121, 2014/59;   my @sample = map { $_ => .denominators }, grep * < 1, map {$_ but Egyptian}, (2 .. 99 X/ 2 .. 99);   say .key.nude.join("/"), " has max denominator, namely ", .value.max given max :by(*.value.max), @sample;   say .key.nude.join("/"), " has max number of denominators, namely ", .value.elems given max :by(*.value.elems), @sample;
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
#UNIX_Shell
UNIX Shell
halve() { expr "$1" / 2 }   double() { expr "$1" \* 2 }   is_even() { expr "$1" % 2 = 0 >/dev/null }   ethiopicmult() { plier=$1 plicand=$2 r=0 while [ "$plier" -ge 1 ]; do is_even "$plier" || r=`expr $r + "$plicand"` plier=`halve "$plier"` plicand=`double "$plicand"` done echo $r }   ethiopicmult 17 34 # => 578
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#Wren
Wren
import "/fmt" for Conv   var SIZE = 32 var LINES = SIZE / 2 var RULE = 90   var ruleTest = Fn.new { |x| (RULE & (1 << (7 & x))) != 0 }   var bshl = Fn.new { |b, bitCount| Conv.btoi(b) << bitCount }   var evolve = Fn.new { |s| var t = List.filled(SIZE, false) t[SIZE-1] = ruleTest.call(bshl.call(s[0], 2) | bshl.call(s[SIZE-1], 1) | Conv.btoi(s[SIZE-2])) t[0] = ruleTest.call(bshl.call(s[1], 2) | bshl.call(s[0], 1) | Conv.btoi(s[SIZE-1])) for (i in 1...SIZE - 1) { t[i] = ruleTest.call(bshl.call(s[i+1], 2) | bshl.call(s[i], 1) | Conv.btoi(s[i-1])) } for (i in 0...SIZE) s[i] = t[i] }   var show = Fn.new { |s| for (i in SIZE - 1..0) System.write(s[i] ? "*" : " ") System.print() }   var state = List.filled(SIZE, false) state[LINES] = true System.print("Rule %(RULE):") for (i in 0...LINES) { show.call(state) evolve.call(state) }
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
#Wrapl
Wrapl
DEF fac(n) n <= 1 | PROD 1:to(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.
#REALbasic
REALbasic
  Class EchoSocket Inherits TCPSocket Sub DataAvailable() If Instr(Me.LookAhead, EndofLine.Windows) > 0 Then Dim data As String = Me.ReadAll Dim lines() As String = Split(data, EndofLine.Windows) For i As Integer = 0 To Ubound(lines) Me.Write(lines(i) + EndOfLine.Windows) Print(lines(i)) Next End If End Sub End Class   Class EchoServer Inherits ServerSocket Function AddSocket() As TCPSocket Return New EchoSocket End Function End Class   Class App Inherits ConsoleApplication Function Run(args() As String) As Integer Listener = New EchoServer Listener.Port = 12321 Listener.Listen() While True DoEvents() 'pump the event loop Wend End Function Private Listener As EchoServer End Class  
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#Ruby
Ruby
def main intervals = [ [2, 1000, true], [1000, 4000, true], [2, 10000, false], [2, 100000, false], [2, 1000000, false], [2, 10000000, false], [2, 100000000, false], [2, 1000000000, false] ] for intv in intervals (start, ending, display) = intv if start == 2 then print "eban numbers up to and including %d:\n" % [ending] else print "eban numbers between %d and %d (inclusive):\n" % [start, ending] end   count = 0 for i in (start .. ending).step(2) b = (i / 1000000000).floor r = (i % 1000000000) m = (r / 1000000).floor r = (r % 1000000) t = (r / 1000).floor r = (r % 1000) if m >= 30 and m <= 66 then m = m % 10 end if t >= 30 and t <= 66 then t = t % 10 end if r >= 30 and r <= 66 then r = r % 10 end if b == 0 or b == 2 or b == 4 or b == 6 then if m == 0 or m == 2 or m == 4 or m == 6 then if t == 0 or t == 2 or t == 4 or t == 6 then if r == 0 or r == 2 or r == 4 or r == 6 then if display then print ' ', i end count = count + 1 end end end end end if display then print "\n" end print "count = %d\n\n" % [count] end end   main()
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
#Julia
Julia
using Makie, LinearAlgebra   N = 40 interval = 0.10   scene = mesh(FRect3D(Vec3f0(-0.5), Vec3f0(1)), color = :skyblue2) rect = scene[end]   for rad in 0.5:1/N:8.5 arr = normalize([cospi(rad/2), 0, sinpi(rad/2), -sinpi(rad/2)]) Makie.rotate!(rect, Quaternionf0(arr[1], arr[2], arr[3], arr[4])) sleep(interval) 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.
#PicoLisp
PicoLisp
(de elementWiseMatrix (Fun Mat1 Mat2) (mapcar '((L1 L2) (mapcar Fun L1 L2)) Mat1 Mat2) )   (de elementWiseScalar (Fun Mat Scalar) (elementWiseMatrix Fun Mat (circ (circ Scalar))) )
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.
#PL.2FI
PL/I
declare (matrix(3,3), vector(3), scalar) fixed; declare (m(3,3), v(3) fixed;   m = scalar * matrix; m = vector * matrix; m = matrix * matrix;   v = scalar * vector; v = vector * vector;
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
#Batch_File
Batch File
:: Draw a Sphere Task from Rosetta Code :: Batch File Implementation   @echo off rem -------------- define arithmetic "functions" rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=6744 rem integer sqrt arithmetic function by Aacini and penpen rem source: https://www.dostips.com/forum/viewtopic.php?f=3&t=5819&start=30#p44016 set "sqrt(N)=( M=(N),j=M/(11*1024)+40, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j+=(M-j*j)>>31 )" rem -------------- define batch file macros with parameters appended rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=2518 setlocal disabledelayedexpansion % == required for macro ==% (set \n=^^^ %== this creates escaped line feed for macro ==% ) rem normalize macro rem argument: v set normalize=for %%# in (1 2) do if %%#==2 ( %\n% for /f "tokens=1" %%a in ("!args!") do set "v=%%a" %\n% set /a "length_sqrd=!v![0]*!v![0]+!v![1]*!v![1]+!v![2]*!v![2]" %\n% set /a "length=%sqrt(N):N=!length_sqrd!%" %== sqrt(N) applied ==% %\n% set /a "!v![0]*=100", "!v![1]*=100", "!v![2]*=100" %== normalized elements mult. by 100 ==% %\n% set /a "!v![0]/=length", "!v![1]/=length", "!v![2]/=length" %\n% ) else set args= rem dot macro rem arguments: s t outputvar set dot=for %%# in (1 2) do if %%#==2 ( %\n% for /f "tokens=1,2,3" %%a in ("!args!") do ( %\n% set "s=%%a" %\n% set "t=%%b" %\n% set "outputvar=%%c" %\n% ) %\n% set /a "d=!s![0]*!t![0]+!s![1]*!t![1]+!s![2]*!t![2]" %\n% if !d! lss 0 (set /a "!outputvar!=-d") else (set "!outputvar!=0") %\n% ) else set args= rem -------------- define pseudo-arrays set "shades[0]=." set "shades[1]=:" set "shades[2]=!" set "shades[3]=*" set "shades[4]=o" set "shades[5]=e" set "shades[6]=&" set "shades[7]=#" set "shades[8]=%%" set "shades[9]=@" set "num_shades=9" %== start at 0 ==%   set "light[0]=30" & set "light[1]=30" & set "light[2]=-50" rem -------------- main thing: execute drawSphere setlocal enabledelayedexpansion %normalize% light %== normalize macro applied ==% call :drawSphere 20 1 exit /b 0 rem -------------- the function to draw the sphere rem arguments: R ambient :drawSphere rem initialize variables from arguments set /a "R=%1", "negR=-R", "twiceR=R*2", "twiceNegR=negR*2" set /a "sqrdR=R*R*100*100" %== R*R is mult. by 100*100 ==% set "k=2" %== k is hardcoded to 2 ==% set "ambient=%3" rem start draw line-by-line for /l %%i in (%negR%, 1, %R%) do ( set /a "x=100*%%i+(100/2)" %== x is mult. by 100 ==% set "line=" for /l %%j in (%twiceNegR%, 1, %twiceR%) do ( set /a "y=(100/2)*%%j+(100/2)" %== y is mult. by 100 ==% set /a "pythag = x*x + y*y" if !pythag! lss !sqrdR! ( set /a "vec[0]=x" set /a "vec[1]=y" set /a "vec[2]=sqrdR-pythag" set /a "vec[2]=%sqrt(N):N=!vec[2]!%" %== sqrt(N) applied ==% %normalize% vec %== normalize macro applied ==% %dot% light vec dot_out %== dot macro applied ==% rem since both light and vec are normalized to 100, rem then dot_out is scaled up by 100*100 now. set /a "dot_out/=100" %== scale-down to 100*[actual] to prevent overflow before exponentiation ==% set "scaleup=1" %== after exponentiation, b would be scaleup*[actual] ==% set "b=1" for /l %%? in (1,1,%k%) do set /a "b*=dot_out","scaleup*=100" %== exponentiation ==% set /a "b+=ambient*scaleup/10" %== add ambient/10 to b ==% set /a "b/=scaleup/100" %== scale-down to 100*[actual] ==% set /a "intensity=(100-b)*num_shades" set /a "intensity/=100" %== final scale-down ==% if !intensity! lss 0 set "intensity=0" if !intensity! gtr %num_shades% set "intensity=%num_shades%" for %%c in (!intensity!) do set "line=!line!!shades[%%c]!" ) else ( set "line=!line! " ) ) echo(!line! ) goto :EOF
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
#Go
Go
package main   import "fmt"   type dlNode struct { string next, prev *dlNode }   type dlList struct { head, tail *dlNode }   func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" }   func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node }   func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } }   func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) }
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Haskell
Haskell
  insert _ Leaf = Leaf insert nv l@(Node pl v r) = (\(Node c _ _) -> c) new where new = updateLeft left . updateRight right $ Node l nv r left = Node pl v new right = case r of Leaf -> Leaf Node _ v r -> Node new v r  
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
#Erlang
Erlang
  open System.Collections.Generic   let first (l: LinkedList<char>) = l.First let last (l: LinkedList<char>) = l.Last   let next (l: LinkedListNode<char>) = l.Next let prev (l: LinkedListNode<char>) = l.Previous   let traverse g f (ls: LinkedList<char>) = let rec traverse (l: LinkedListNode<char>) = match l with | null -> () | _ -> printf "%A" l.Value traverse (f l) traverse (g ls)   let traverseForward = traverse first next let traverseBackward = traverse last prev   let cs = LinkedList(['a'..'z'])   traverseForward cs printfn "" traverseBackward cs  
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
#F.23
F#
  open System.Collections.Generic   let first (l: LinkedList<char>) = l.First let last (l: LinkedList<char>) = l.Last   let next (l: LinkedListNode<char>) = l.Next let prev (l: LinkedListNode<char>) = l.Previous   let traverse g f (ls: LinkedList<char>) = let rec traverse (l: LinkedListNode<char>) = match l with | null -> () | _ -> printf "%A" l.Value traverse (f l) traverse (g ls)   let traverseForward = traverse first next let traverseBackward = traverse last prev   let cs = LinkedList(['a'..'z'])   traverseForward cs printfn "" traverseBackward cs  
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
#Clojure
Clojure
(defrecord Node [prev next data])   (defn new-node [prev next data] (Node. (ref prev) (ref next) data))
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
#Common_Lisp
Common Lisp
(defstruct dlist head tail) (defstruct dlink content prev 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
#D
D
struct Node(T) { T data; typeof(this)* prev, next; }   void main() { alias N = Node!int; N* n = new N(10); }
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)
#D
D
import std.stdio, std.random, std.algorithm, std.traits, std.array;   enum DutchColors { red, white, blue }   void dutchNationalFlagSort(DutchColors[] items) pure nothrow @nogc { int lo, mid, hi = items.length - 1;   while (mid <= hi) final switch (items[mid]) { case DutchColors.red: swap(items[lo++], items[mid++]); break; case DutchColors.white: mid++; break; case DutchColors.blue: swap(items[mid], items[hi--]); break; } }   void main() { DutchColors[12] balls; foreach (ref ball; balls) ball = uniform!DutchColors;   writeln("Original Ball order:\n", balls); balls.dutchNationalFlagSort; writeln("\nSorted Ball Order:\n", balls); assert(balls[].isSorted, "Balls not 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
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms;   namespace Cuboid { public partial class Form1 : Form { double[][] nodes = { new double[] {-1, -1, -1}, new double[] {-1, -1, 1}, new double[] {-1, 1, -1}, new double[] {-1, 1, 1}, new double[] {1, -1, -1}, new double[] {1, -1, 1}, new double[] {1, 1, -1}, new double[] {1, 1, 1} };   int[][] edges = { new int[] {0, 1}, new int[] {1, 3}, new int[] {3, 2}, new int[] {2, 0}, new int[] {4, 5}, new int[] {5, 7}, new int[] {7, 6}, new int[] {6, 4}, new int[] {0, 4}, new int[] {1, 5}, new int[] {2, 6}, new int[] {3, 7}};   private int mouseX; private int prevMouseX; private int prevMouseY; private int mouseY;   public Form1() { Width = Height = 640; StartPosition = FormStartPosition.CenterScreen; SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);   MouseMove += (s, e) => { prevMouseX = mouseX; prevMouseY = mouseY; mouseX = e.X; mouseY = e.Y;   double incrX = (mouseX - prevMouseX) * 0.01; double incrY = (mouseY - prevMouseY) * 0.01;   RotateCuboid(incrX, incrY); Refresh(); };   MouseDown += (s, e) => { mouseX = e.X; mouseY = e.Y; };   Scale(80, 120, 160); RotateCuboid(Math.PI / 5, Math.PI / 9); }   private void RotateCuboid(double angleX, double angleY) { double sinX = Math.Sin(angleX); double cosX = Math.Cos(angleX);   double sinY = Math.Sin(angleY); double cosY = Math.Cos(angleY);   foreach (var node in nodes) { double x = node[0]; double y = node[1]; double z = node[2];   node[0] = x * cosX - z * sinX; node[2] = z * cosX + x * sinX;   z = node[2];   node[1] = y * cosY - z * sinY; node[2] = z * cosY + y * sinY; } }   private void Scale(int v1, int v2, int v3) { foreach (var item in nodes) { item[0] *= v1; item[1] *= v2; item[2] *= v3; } }   protected override void OnPaint(PaintEventArgs args) { var g = args.Graphics; g.SmoothingMode = SmoothingMode.HighQuality; g.Clear(Color.White);   g.TranslateTransform(Width / 2, Height / 2);   foreach (var edge in edges) { double[] xy1 = nodes[edge[0]]; double[] xy2 = nodes[edge[1]]; g.DrawLine(Pens.Black, (int)Math.Round(xy1[0]), (int)Math.Round(xy1[1]), (int)Math.Round(xy2[0]), (int)Math.Round(xy2[1])); }   foreach (var node in nodes) { g.FillEllipse(Brushes.Black, (int)Math.Round(node[0]) - 4, (int)Math.Round(node[1]) - 4, 8, 8); } } } }
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.
#Prolog
Prolog
test :- read(Name), atomics_to_string([Name, "= 50, writeln('", Name, "' = " , Name, ")"], String), term_string(Term, String), Term.
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.
#Python
Python
>>> name = raw_input("Enter a variable name: ") Enter a variable name: X >>> globals()[name] = 42 >>> X 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
#OCaml
OCaml
module G = Graphics   let () = G.open_graph ""; G.resize_window 320 240; G.set_color G.red; G.plot 100 100; ignore (G.read_key ())
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
#Ol
Ol
  (import (lib gl)) (import (OpenGL version-1-0))   ; init (glClearColor 0.3 0.3 0.3 1) (glOrtho 0 320 0 240 0 1)   ; draw loop (gl:set-renderer (lambda (mouse) (glClear GL_COLOR_BUFFER_BIT) (glBegin GL_POINTS) (glColor3f 255 0 0) (glVertex2f 100 100) (glEnd)))  
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
#REXX
REXX
/*REXX program performs division on positive integers using the Egyptian division method*/ numeric digits 1000 /*support gihugic numbers & be gung-ho.*/ parse arg n d . /*obtain optional arguments from the CL*/ if d=='' | d=="," then do; n= 580; d= 34 /*Not specified? Then use the defaults*/ end call EgyptDiv n, d /*invoke the Egyptian Division function*/ parse var result q r /*extract the quotient & the remainder.*/ say n ' divided by ' d " is " q ' with a remainder of ' r exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ EgyptDiv: procedure; parse arg num,dem /*obtain the numerator and denominator.*/ p= 1; t= dem /*initialize the double & power values.*/ do #=1 until t>num /*construct the power & doubling lists.*/ pow.#= p; p= p + p /*build power entry; bump power value.*/ dbl.#= t; t= t + t /* " doubling "  ; " doubling val.*/ end /*#*/ acc=0; ans=0 /*initialize accumulator & answer to 0 */ do s=# by -1 for # /* [↓] process the table "backwards". */ sum= acc + dbl.s /*compute the sum (to be used for test)*/ if sum>num then iterate /*Is sum to big? Then ignore this step*/ acc= sum /*use the "new" sum for the accumulator*/ ans= ans + pow.s /*calculate the (newer) running answer.*/ end /*s*/ return ans num-acc /*return the answer and the remainder. */
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#Ring
Ring
  load "stdlib.ring"   table = newlist(32, 2) dividend = 580 divisor = 34   i = 1 table[i][1] = 1 table[i][2] = divisor   while table[i] [2] < dividend i = i + 1 table[i][1] = table[i -1] [1] * 2 table[i][2] = table[i -1] [2] * 2 end i = i - 1 answer = table[i][1] accumulator = table[i][2]   while i > 1 i = i - 1 if table[i][2]+ accumulator <= dividend answer = answer + table[i][1] accumulator = accumulator + table[i][2] ok end   see string(dividend) + " divided by " + string(divisor) + " using egytian division" + nl see " returns " + string(answer) + " mod(ulus) " + string(dividend-accumulator)  
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
#REXX
REXX
/*REXX program converts a fraction (can be improper) to an Egyptian fraction. */ parse arg fract '' -1 t; z=$egyptF(fract) /*compute the Egyptian fraction. */ if t\==. then say fract ' ───► ' z /*show Egyptian fraction from C.L.*/ return z /*stick a fork in it, we're done.*/ /*────────────────────────────────$EGYPTF subroutine──────────────────────────*/ $egyptF: parse arg z 1 zn '/' zd,,$; if zd=='' then zd=1 /*whole number ?*/ if z='' then call erx "no fraction was specified." if zd==0 then call erx "denominator can't be zero:" zd if zn==0 then call erx "numerator can't be zero:" zn if zd<0 | zn<0 then call erx "fraction can't be negative" z if \datatype(zn,'W') then call erx "numerator must be an integer:" zn if \datatype(zd,'W') then call erx "denominator must be an integer:" zd _=zn%zd /*check if it's an improper fraction. */ if _>=1 then do /*if improper fraction, then append it.*/ $='['_"]" /*append the whole # part of fraction. */ zn=zn-_*zd /*now, just use the proper fraction. */ if zn==0 then return $ /*Is there no fraction? Then we're done*/ end if zd//zn==0 then do; zd=zd%zn; zn=1; end do forever if zn==1 & datatype(zd,'W') then return $ "1/"zd /*append Egyptian fract.*/ nd=zd%zn+1; $=$ '1/'nd /*add unity to integer fraction, append*/ z=$fractSub(zn'/'zd, "-", 1'/'nd) /*go and subtract the two fractions. */ parse var z zn '/' zd /*extract the numerator and denominator*/ L=2*max(length(zn),length(zd)) /*calculate if need more decimal digits*/ if L>=digits() then numeric digits L+L /*yes, then bump the decimal digits*/ end /*forever*/ /* [↑] the DO forever ends when zn==1.*/ /*────────────────────────────────$FRACTSUB subroutine────────────────────────*/ $fractSub: procedure; parse arg z.1,,z.2 1 zz.2; arg ,op do j=1 for 2; z.j=translate(z.j,'/',"_"); end if z.1=='' then z.1=(op\=="+" & op\=='-') /*unary +,- first fraction.*/ if z.2=='' then z.2=(op\=="+" & op\=='-') /*unary +.- second fraction.*/ do j=1 for 2 /*process both of the fractions*/ if pos('/',z.j)==0 then z.j=z.j"/1"; parse var z.j n.j '/' d.j if \datatype(n.j,'N') then call erx "numerator isn't an integer:" n.j if \datatype(d.j,'N') then call erx "denominator isn't an integer:" d.j n.j=n.j/1; d.j=d.j/1 /*normalize numerator/denominator.*/   do while \datatype(n.j,'W'); n.j=n.j*10/1; d.j=d.j*10/1; end /*while*/ /* [↑] normalize both numbers. */ if d.j=0 then call erx "denominator can't be zero:" z.j g=gcd(n.j,d.j); if g=0 then iterate; n.j=n.j/g; d.j=d.j/g end /*j*/ l=lcm(d.1 d.2); do j=1 for 2; n.j=l*n.j/d.j; d.j=l; end /*j*/ if op=='-' then n.2=-n.2 t=n.1+n.2; u=l; if t==0 then return 0 g=gcd(t,u); t=t/g; u=u/g; if u==1 then return t return t'/'u /*─────────────────────────────general 1─line subs────────────────────────────*/ erx: say; say '***error!***' arg(1); say; exit 13 gcd:procedure;$=;do i=1 for arg();$=$ arg(i);end;parse var $ x z .;if x=0 then x=z;x=abs(x);do j=2 to words($);y=abs(word($,j));if y=0 then iterate;do until _==0;_=x//y;x=y;y=_;end;end;return x lcm:procedure;y=;do j=1 for arg();y=y arg(j);end;x=word(y,1);do k=2 to words(y);!=abs(word(y,k));if !=0 then return 0;x=x*!/gcd(x,!);end;return x p: return word(arg(1),1)
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
#Ursala
Ursala
odd = ~&ihB double = ~&iNiCB half = ~&itB
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#zkl
zkl
fcn rule(n){ n=n.toString(2); "00000000"[n.len() - 8,*] + n } fcn applyRule(rule,cells){ cells=String(cells[-1],cells,cells[0]); // wrap cell ends (cells.len() - 2).pump(String,'wrap(n){ rule[7 - cells[n,3].toInt(2)] }) }
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
#Wren
Wren
import "/fmt" for Fmt import "/big" for BigInt   class Factorial { static iterative(n) { if (n < 2) return BigInt.one var fact = BigInt.one for (i in 2..n.toSmall) fact = fact * i return fact }   static recursive(n) { if (n < 2) return BigInt.one return n * recursive(n-1) } }   var n = BigInt.new(24) Fmt.print("Factorial(%(n)) iterative -> $,s", Factorial.iterative(n)) Fmt.print("Factorial(%(n)) recursive -> $,s", Factorial.recursive(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.
#REBOL
REBOL
server-port: open/lines tcp://:12321 forever [ connection-port: first server-port until [ wait connection-port error? try [insert connection-port first connection-port] ] close connection-port ] close server-port
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#Scala
Scala
object EbanNumbers {   class ERange(s: Int, e: Int, p: Boolean) { val start: Int = s val end: Int = e val print: Boolean = p }   def main(args: Array[String]): Unit = { val rgs = List( new ERange(2, 1000, true), new ERange(1000, 4000, true), new ERange(2, 10000, false), new ERange(2, 100000, false), new ERange(2, 1000000, false), new ERange(2, 10000000, false), new ERange(2, 100000000, false), new ERange(2, 1000000000, false) ) for (rg <- rgs) { if (rg.start == 2) { println(s"eban numbers up to an including ${rg.end}") } else { println(s"eban numbers between ${rg.start} and ${rg.end}") }   var count = 0 for (i <- rg.start to rg.end) { val b = i / 1000000000 var r = i % 1000000000 var m = r / 1000000 r = i % 1000000 var t = r / 1000 r %= 1000 if (m >= 30 && m <= 66) { m %= 10 } if (t >= 30 && t <= 66) { t %= 10 } if (r >= 30 && r <= 66) { r %= 10 } if (b == 0 || b == 2 || b == 4 || b == 6) { if (m == 0 || m == 2 || m == 4 || m == 6) { if (t == 0 || t == 2 || t == 4 || t == 6) { if (r == 0 || r == 2 || r == 4 || r == 6) { if (rg.print) { print(s"$i ") } count += 1 } } } } } if (rg.print) { println() } println(s"count = $count") println() } } }
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
#Kotlin
Kotlin
// version 1.1   import java.awt.* import javax.swing.*   class RotatingCube : JPanel() { private val nodes = arrayOf( doubleArrayOf(-1.0, -1.0, -1.0), doubleArrayOf(-1.0, -1.0, 1.0), doubleArrayOf(-1.0, 1.0, -1.0), doubleArrayOf(-1.0, 1.0, 1.0), doubleArrayOf( 1.0, -1.0, -1.0), doubleArrayOf( 1.0, -1.0, 1.0), doubleArrayOf( 1.0, 1.0, -1.0), doubleArrayOf( 1.0, 1.0, 1.0) ) private val edges = arrayOf( intArrayOf(0, 1), intArrayOf(1, 3), intArrayOf(3, 2), intArrayOf(2, 0), intArrayOf(4, 5), intArrayOf(5, 7), intArrayOf(7, 6), intArrayOf(6, 4), intArrayOf(0, 4), intArrayOf(1, 5), intArrayOf(2, 6), intArrayOf(3, 7) )   init { preferredSize = Dimension(640, 640) background = Color.white scale(100.0) rotateCube(Math.PI / 4.0, Math.atan(Math.sqrt(2.0))) Timer(17) { rotateCube(Math.PI / 180.0, 0.0) repaint() }.start() }   private fun scale(s: Double) { for (node in nodes) { node[0] *= s node[1] *= s node[2] *= s } }   private fun rotateCube(angleX: Double, angleY: Double) { val sinX = Math.sin(angleX) val cosX = Math.cos(angleX) val sinY = Math.sin(angleY) val cosY = Math.cos(angleY) for (node in nodes) { val x = node[0] val y = node[1] var z = node[2] node[0] = x * cosX - z * sinX node[2] = z * cosX + x * sinX z = node[2] node[1] = y * cosY - z * sinY node[2] = z * cosY + y * sinY } }   private fun drawCube(g: Graphics2D) { g.translate(width / 2, height / 2) for (edge in edges) { val xy1 = nodes[edge[0]] val xy2 = nodes[edge[1]] g.drawLine(Math.round(xy1[0]).toInt(), Math.round(xy1[1]).toInt(), Math.round(xy2[0]).toInt(), Math.round(xy2[1]).toInt()) } for (node in nodes) { g.fillOval(Math.round(node[0]).toInt() - 4, Math.round(node[1]).toInt() - 4, 8, 8) } }   override public fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.color = Color.blue drawCube(g) } }   fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE f.title = "Rotating cube" f.isResizable = false f.add(RotatingCube(), BorderLayout.CENTER) f.pack() f.setLocationRelativeTo(null) f.isVisible = 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.
#Python
Python
>>> import random >>> from operator import add, sub, mul, floordiv >>> from pprint import pprint as pp >>> >>> def ewise(matrix1, matrix2, op): return [[op(e1,e2) for e1,e2 in zip(row1, row2)] for row1,row2 in zip(matrix1, matrix2)]   >>> m,n = 3,4 # array dimensions >>> a0 = [[random.randint(1,9) for y in range(n)] for x in range(m)] >>> a1 = [[random.randint(1,9) for y in range(n)] for x in range(m)] >>> pp(a0); pp(a1) [[7, 8, 7, 4], [4, 9, 4, 1], [2, 3, 6, 4]] [[4, 5, 1, 6], [6, 8, 3, 4], [2, 2, 6, 3]] >>> pp(ewise(a0, a1, add)) [[11, 13, 8, 10], [10, 17, 7, 5], [4, 5, 12, 7]] >>> pp(ewise(a0, a1, sub)) [[3, 3, 6, -2], [-2, 1, 1, -3], [0, 1, 0, 1]] >>> pp(ewise(a0, a1, mul)) [[28, 40, 7, 24], [24, 72, 12, 4], [4, 6, 36, 12]] >>> pp(ewise(a0, a1, floordiv)) [[1, 1, 7, 0], [0, 1, 1, 0], [1, 1, 1, 1]] >>> pp(ewise(a0, a1, pow)) [[2401, 32768, 7, 4096], [4096, 43046721, 64, 1], [4, 9, 46656, 64]] >>> pp(ewise(a0, a1, lambda x, y:2*x - y)) [[10, 11, 13, 2], [2, 10, 5, -2], [2, 4, 6, 5]] >>> >>> def s_ewise(scalar1, matrix1, op): return [[op(scalar1, e1) for e1 in row1] for row1 in matrix1]   >>> scalar = 10 >>> a0 [[7, 8, 7, 4], [4, 9, 4, 1], [2, 3, 6, 4]] >>> for op in ( add, sub, mul, floordiv, pow, lambda x, y:2*x - y ): print("%10s :" % op.__name__, s_ewise(scalar, a0, op))     add : [[17, 18, 17, 14], [14, 19, 14, 11], [12, 13, 16, 14]] sub : [[3, 2, 3, 6], [6, 1, 6, 9], [8, 7, 4, 6]] mul : [[70, 80, 70, 40], [40, 90, 40, 10], [20, 30, 60, 40]] floordiv : [[1, 1, 1, 2], [2, 1, 2, 10], [5, 3, 1, 2]] pow : [[10000000, 100000000, 10000000, 10000], [10000, 1000000000, 10000, 10], [100, 1000, 1000000, 10000]] <lambda> : [[13, 12, 13, 16], [16, 11, 16, 19], [18, 17, 14, 16]] >>>
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
#Befunge
Befunge
45*65*65*"2"30p20p10p::00p2*40p4*5vv< >60p140g->:::*00g50g*60g40g-:*-\-v0>1 ^_@#`\g0<|`\g04:+1, <*84$$_v#`\0:<>p^ >v>g2+:5^$>g:*++*/7g^>*:9$#<"~"/:"~"v g:^06,+55<^03*<v09p07%"~"p09/"~"p08%< ^>#0 *#12#<0g:^>+::"~~"90g*80g+*70gv| g-10g*+:9**00gv|!*`\2\`-20::/2-\/\+<> %#&eo*!:..^g05<>$030g-*9/\20g*+60g40^
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
#Icon_and_Unicon
Icon and Unicon
  class DoubleLink (value, prev_link, next_link)   # insert given node after this one, losing its existing connections method insert_after (node) node.prev_link := self if (\next_link) then next_link.prev_link := node node.next_link := next_link self.next_link := node end   initially (value, prev_link, next_link) self.value := value self.prev_link := prev_link # links are 'null' if not given self.next_link := next_link end  
http://rosettacode.org/wiki/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
#J
J
(pred;succ;<data) conew 'DoublyLinkedListElement'
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
#Java
Java
  import java.util.LinkedList;   @SuppressWarnings("serial") public class DoublyLinkedListInsertion<T> extends LinkedList<T> {   public static void main(String[] args) { DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>(); list.addFirst("Add First 1"); list.addFirst("Add First 2"); list.addFirst("Add First 3"); list.addFirst("Add First 4"); list.addFirst("Add First 5"); traverseList(list);   list.addAfter("Add First 3", "Add New"); traverseList(list); }   /* * Add after indicated node. If not in the list, added as the last node. */ public void addAfter(T after, T element) { int index = indexOf(after); if ( index >= 0 ) { add(index + 1, element); } else { addLast(element); } }   private static void traverseList(LinkedList<String> list) { System.out.println("Traverse List:"); for ( int i = 0 ; i < list.size() ; i++ ) { System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i)); } System.out.println(); }   }  
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
#ActionScript
ActionScript
  package {   import flash.display.Graphics; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer;   public class Clock extends Sprite {   // Changes of hands (in degrees) per second private static const HOUR_HAND_CHANGE:Number = 1 / 120; // 360 / (60 * 60 * 12) private static const MINUTE_HAND_CHANGE:Number = 0.1; // 360 / (60 * 60) private static const SECOND_HAND_CHANGE:Number = 6; // 360 / 60   private var _timer:Timer;   private var _hHand:Shape; private var _mHand:Shape; private var _sHand:Shape;   public function Clock() { if ( stage ) _init(); else addEventListener(Event.ADDED_TO_STAGE, _init); }   private function _init(e:Event = null):void {   var i:uint;   var base:Shape = new Shape(), hHand:Shape = new Shape(), mHand:Shape = new Shape(); var sHand:Shape = new Shape(), hub:Shape = new Shape();   var size:Number = 500; var c:Number = size / 2; x = 30; y = 30;   var baseGraphics:Graphics = base.graphics;   baseGraphics.lineStyle(5, 0xEE0000); baseGraphics.beginFill(0xFFDDDD); baseGraphics.drawCircle(c, c, c);   var uAngle:Number = Math.PI / 30;   var markerStart:Number = c - 30; var markerEnd:Number = c - 15;   var markerX1:Number, markerY1:Number, markerX2:Number, markerY2:Number; var angle:Number, angleSin:Number, angleCos:Number;   baseGraphics.endFill();   var isMajorMarker:Boolean = true;   for ( i = 0; i < 60; i++ ) { // Draw the markers   angle = uAngle * i; angleSin = Math.sin(angle); angleCos = Math.cos(angle);   markerX1 = c + markerStart * angleCos; markerY1 = c + markerStart * angleSin; markerX2 = c + markerEnd * angleCos; markerY2 = c + markerEnd * angleSin;   if ( i % 5 == 0 ) { baseGraphics.lineStyle(3, 0x000080); isMajorMarker = true; } else if ( isMajorMarker ) { baseGraphics.lineStyle(1, 0x000080); isMajorMarker = false; }   baseGraphics.moveTo(markerX1, markerY1); baseGraphics.lineTo(markerX2, markerY2); }   addChild(base);   sHand.graphics.lineStyle(2, 0x00BB00); sHand.graphics.moveTo(0, 0); sHand.graphics.lineTo(0, 40 - c); sHand.x = sHand.y = c;   mHand.graphics.lineStyle(8, 0x444444); mHand.graphics.moveTo(0, 0); mHand.graphics.lineTo(0, 50 - c); mHand.x = mHand.y = c;   hHand.graphics.lineStyle(8, 0x777777); hHand.graphics.moveTo(0, 0); hHand.graphics.lineTo(0, 120 - c); hHand.x = hHand.y = c;   hub.graphics.lineStyle(4, 0x664444); hub.graphics.beginFill(0xCC9999); hub.graphics.drawCircle(c, c, 5);   _hHand = hHand; _mHand = mHand; _sHand = sHand;   addChild(mHand); addChild(hHand); addChild(sHand); addChild(hub);   var date:Date = new Date();   // Since millisecond precision is not needed, round it up to the nearest second. var seconds:Number = date.seconds + ((date.milliseconds > 500) ? 1 : 0); var minutes:Number = date.minutes + seconds / 60; var hours:Number = (date.hours + minutes / 60) % 12;   sHand.rotation = seconds * 6; mHand.rotation = minutes * 6; hHand.rotation = hours * 30;   _timer = new Timer(1000); // 1 second = 1000 ms _timer.addEventListener(TimerEvent.TIMER, _onTimerTick); _timer.start();   }   private function _onTimerTick(e:TimerEvent):void { _hHand.rotation += HOUR_HAND_CHANGE; _mHand.rotation += MINUTE_HAND_CHANGE; _sHand.rotation += SECOND_HAND_CHANGE; }   }   }  
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
#Fortran
Fortran
Dim As Integer i, MiLista()   For i = 0 To Int(Rnd * 100)+25 Redim Preserve MiLista(i) MiLista(i) = Rnd * 314 Next   'Tour from the beginning For i = Lbound(MiLista) To Ubound(MiLista) Print MiLista(i) Next i   Print 'Travel from the end For i = Ubound(MiLista) To Lbound(MiLista) Step -1 Print MiLista(i) Next i Sleep
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
#FreeBASIC
FreeBASIC
Dim As Integer i, MiLista()   For i = 0 To Int(Rnd * 100)+25 Redim Preserve MiLista(i) MiLista(i) = Rnd * 314 Next   'Tour from the beginning For i = Lbound(MiLista) To Ubound(MiLista) Print MiLista(i) Next i   Print 'Travel from the end For i = Ubound(MiLista) To Lbound(MiLista) Step -1 Print MiLista(i) Next i Sleep
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
#Delphi
Delphi
struct Node(T) {   type   pList = ^List ;   list = record data : pointer ; prev : pList ; next : pList ; 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
#E
E
def makeElement(var value, var next, var prev) { def element { to setValue(v) { value := v } to getValue() { return value }   to setNext(n) { next := n } to getNext() { return next }   to setPrev(p) { prev := p } to getPrev() { return prev } }   return element }
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
#Erlang
Erlang
  new( Data ) -> erlang:spawn( fun() -> loop( Data, noprevious, nonext ) end ).  
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#Elixir
Elixir
defmodule Dutch_national_flag do defp ball(:red), do: 1 defp ball(:white), do: 2 defp ball(:blue), do: 3   defp random_ball, do: Enum.random([:red, :white, :blue])   defp random_ball(n), do: (for _ <- 1..n, do: random_ball())   defp is_dutch([]), do: true defp is_dutch([_]), do: true defp is_dutch([b,h|l]), do: ball(b) < ball(h) and is_dutch([h|l]) defp is_dutch(_), do: false   def dutch(list), do: dutch([], [], [], list)   defp dutch(r, w, b, []), do: r ++ w ++ b defp dutch(r, w, b, [:red | list]), do: dutch([:red | r], w, b, list) defp dutch(r, w, b, [:white | list]), do: dutch(r, [:white | w], b, list) defp dutch(r, w, b, [:blue | list]), do: dutch(r, w, [:blue | b], list)   def problem(n \\ 10) do list = random_ball(n) if is_dutch(list) do IO.puts "The random sequence #{inspect list} is already in the order of the Dutch flag!" else IO.puts "The starting random sequence is #{inspect list};" IO.puts "The ordered sequence is #{inspect dutch(list)}." end end end   Dutch_national_flag.problem
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)
#Erlang
Erlang
-module(dutch). -export([random_balls/1, is_dutch/1, dutch/1]).   ball(red) -> 1; ball(white) -> 2; ball(blue) -> 3.   random_ball() -> lists:nth(random:uniform(3), [red, white, blue]).   random_balls(N) -> random_balls(N,[]). random_balls(0,L) -> L; random_balls(N,L) when N > 0 -> B = random_ball(), random_balls(N-1, [B|L]).   is_dutch([]) -> true; is_dutch([_]) -> true; is_dutch([B|[H|L]]) -> (ball(B) < ball(H)) and is_dutch([H|L]); is_dutch(_) -> false.   dutch(L) -> dutch([],[],[],L).   dutch(R, W, B, []) -> R ++ W ++ B; dutch(R, W, B, [red | L]) -> dutch([red|R], W, B, L); dutch(R, W, B, [white | L]) -> dutch(R, [white|W], B, L); dutch(R, W, B, [blue | L]) -> dutch(R, W, [blue|B], L).
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
#C.2B.2B
C++
  #include<graphics.h> #include<iostream>   int main() { int k; initwindow(1500,810,"Rosetta Cuboid");   do{ std::cout<<"Enter ratio of sides ( 0 or -ve to exit) : "; std::cin>>k;   if(k>0){ bar3d(100, 100, 100 + 2*k, 100 + 4*k, 3*k, 1); } }while(k>0);   return 0; }    
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.
#Quackery
Quackery
[ say "The word " dup echo$ names find names found iff [ say " exists." ] else [ say " does not exist." ] ] is exists? ( $ --> )     [ $ "Please enter a name: " input cr dup exists? cr cr dup say "Creating " echo$ say "..." $ "[ stack ] is " over join quackery cr cr exists? cr ] is task ( --> )
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.
#R
R
# Read the name in from a command prompt varname <- readline("Please name your variable >") # Make sure the name is valid for a variable varname <- make.names(varname) message(paste("The variable being assigned is '", varname, "'")) # Assign the variable (with value 42) into the user workspace (global environment) assign(varname, 42) #Check that the value has been assigned ok ls(pattern=varname) get(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.
#Racket
Racket
  -> (begin (printf "Enter some name: ") (namespace-set-variable-value! (read) 123)) Enter some name: bleh -> bleh 123  
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
#Perl
Perl
use Gtk3 '-init';   my $window = Gtk3::Window->new(); $window->set_default_size(320, 240); $window->set_border_width(10); $window->set_title("Draw a Pixel"); $window->set_app_paintable(TRUE);   my $da = Gtk3::DrawingArea->new(); $da->signal_connect('draw' => \&draw_in_drawingarea); $window->add($da); $window->show_all();   Gtk3->main;   sub draw_in_drawingarea { my ($widget, $cr, $data) = @_; $cr->set_source_rgb(1, 0, 0); $cr->set_line_width(1); $cr->rectangle( 100, 100, 1, 1); $cr->stroke; }
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
#Phix
Phix
with javascript_semantics include pGUI.e cdCanvas cdcanvas function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) cdCanvasActivate(cdcanvas) cdCanvasPixel(cdcanvas, 100, 100, CD_RED) cdCanvasFlush(cdcanvas) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) return IUP_DEFAULT end function procedure main() IupOpen() Ihandle canvas = IupCanvas(NULL) IupSetAttribute(canvas, "RASTERSIZE", "320x240") IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) Ihandle dlg = IupDialog(canvas) IupSetAttribute(dlg, "TITLE", "Draw a pixel") IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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
#Ruby
Ruby
def egyptian_divmod(dividend, divisor) table = [[1, divisor]] table << table.last.map{|e| e*2} while table.last.first * 2 <= dividend answer, accumulator = 0, 0 table.reverse_each do |pow, double| if accumulator + double <= dividend accumulator += double answer += pow end end [answer, dividend - accumulator] end   puts "Quotient = %s Remainder = %s" % egyptian_divmod(580, 34)  
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
#Rust
Rust
fn egyptian_divide(dividend: u32, divisor: u32) -> (u32, u32) { let dividend = dividend as u64; let divisor = divisor as u64;   let pows = (0..32).map(|p| 1 << p); let doublings = (0..32).map(|p| divisor << p);   let (answer, sum) = doublings .zip(pows) .rev() .skip_while(|(i, _)| i > &dividend ) .fold((0, 0), |(answer, sum), (double, power)| { if sum + double < dividend { (answer + power, sum + double) } else { (answer, sum) } });   (answer as u32, (dividend - sum) as u32) }   fn main() { let (div, rem) = egyptian_divide(580, 34); println!("580 divided by 34 is {} remainder {}", div, rem); }
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
#Ruby
Ruby
def ef(fr) ans = [] if fr >= 1 return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1 intfr = fr.to_i ans, fr = [intfr], fr - intfr end x, y = fr.numerator, fr.denominator while x != 1 ans << Rational(1, (1/fr).ceil) fr = Rational(-y % x, y * (1/fr).ceil) x, y = fr.numerator, fr.denominator end ans << fr end   for fr in [Rational(43, 48), Rational(5, 121), Rational(2014, 59)] puts '%s => %s' % [fr, ef(fr).join(' + ')] end   lenmax = denommax = [0] for b in 2..99 for a in 1...b fr = Rational(a,b) e = ef(fr) elen, edenom = e.length, e[-1].denominator lenmax = [elen, fr] if elen > lenmax[0] denommax = [edenom, fr] if edenom > denommax[0] end end puts 'Term max is %s with %i terms' % [lenmax[1], lenmax[0]] dstr = denommax[0].to_s puts 'Denominator max is %s with %i digits' % [denommax[1], dstr.size], dstr
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
#VBA
VBA
Private Function lngHalve(Nb As Long) As Long lngHalve = Nb / 2 End Function   Private Function lngDouble(Nb As Long) As Long lngDouble = Nb * 2 End Function   Private Function IsEven(Nb As Long) As Boolean IsEven = (Nb Mod 2 = 0) End Function
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
#x86_Assembly
x86 Assembly
global factorial section .text   ; Input in ECX register (greater than 0!) ; Output in EAX register factorial: mov eax, 1 .factor: mul ecx loop .factor ret
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.
#Ruby
Ruby
require 'socket' server = TCPServer.new(12321)   while (connection = server.accept) Thread.new(connection) do |conn| port, host = conn.peeraddr[1,2] client = "#{host}:#{port}" puts "#{client} is connected" begin loop do line = conn.readline puts "#{client} says: #{line}" conn.puts(line) end rescue EOFError conn.close puts "#{client} has disconnected" end end end
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#Tailspin
Tailspin
  templates isEban def number: $; '$;' -> \(<'([246]|[3456][0246])(0[03456][0246])*'> $ !\) -> $number ! end isEban  
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Structure Interval Dim start As Integer Dim last As Integer Dim print As Boolean   Sub New(s As Integer, l As Integer, p As Boolean) start = s last = l print = p End Sub End Structure   Sub Main() Dim intervals As Interval() = { New Interval(2, 1_000, True), New Interval(1_000, 4_000, True), New Interval(2, 10_000, False), New Interval(2, 100_000, False), New Interval(2, 1_000_000, False), New Interval(2, 10_000_000, False), New Interval(2, 100_000_000, False), New Interval(2, 1_000_000_000, False) } For Each intv In intervals If intv.start = 2 Then Console.WriteLine("eban numbers up to and including {0}:", intv.last) Else Console.WriteLine("eban numbers between {0} and {1} (inclusive):", intv.start, intv.last) End If   Dim count = 0 For i = intv.start To intv.last Step 2 Dim b = i \ 1_000_000_000 Dim r = i Mod 1_000_000_000 Dim m = r \ 1_000_000 r = i Mod 1_000_000 Dim t = r \ 1_000 r = r Mod 1_000 If m >= 30 AndAlso m <= 66 Then m = m Mod 10 End If If t >= 30 AndAlso t <= 66 Then t = t Mod 10 End If If r >= 30 AndAlso r <= 66 Then r = r Mod 10 End If If b = 0 OrElse b = 2 OrElse b = 4 OrElse b = 6 Then If m = 0 OrElse m = 2 OrElse m = 4 OrElse m = 6 Then If t = 0 OrElse t = 2 OrElse t = 4 OrElse t = 6 Then If r = 0 OrElse r = 2 OrElse r = 4 OrElse r = 6 Then If intv.print Then Console.Write("{0} ", i) End If count += 1 End If End If End If End If Next If intv.print Then Console.WriteLine() End If Console.WriteLine("count = {0}", count) Console.WriteLine() Next End Sub   End Module
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
#Lua
Lua
local abs,atan,cos,floor,pi,sin,sqrt = math.abs,math.atan,math.cos,math.floor,math.pi,math.sin,math.sqrt local bitmap = { init = function(self, w, h, value) self.w, self.h, self.pixels = w, h, {} for y=1,h do self.pixels[y]={} end self:clear(value) end, clear = function(self, value) for y=1,self.h do for x=1,self.w do self.pixels[y][x] = value or " " end end end, set = function(self, x, y, value) x,y = floor(x),floor(y) if x>0 and y>0 and x<=self.w and y<=self.h then self.pixels[y][x] = value or "#" end end, line = function(self, x1, y1, x2, y2, c) x1,y1,x2,y2 = floor(x1),floor(y1),floor(x2),floor(y2) local dx, sx = abs(x2-x1), x1<x2 and 1 or -1 local dy, sy = abs(y2-y1), y1<y2 and 1 or -1 local err = floor((dx>dy and dx or -dy)/2) while(true) do self:set(x1, y1, c) if (x1==x2 and y1==y2) then break end if (err > -dx) then err, x1 = err-dy, x1+sx if (x1==x2 and y1==y2) then self:set(x1, y1, c) break end end if (err < dy) then err, y1 = err+dx, y1+sy end end end, render = function(self) for y=1,self.h do print(table.concat(self.pixels[y])) end end, } screen = { clear = function() os.execute("cls") -- or? os.execute("clear"), or? io.write("\027[2J\027[H"), or etc? end, } local camera = { fl = 2.5 } local L = 0.5 local cube = { verts = { {L,L,L}, {L,-L,L}, {-L,-L,L}, {-L,L,L}, {L,L,-L}, {L,-L,-L}, {-L,-L,-L}, {-L,L,-L} }, edges = { {1,2}, {2,3}, {3,4}, {4,1}, {5,6}, {6,7}, {7,8}, {8,5}, {1,5}, {2,6}, {3,7}, {4,8} }, rotate = function(self, rx, ry) local cx,sx = cos(rx),sin(rx) local cy,sy = cos(ry),sin(ry) for i,v in ipairs(self.verts) do local x,y,z = v[1],v[2],v[3] v[1], v[2], v[3] = x*cx-z*sx, y*cy-x*sx*sy-z*cx*sy, x*sx*cy+y*sy+z*cx*cy end end, } local renderer = { render = function(self, shape, camera, bitmap) local fl = camera.fl local ox, oy = bitmap.w/2, bitmap.h/2 local mx, my = bitmap.w/2, bitmap.h/2 local rpverts = {} for i,v in ipairs(shape.verts) do local x,y,z = v[1],v[2],v[3] local px = ox + mx * (fl*x)/(fl-z) local py = oy + my * (fl*y)/(fl-z) rpverts[i] = { px,py } end for i,e in ipairs(shape.edges) do local v1, v2 = rpverts[e[1]], rpverts[e[2]] bitmap:line( v1[1], v1[2], v2[1], v2[2], "██" ) end end } -- bitmap:init(40,40) cube:rotate(pi/4, atan(sqrt(2))) for i=1,60 do cube:rotate(pi/60,0) bitmap:clear("··") renderer:render(cube, camera, bitmap) screen:clear() bitmap:render() 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.
#R
R
# create a 2-times-2 matrix mat <- matrix(1:4, 2, 2)   # matrix with scalar mat + 2 mat * 2 mat ^ 2   # matrix with matrix mat + mat mat * mat mat ^ mat
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
#Brlcad
Brlcad
opendb balls.g y # Create a database to hold our shapes units cm # Set the unit of measure in ball.s sph 0 0 0 3 # Create a sphere of radius 3 cm named ball.s with its centre at 0,0,0
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#JavaScript
JavaScript
DoublyLinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) { if (this._value == searchValue) { var after = this.next(); this.next(nodeToInsert); nodeToInsert.prev(this); nodeToInsert.next(after); after.prev(nodeToInsert); } else if (this.next() == null) throw new Error(0, "value '" + searchValue + "' not found in linked list.") else this.next().insertAfter(searchValue, nodeToInsert); }   var list = createDoublyLinkedListFromArray(['A','B']); list.insertAfter('A', new DoublyLinkedList('C', null, null));
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
#Julia
Julia
mutable struct DLNode{T} value::T pred::Union{DLNode{T}, Nothing} succ::Union{DLNode{T}, Nothing} DLNode(v) = new{typeof(v)}(v, nothing, nothing) end   function insertpost(prevnode, node) succ = prevnode.succ prevnode.succ = node node.pred = prevnode node.succ = succ if succ != nothing succ.pred = node end node end   function printfromroot(root) print(root.value) while root.succ != nothing root = root.succ print(" -> $(root.value)") end println() end   node1 = DLNode(1) printfromroot(node1) node2 = DLNode(2) node3 = DLNode(3) insertpost(node1, node2) printfromroot(node1) insertpost(node1, node3) printfromroot(node1)  
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
#Ada
Ada
with Ada.Numerics.Elementary_Functions; with Ada.Calendar.Formatting; with Ada.Calendar.Time_Zones;   with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Events.Events;   procedure Draw_A_Clock is use Ada.Calendar; use Ada.Calendar.Formatting; Window  : SDL.Video.Windows.Window; Renderer : SDL.Video.Renderers.Renderer; Event  : SDL.Events.Events.Events; Offset  : Time_Zones.Time_Offset;   procedure Draw_Clock (Stamp : Time) is use SDL.C; use Ada.Numerics.Elementary_Functions; Radi : constant array (0 .. 59) of int := (0 | 15 | 30 | 45 => 2, 5 | 10 | 20 | 25 | 35 | 40 | 50 | 55 => 1, others => 0); Diam : constant array (0 .. 59) of int := (0 | 15 | 30 | 45 => 5, 5 | 10 | 20 | 25 | 35 | 40 | 50 | 55 => 3, others => 1); Width  : constant int  := Window.Get_Surface.Size.Width; Height : constant int  := Window.Get_Surface.Size.Height; Radius : constant Float := Float (int'Min (Width, Height)); R_1  : constant Float := 0.48 * Radius; R_2  : constant Float := 0.35 * Radius; R_3  : constant Float := 0.45 * Radius; R_4  : constant Float := 0.47 * Radius; Hour  : constant Hour_Number  := Formatting.Hour (Stamp, Offset); Minute : constant Minute_Number := Formatting.Minute (Stamp, Offset); Second : constant Second_Number := Formatting.Second (Stamp);   function To_X (A : Float; R : Float) return int is (Width / 2 + int (R * Sin (A, 60.0)));   function To_Y (A : Float; R : Float) return int is (Height / 2 - int (R * Cos (A, 60.0)));   begin SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); Renderer.Set_Draw_Colour ((0, 0, 150, 255)); Renderer.Fill (Rectangle => (0, 0, Width, Height)); Renderer.Set_Draw_Colour ((200, 200, 200, 255)); for A in 0 .. 59 loop Renderer.Fill (Rectangle => (To_X (Float (A), R_1) - Radi (A), To_Y (Float (A), R_1) - Radi (A), Diam (A), Diam (A))); end loop; Renderer.Set_Draw_Colour ((200, 200, 0, 255)); Renderer.Draw (Line => ((Width / 2, Height / 2), (To_X (5.0 * (Float (Hour) + Float (Minute) / 60.0), R_2), To_Y (5.0 * (Float (Hour) + Float (Minute) / 60.0), R_2)))); Renderer.Draw (Line => ((Width / 2, Height / 2), (To_X (Float (Minute) + Float (Second) / 60.0, R_3), To_Y (Float (Minute) + Float (Second) / 60.0, R_3)))); Renderer.Set_Draw_Colour ((220, 0, 0, 255)); Renderer.Draw (Line => ((Width / 2, Height / 2), (To_X (Float (Second), R_4), To_Y (Float (Second), R_4)))); Renderer.Fill (Rectangle => (Width / 2 - 3, Height / 2 - 3, 7, 7)); end Draw_Clock;   function Poll_Quit return Boolean is use type SDL.Events.Event_Types; begin while SDL.Events.Events.Poll (Event) loop if Event.Common.Event_Type = SDL.Events.Quit then return True; end if; end loop; return False; end Poll_Quit;   begin Offset := Time_Zones.UTC_Time_Offset;   if not SDL.Initialise (Flags => SDL.Enable_Screen) then return; end if;   SDL.Video.Windows.Makers.Create (Win => Window, Title => "Draw a clock", Position => SDL.Natural_Coordinates'(X => 10, Y => 10), Size => SDL.Positive_Sizes'(300, 300), Flags => SDL.Video.Windows.Resizable); loop Draw_Clock (Clock); Window.Update_Surface; delay 0.200; exit when Poll_Quit; end loop;   Window.Finalize; SDL.Finalise; end Draw_A_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
#Go
Go
package main   import "fmt"   type dlNode struct { string next, prev *dlNode }   type dlList struct { head, tail *dlNode }   func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" }   func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node }   func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } }   func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll)   // traverse from end to beginning fmt.Print("From tail:") for p := dll.tail; p != nil; p = p.prev { fmt.Print(" ", p.string) } fmt.Println("") }
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
#F.23
F#
  type 'a DLElm = { mutable prev: 'a DLElm option data: 'a mutable next: 'a DLElm option }  
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
#Factor
Factor
TUPLE: node data 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
#Fortran
Fortran
type node real :: data type(node), pointer :: next => null(), previous => null() end type node ! ! . . . . ! type( node ), target :: head
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
#FreeBASIC
FreeBASIC
type node nxt as node ptr prv as node ptr dat as any ptr 'points to any kind of data; user's responsibility 'to keep track of what's actually in it end type
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)
#F.23
F#
(* Since the task description here does not impose Dijsktra's original restrictions * Changing the order is only allowed by swapping 2 elements * Every element must only be inspected once we have several options ... One way -- especially when we work with immutable data structures -- is to scan the unordered list, collect the different colours on our way and append the 3 sub-lists in the correct order. *) let rnd = System.Random()   type color = | Red | White | Blue   let isDutch s = Seq.forall2 (fun last this -> match (last, this) with | (Red, Red) | (Red, White) | (White, White) | (White, Blue) | (Blue, Blue) -> true | _ -> false ) s (Seq.skip 1 s)   [<EntryPoint>] let main argv = let n = 10 let rec getBallsToSort n s = let sn = Seq.take n s if (isDutch sn) then (getBallsToSort n (Seq.skip 1 s)) else sn let balls = getBallsToSort n (Seq.initInfinite (fun _ -> match (rnd.Next(3)) with | 0 -> Red | 1 -> White | _ -> Blue)) printfn "Sort the sequence of %i balls: %A" n (Seq.toList balls) let (rs,ws,bs) = balls |> Seq.fold (fun (rs,ws,bs) b -> match b with | Red -> (b::rs,ws,bs) | White -> (rs,b::ws,bs) | Blue -> (rs,ws,b::bs)) ([],[],[]) let sorted = rs @ ws @ bs printfn "The sequence %A is sorted: %b" sorted (isDutch sorted) 0
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
#Clojure
Clojure
  (use 'quil.core)   (def w 500) (def h 400)   (defn setup [] (background 0))   (defn draw [] (push-matrix) (translate (/ w 2) (/ h 2) 0) (rotate-x 0.7) (rotate-z 0.5) (box 100 150 200) ; 2x3x4 relative dimensions (pop-matrix))   (defsketch main  :title "cuboid"  :setup setup  :size [w h]  :draw draw  :renderer :opengl)  
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.
#Raku
Raku
our $our-var = 'The our var'; my $my-var = 'The my var';   my $name = prompt 'Variable name: '; my $value = $::('name'); # use the right sigil, etc   put qq/Var ($name) starts with value 「$value」/;   $::('name') = 137;   put qq/Var ($name) ends with value 「{$::('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.
#REBOL
REBOL
rebol [ Title: "Dynamic Variable Name" URL: http://rosettacode.org/wiki/Dynamic_variable_names ]   ; Here, I ask the user for a name, then convert it to a word and ; assign the value "Hello!" to it. To read this phrase, realize that ; REBOL collects terms from right to left, so "Hello!" is stored for ; future use, then the prompt string "Variable name? " is used as the ; argument to ask (prompts user for input). The result of ask is ; converted to a word so it can be an identifier, then the 'set' word ; accepts the new word and the string ("Hello!") to be assigned.   set to-word ask "Variable name? " "Hello!"
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
#Processing
Processing
size(320, 240); set(100, 100, color(255,0,0));
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
#PureBasic
PureBasic
  If OpenWindow(0, 0, 0, 320, 240, "Rosetta Code Draw A Pixel in PureBasic") If CreateImage(0, 320, 240) And StartDrawing(ImageOutput(0)) Plot(100, 100,RGB(255,0,0)) StopDrawing() ImageGadget(0, 0, 0, 320, 240, ImageID(0)) EndIf Repeat Event = WaitWindowEvent() Until Event = #PB_Event_CloseWindow EndIf  
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
#Scala
Scala
object EgyptianDivision extends App {   private def divide(dividend: Int, divisor: Int): Unit = { val powersOf2, doublings = new collection.mutable.ListBuffer[Integer]   //populate the powersof2- and doublings-columns var line = 0 while ((math.pow(2, line) * divisor) <= dividend) { val powerOf2 = math.pow(2, line).toInt powersOf2 += powerOf2 doublings += (powerOf2 * divisor) line += 1 }   var answer, accumulator = 0 //Consider the rows in reverse order of their construction (from back to front of the List) var i = powersOf2.size - 1 for (i <- powersOf2.size - 1 to 0 by -1) if (accumulator + doublings(i) <= dividend) { accumulator += doublings(i) answer += powersOf2(i) }   println(f"$answer%d, remainder ${dividend - accumulator}%d") }   divide(580, 34)   }
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
#Sidef
Sidef
func egyptian_divmod(dividend, divisor) { var table = [[1, divisor]] table << table[-1].map{|e| 2*e } while (2*table[-1][0] <= dividend) var (answer, accumulator) = (0, 0) table.reverse.each { |pair| var (pow, double) = pair... if (accumulator + double <= dividend) { accumulator += double answer += pow } } return (answer, dividend - accumulator) }   say ("Quotient = %s Remainder = %s" % egyptian_divmod(580, 34))
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
#Rust
Rust
  use num_bigint::BigInt; use num_integer::Integer; use num_traits::{One, Zero}; use std::fmt;   #[derive(Debug, Clone, PartialEq, PartialOrd)] struct Rational { nominator: BigInt, denominator: BigInt, }   impl Rational { fn new(n: &BigInt, d: &BigInt) -> Rational { assert!(!d.is_zero(), "denominator cannot be 0"); // simplify if possible let c = n.gcd(d); Rational { nominator: n / &c, denominator: d / &c, } }   fn is_proper(&self) -> bool { self.nominator < self.denominator } fn to_egyptian(&self) -> Vec<Rational> { let mut frac: Vec<Rational> = Vec::new();   let mut current: Rational; if !self.is_proper() { // input is grater than 1 // store the integer part frac.push(Rational::new( &self.nominator.div_floor(&self.denominator), &One::one(), ));   // calculate the remainder current = Rational::new( &self.nominator.mod_floor(&self.denominator), &self.denominator, ); } else { current = self.clone(); }   while !current.nominator.is_one() { let div = current.denominator.div_ceil(&current.nominator);   // store the term frac.push(Rational::new(&One::one(), &div));   current = Rational::new( &(-&current.denominator).mod_floor(&current.nominator), match current.denominator.checked_mul(&div).as_ref() { Some(r) => r, _ => break, }, ); }   frac.push(current); frac } }   impl fmt::Display for Rational { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.denominator.is_one() { // for integers only display the integer part write!(f, "{}", self.nominator) } else { write!(f, "{}/{}", self.nominator, self.denominator) } } }   fn rational_vec_to_string(vec: Vec<Rational>) -> String { let mut p = vec .iter() .fold(String::new(), |acc, num| (acc + &num.to_string() + ", "));   if p.len() > 1 { p.truncate(p.len() - 2); } format!("[{}]", p) }   fn run_max_searches(x: usize) { // generate all proper fractions with 2 digits let pairs = (1..x).flat_map(move |i| (i + 1..x).map(move |j| (i, j)));   let mut max_length = (0, Rational::new(&BigInt::from(1), &BigInt::from(1))); let mut max_denom = ( Zero::zero(), Rational::new(&BigInt::from(1), &BigInt::from(1)), );   for (i, j) in pairs { let e = Rational::new(&BigInt::from(i), &BigInt::from(j)).to_egyptian(); if e.len() > max_length.0 { max_length = (e.len(), Rational::new(&BigInt::from(i), &BigInt::from(j))); }   if e.last().unwrap().denominator > max_denom.0 { max_denom = ( e.last().unwrap().denominator.clone(), Rational::new(&BigInt::from(i), &BigInt::from(j)), ); } }   println!( "Maximum length of terms is for {} with {} terms", max_length.1, max_length.0 ); println!("{}", rational_vec_to_string(max_length.1.to_egyptian()));   println!( "Maximum denominator is for {} with {} terms", max_denom.1, max_denom.0 ); println!("{}", rational_vec_to_string(max_denom.1.to_egyptian())); } fn main() { let tests = [ Rational::new(&BigInt::from(43), &BigInt::from(48)), Rational::new(&BigInt::from(5), &BigInt::from(121)), Rational::new(&BigInt::from(2014), &BigInt::from(59)), ];   for test in tests.iter() { println!("{} -> {}", test, rational_vec_to_string(test.to_egyptian())); }   run_max_searches(100); run_max_searches(1000); }    
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
#VBScript
VBScript
option explicit   class List private theList private nOccupiable private nTop   sub class_initialize nTop = 0 nOccupiable = 100 redim theList( nOccupiable ) end sub   public sub store( x ) if nTop >= nOccupiable then nOccupiable = nOccupiable + 100 redim preserve theList( nOccupiable ) end if theList( nTop ) = x nTop = nTop + 1 end sub   public function recall( n ) if n >= 0 and n <= nOccupiable then recall = theList( n ) else err.raise vbObjectError + 1000,,"Recall bounds error" end if end function   public sub replace( n, x ) if n >= 0 and n <= nOccupiable then theList( n ) = x else err.raise vbObjectError + 1001,,"Replace bounds error" end if end sub   public property get listCount listCount = nTop end property   end class   function halve( n ) halve = int( n / 2 ) end function   function twice( n ) twice = int( n * 2 ) end function   function iseven( n ) iseven = ( ( n mod 2 ) = 0 ) end function     function multiply( n1, n2 ) dim LL set LL = new List   dim RR set RR = new List   LL.store n1 RR.store n2   do while n1 <> 1 n1 = halve( n1 ) LL.store n1 n2 = twice( n2 ) RR.store n2 loop   dim i for i = 0 to LL.listCount if iseven( LL.recall( i ) ) then RR.replace i, 0 end if next   dim total total = 0 for i = 0 to RR.listCount total = total + RR.recall( i ) next   multiply = total end function  
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
#XL
XL
0! -> 1 N! -> N * (N-1)!
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Rust
Rust
  use std::net::{TcpListener, TcpStream}; use std::io::{BufReader, BufRead, Write}; use std::thread;   fn main() { let listener = TcpListener::bind("127.0.0.1:12321").unwrap(); println!("server is running on 127.0.0.1:12321 ...");   for stream in listener.incoming() { let stream = stream.unwrap(); thread::spawn(move || handle_client(stream)); } }   fn handle_client(stream: TcpStream) { let mut stream = BufReader::new(stream); loop { let mut buf = String::new(); if stream.read_line(&mut buf).is_err() { break; } stream .get_ref() .write(buf.as_bytes()) .unwrap(); } }