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 ...
#Go
Go
package main   import ( "image" "image/color" "image/gif" "log" "math" "os" )   const ( width, height = 640, 640 offset = height / 2 fileName = "rotatingCube.gif" )   var nodes = [][]float64{{-100, -100, -100}, {-100, -100, 100}, {-100, 100, -100}, {-100, 100, 100}, {100, -100, -100}, {100, -100, ...
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 ...
#MATLAB
MATLAB
a = rand; b = rand(10,10); scalar_matrix = a * b; component_wise = b .* b;
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Arendelle
Arendelle
[ #j , [ #i , { ( #x - 19 ) ^ 2 + ( #y - 14 ) ^ 2 < 125 , p } r ] [ #i , l ] d ]
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 inse...
#C.2B.2B
C++
template <typename T> void insert_after(Node<T>* N, T&& data) { auto node = new Node<T>{N, N->next, std::forward(data)}; if(N->next != nullptr) N->next->prev = node; N->next = node; }
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#Clojure
Clojure
(defrecord Node [prev next data])   (defn new-node [prev next data] (Node. (ref prev) (ref next) data))   (defn new-list [head tail] (List. (ref head) (ref tail)))   (defn insert-between [node1 node2 new-node] (dosync (ref-set (:next node1) new-node) (ref-set (:prev new-node) node1) (ref-set (:next new-n...
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: Def...
#AutoHotkey
AutoHotkey
LINK(L₁,1)→A LINK(L₁+10,2)→B LINK(L₁+50,3)→C   INSERT(A,B) INSERT(A,C)   A→I While I≠0 Disp VALUE(I)▶Dec,i NEXT(I)→I End   Disp "-----",i   B→I While I≠0 Disp VALUE(I)▶Dec,i PREV(I)→I 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: Def...
#Axe
Axe
LINK(L₁,1)→A LINK(L₁+10,2)→B LINK(L₁+50,3)→C   INSERT(A,B) INSERT(A,C)   A→I While I≠0 Disp VALUE(I)▶Dec,i NEXT(I)→I End   Disp "-----",i   B→I While I≠0 Disp VALUE(I)▶Dec,i PREV(I)→I 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: Def...
#BBC_BASIC
BBC BASIC
DIM node{pPrev%, pNext%, iData%} DIM a{} = node{}, b{} = node{}, c{} = node{}   a.pNext% = b{} a.iData% = 123 b.pPrev% = a{} b.iData% = 789 c.iData% = 456   PROCinsert(a{}, c{})   PRINT "Traverse forwards:" pnode% = a{} REPEAT  !(^node{}+4) = pnod...
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 ...
#Action.21
Action!
DEFINE PTR="CARD"   TYPE ListNode=[ BYTE data PTR prv,nxt]
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 fla...
#BaCon
BaCon
DECLARE color$[] = { "red", "white", "blue" }   DOTIMES 16 ball$ = APPEND$(ball$, 0, color$[RANDOM(3)] ) DONE   PRINT "Unsorted: ", ball$   PRINT " Sorted: ", REPLACE$(SORT$(REPLACE$(ball$, "blue", "z")), "z", "blue")
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#BASIC256
BASIC256
arraybase 1 dim flag = {"Red","White","Blue"} dim balls(9)   print "Random: |"; for i = 1 to 9 kolor = (rand * 3) + 1 balls[i] = flag[kolor] print balls[i]; " |"; next i print   print "Sorted: |"; for i = 1 to 3 kolor = flag[i] for j = 1 to 9 if balls[j] = kolor then print balls[j]; " |"; ...
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. R...
#AWK
AWK
  # syntax: GAWK -f DRAW_A_CUBOID.AWK [-v x=?] [-v y=?] [-v z=?] # example: GAWK -f DRAW_A_CUBOID.AWK -v x=12 -v y=4 -v z=6 # converted from VBSCRIPT BEGIN { init_sides() draw_cuboid(2,3,4) draw_cuboid(1,1,1) draw_cuboid(6,2,1) exit (errors == 0) ? 0 : 1 } function draw_cuboid(nx,ny,nz, esf,i,i_max...
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.
#Maxima
Maxima
/* Use :: for indirect assignment */ block([name: read("name?"), x: read("value?")], name :: x);
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.
#min
min
42 "Enter a variable name" ask define
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.
#MUMPS
MUMPS
USER>KILL ;Clean up workspace   USER>WRITE ;show all variables and definitions   USER>READ "Enter a variable name: ",A Enter a variable name: GIBBERISH USER>SET @A=3.14159   USER>WRITE   A="GIBBERISH" GIBBERISH=3.14159
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
#Julia
Julia
using Gtk, Graphics   const can = @GtkCanvas() const win = GtkWindow(can, "Draw a Pixel", 320, 240)   draw(can) do widget ctx = getgc(can) set_source_rgb(ctx, 255, 0, 0) move_to(ctx, 100, 100) line_to(ctx, 101,100) stroke(ctx) end   show(can) const cond = Condition() endit(w) = notify(cond) signal_c...
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
#Kotlin
Kotlin
// Version 1.2.41   import java.awt.Color import java.awt.Graphics import java.awt.image.BufferedImage   class BasicBitmapStorage(width: Int, height: Int) { val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)   fun fill(c: Color) { val g = image.graphics g.color = c g....
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...
#Phix
Phix
with javascript_semantics procedure egyptian_division(integer dividend, divisor) integer p2 = 1, dbl = divisor, ans = 0, accum = 0 sequence p2s = {}, dbls = {}, args while dbl<=dividend do p2s = append(p2s,p2) dbls = append(dbls,dbl) dbl += dbl p2 += p2 end while for ...
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...
#Phix
Phix
with javascript_semantics include mpfr.e function egyptian(integer num, denom) mpz n = mpz_init(num), d = mpz_init(denom), t = mpz_init() sequence result = {} while mpz_cmp_si(n,0)!=0 do mpz_cdiv_q(t, d, n) result = append(result,"1/"&mpz_get_str(t)) mpz_neg(d,d) ...
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 ...
#Swift
Swift
import Darwin   func ethiopian(var #int1:Int, var #int2:Int) -> Int { var lhs = [int1], rhs = [int2]   func isEven(#n:Int) -> Bool {return n % 2 == 0} func double(#n:Int) -> Int {return n * 2} func halve(#n:Int) -> Int {return n / 2}   while int1 != 1 { lhs.append(halve(n: int1)) rhs.append(double(n: ...
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 ...
#Rust
Rust
  fn main() { struct ElementaryCA { rule: u8, state: u64, } impl ElementaryCA { fn new(rule: u8) -> (u64, ElementaryCA) { let out = ElementaryCA { rule, state: 1, }; (out.state, out) } fn next(&mut se...
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 ...
#Scala
Scala
import java.awt._ import java.awt.event.ActionEvent   import javax.swing._   object ElementaryCellularAutomaton extends App {   SwingUtilities.invokeLater(() => new JFrame("Elementary Cellular Automaton") {   class ElementaryCellularAutomaton extends JPanel { private val dim = new Dimension(900, 450...
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 iterat...
#Wart
Wart
def (fact n) if (n = 0) 1 (n * (fact 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 local...
#PureBasic
PureBasic
NewMap RecData.s() OpenWindow(0, 100, 200, 200, 100, "Echo Server", #PB_Window_SystemMenu | #PB_Window_MinimizeGadget ) InitNetwork() CreateNetworkServer(1, 12321)   Repeat Event = NetworkServerEvent() ClientID = EventClient()   If Event = #PB_NetworkEvent_Connect ; When a new client has been connected... ...
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 billio...
#Phix
Phix
with javascript_semantics function count_eban(integer p10) -- returns the count of eban numbers 1..power(10,p10) integer n = p10-floor(p10/3), p5 = floor(n/2), p4 = floor((n+1)/2) return power(5,p5)*power(4,p4)-1 end function function eban(integer n) -- returns true if n is an eban num...
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 ...
#Haskell
Haskell
{-# LANGUAGE RecursiveDo #-} import Reflex.Dom import Data.Map as DM (Map, lookup, insert, empty, fromList) import Data.Matrix import Data.Time.Clock import Control.Monad.Trans   size = 500 updateFrequency = 0.2 rotationStep = pi/10   data Color = Red | Green | Blue | Yellow | Orange | Purple | Black deriving (Sho...
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 ...
#Maxima
Maxima
a: matrix([1, 2], [3, 4]); b: matrix([2, 4], [3, 1]);   a * b; a / b; a + b; a - b; a^3; a^b; /* won't work */ fullmapl("^", a, b); sin(a);
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 ...
#Nim
Nim
import math, strutils   type Matrix[height, width: static Positive; T: SomeNumber] = array[height, array[width, T]]   ####################################################################################################   proc `$`(m: Matrix): string = for i, row in m: var line = "[" for j, val in row: li...
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
#ATS
ATS
  (* ** Solution to Draw_a_sphere.dats *)   (* ****** ****** *) // #include "share/atspre_define.hats" // defines some names #include "share/atspre_staload.hats" // for targeting C #include "share/HATS/atspre_staload_libats_ML.hats" // for ... #include "share/HATS/atslib_staload_libats_libc.hats" // for libc // (* ****...
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 inse...
#Common_Lisp
Common Lisp
import std.stdio;   struct Node(T) { T data; typeof(this)* prev, next; }   /// If prev is null, prev gets to point to a new node. void insertAfter(T)(ref Node!T* prev, T item) pure nothrow { if (prev) { auto newNode = new Node!T(item, prev, prev.next); prev.next = newNode; if (newNod...
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 inse...
#D
D
import std.stdio;   struct Node(T) { T data; typeof(this)* prev, next; }   /// If prev is null, prev gets to point to a new node. void insertAfter(T)(ref Node!T* prev, T item) pure nothrow { if (prev) { auto newNode = new Node!T(item, prev, prev.next); prev.next = newNode; if (newNod...
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: Def...
#C
C
// A doubly linked list of strings; #include <stdio.h> #include <stdlib.h> #include <string.h>   typedef struct sListEntry { const char *value; struct sListEntry *next; struct sListEntry *prev; } *ListEntry, *LinkedList;   typedef struct sListIterator{ ListEntry link; LinkedList head; } *LIterator;...
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 ...
#Ada
Ada
type Link; type Link_Access is access Link; type Link is record Next : Link_Access := null; Prev : Link_Access := null; Data : Integer; end record;
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 ...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- # CO REQUIRES: MODE OBJVALUE = ~ # Mode/type of actual obj to be queued # END CO   MODE OBJLINK = STRUCT( REF OBJLINK next, REF OBJLINK prev, OBJVALUE value # ... etc. required # );   PROC obj link new = REF OBJLINK: HEAP OBJLINK;   PROC obj link free = (REF OBJLINK free)VOID: prev OF...
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 ...
#ALGOL_W
ALGOL W
 % record type to hold an element of a doubly linked list of integers  % record DListIElement ( reference(DListIElement) prev  ; integer iValue  ; reference(DListIElement) next );  % additional record types would be required for othe...
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 fla...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0,0)   nBalls% = 12 DIM Balls$(nBalls%-1), Weight%(nBalls%-1), DutchFlag$(2) DutchFlag$() = "Red ", "White ", "Blue "   REM. Generate random list of balls, ensuring not sorted: REPEAT prev% = 0 : sorted% = TRUE FOR bal...
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 fla...
#C
C
#include <stdio.h> //printf() #include <stdlib.h> //srand(), rand(), RAND_MAX, qsort() #include <stdbool.h> //true, false #include <time.h> //time()   #define NUMBALLS 5 //NUMBALLS>1   int compar(const void *a, const void *b){ char c1=*(const char*)a, c2=*(const char*)b; //first cast void* to char*, then dereference ...
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. R...
#BBC_BASIC
BBC BASIC
ORIGIN 100, 100 PROCcuboid(200, 300, 400) END   DEF PROCcuboid(x, y, z) MOVE 0, 0 : MOVE 0, y GCOL 1 : PLOT 117, x, y GCOL 2 : PLOT 117, x + z * 0.4, y + z * 0.4 GCOL 4 : PLOT 117, x + z * 0.4, z * 0.4 ENDPROC  
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.
#Nanoquery
Nanoquery
print "Enter a variable name: " name = input()   print name + " = " exec(name + " = 42") exec("println " + 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.
#Nim
Nim
import tables   var theVar: int = 5 varMap = initTable[string, pointer]()   proc ptrToInt(p: pointer): int = result = cast[ptr int](p)[]   proc main() = write(stdout, "Enter a var name: ") let sVar = readLine(stdin) varMap[$svar] = theVar.addr echo "Variable ", sVar, " is ", ptrToInt(varMap[$sVar])   when...
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.
#Octave
Octave
varname = input ("Enter variable name: ", "s"); value = input ("Enter value: ", "s"); eval([varname,"=",value]);
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Lambdatalk
Lambdatalk
  1) html/css   {div {@ style="position:relative; left:0; top:0; width:320px; height:240px; border:1px solid #000;"} {div {@ style="position:absolute; left:100px; top:100px; width:1px; height:1px; background:#f00; border:0;"}}}   2) svg   {svg {@ width="320" height="240" ...
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...
#PicoLisp
PicoLisp
(seed (in "/dev/urandom" (rd 8)))   (de divmod (Dend Disor) (cons (/ Dend Disor) (% Dend Disor)) ) (de egyptian (Dend Disor) (let (P 0 D Disor S (make (while (>= Dend (setq @@ (+ D D))) (yoke (cons (** 2 (swap 'P (i...
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...
#Prolog
Prolog
egyptian_divide(Dividend, Divisor, Quotient, Remainder):- powers2_multiples(Dividend, [1], Powers, [Divisor], Multiples), accumulate(Dividend, Powers, Multiples, 0, Quotient, 0, Acc), Remainder is Dividend - Acc.   powers2_multiples(Dividend, Powers, Powers, Multiples, Multiples):- Multiples = [M|_], ...
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...
#Prolog
Prolog
count_digits(Number, Count):- atom_number(A, Number), atom_length(A, Count).   integer_to_atom(Number, Atom):- atom_number(A, Number), atom_length(A, Count), (Count =< 20 -> Atom = A ; sub_atom(A, 0, 10, _, A1), P is Count - 10, sub_atom(A, P, 10, _, A2), ...
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 ...
#Tcl
Tcl
# This is how to declare functions - the mathematical entities - as opposed to procedures proc function {name arguments body} { uplevel 1 [list proc tcl::mathfunc::$name $arguments [list expr $body]] }   function double n {$n * 2} function halve n {$n / 2} function even n {($n & 1) == 0} function mult {a b} { $...
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 ...
#Scheme
Scheme
; uses SRFI-1 library http://srfi.schemers.org/srfi-1/srfi-1.html   (define (evolve ls r) (unfold (lambda (x) (null? (cddr x))) (lambda (x) (vector-ref r (+ (* 4 (first x)) (* 2 (second x)) (third x)))) cdr (cons (last ls) (append ls (list (car ls))))))   (define (automaton s r n) (define (*au...
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 iterat...
#WDTE
WDTE
let max a b => a { < b => b };   let ! n => n { > 1 => - n 1 -> ! -> * n } -> max 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 local...
#Python
Python
import SocketServer   HOST = "localhost" PORT = 12321   # this server uses ThreadingMixIn - one thread per connection # replace with ForkMixIn to spawn a new process per connection   class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): # no need to override anything - default behavior is just fine...
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 billio...
#PicoLisp
PicoLisp
(de _eban? (N) (let (B (/ N 1000000000) R (% N 1000000000) M (/ R 1000000) R (% N 1000000) Z (/ R 1000) R (% R 1000) ) (and (>= M 30) (<= M 66) (setq M (% M 10)) ) (and (>= Z 30) (<= Z 66) (setq Z (% ...
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 billio...
#Python
Python
  # Use inflect   """   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 number...
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 ...
#J
J
require'gl2 gles ide/qt/opengl' coinsert'jgl2 jgles qtopengl'   rotcube=: {{ if.0=nc<'sprog'do.return.end. fixosx=. 'opengl';'opengl',('DARWIN'-:UNAME)#' version 4.1' wd 'pc rot; minwh 300 300; cc cube opengl flush' rplc fixosx HD=: ".wd 'qhwndc cube' wd 'ptimer 17; pshow' }}   rot_close=: {{ wd 'ptimer 0' ...
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if ...
#PARI.2FGP
PARI/GP
multMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]*B[i,j]); divMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]/B[i,j]); powMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]^B[i,j]);
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
#AutoHotkey
AutoHotkey
#NoEnv SetBatchLines, -1 #SingleInstance, Force   ; Uncomment if Gdip.ahk is not in your standard library #Include, Gdip.ahk   ; Settings X := 200, Y := 200, Width := 200, Height := 200 ; Location and size of sphere rotation := -30 ; degrees ARGB := 0xFFFF0000 ; Color=Solid Red   If !pToken := Gdip_Startup() ; Start gd...
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 inse...
#Delphi
Delphi
  program Element_insertion;   {$APPTYPE CONSOLE}   uses System.SysUtils,Boost.LinkedList;   var List:TLinkedList<Integer>; Node:TLinkedListNode<Integer>; begin List := TLinkedList<Integer>.Create; Node:= List.Add(5); List.AddAfter(Node,7); List.AddAfter(Node,15); Writeln(List.ToString); List.Free; Re...
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 inse...
#E
E
def insert(after, value) { def newNode := makeElement(value, after, after.getNext()) after.getNext().setPrev(newNode) after.setNext(newNode) }
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 inse...
#Erlang
Erlang
2> doubly_linked_list:task(). foreach_next a foreach_next c foreach_next b foreach_previous b foreach_previous c foreach_previous a
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: Def...
#C.23
C#
using System; using System.Collections.Generic;   namespace RosettaCode.DoublyLinkedList { internal static class Program { private static void Main() { var list = new LinkedList<char>("hello");   var current = list.First; do { Conso...
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: Def...
#C.2B.2B
C++
#include <iostream> #include <list>   int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */   /* structure Node Doublylinked List*/ .struct 0 NDlist_next: @ next element .struct NDlist_next + 4 NDlist_prev: @ previous element .struct NDlist_prev + 4 NDlist_value: @ element value or key .struct ND...
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 ...
#AutoHotkey
AutoHotkey
Lbl LINK r₂→{r₁}ʳ 0→{r₁+2}ʳ 0→{r₁+4}ʳ r₁ Return   Lbl NEXT {r₁+2}ʳ Return   Lbl PREV {r₁+4}ʳ Return   Lbl VALUE {r₁}ʳ Return
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#Axe
Axe
Lbl LINK r₂→{r₁}ʳ 0→{r₁+2}ʳ 0→{r₁+4}ʳ r₁ Return   Lbl NEXT {r₁+2}ʳ Return   Lbl PREV {r₁+4}ʳ Return   Lbl VALUE {r₁}ʳ Return
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#C.2B.2B
C++
#include <algorithm> #include <iostream>   // Dutch national flag problem template <typename BidIt, typename T> void dnf_partition(BidIt first, BidIt last, const T& low, const T& high) { for (BidIt next = first; next != last; ) { if (*next < low) { std::iter_swap(first++, next++); } else...
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. R...
#Befunge
Befunge
"  :htdiW">:#,_>&>00p" :thgieH">:#,_>&>:10p0"  :htpeD">:#,_$>&>:20p55+,+:1`*:vv v\-*`0:-g01\++*`\0:-\-1g01:\-*`0:-g02\+*`\0:-\-1g02<:::::<\g3`\g01:\1\+55\1-1_v >":"\1\:20g\`!3g:30p\00g2*\::20g\`\20g1-\`+1+3g\1\30g\:20g-::0\`\2*1+*-\48*\:^v /\_ @_\#!:!#$>#$_\#!:,#-\#1 <+1\<*84g02"_"+1*2g00+551$<
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.
#Oforth
Oforth
: createVar(varname) "tvar: " varname + eval ;   "myvar" createVar   12 myvar put myvar at .
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.
#PARI.2FGP
PARI/GP
eval(Str(input(), "=34"))
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.
#Pascal
Pascal
  PROGRAM ExDynVar;   {$IFDEF FPC} {$mode objfpc}{$H+}{$J-}{R+} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF}   (*) Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64 The free and readable alternative at C/C++ speeds compiles natively to almost any platform, including raspberry PI   This demo uses...
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
#Lua
Lua
local SDL = require "SDL"   local ret = SDL.init { SDL.flags.Video } local window = SDL.createWindow { title = "Pixel", height = 320, width = 240 }   local renderer = SDL.createRenderer(window, 0, 0)   renderer:clear() renderer:setDrawColor(0xFF0000) renderer:drawPoint({x = 100,y = 100}) renderer:present()   SDL.del...
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
CreateWindow[PaletteNotebook[{Graphics[{Red, Point[{100, 100}]}]}], WindowSize -> {320, 240}]
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...
#Python
Python
from itertools import product   def egyptian_divmod(dividend, divisor): assert divisor != 0 pwrs, dbls = [1], [divisor] while dbls[-1] <= dividend: pwrs.append(pwrs[-1] * 2) dbls.append(pwrs[-1] * divisor) ans, accum = 0, 0 for pwr, dbl in zip(pwrs[-2::-1], dbls[-2::-1]): if ...
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...
#Python
Python
from fractions import Fraction from math import ceil   class Fr(Fraction): def __repr__(self): return '%s/%s' % (self.numerator, self.denominator)   def ef(fr): ans = [] if fr >= 1: if fr.denominator == 1: return [[int(fr)], Fr(0, 1)] intfr = int(fr) ans, fr = [[i...
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 ...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT ASK "insert number1", nr1="" ASK "insert number2", nr2=""   SET nrs=APPEND(nr1,nr2),size_nrs=SIZE(nrs) IF (size_nrs!=2) ERROR/STOP "insert two numbers" LOOP n=nrs IF (n!='digits') ERROR/STOP n, " is not a digit" ENDLOOP   PRINT "ethopian multiplication of ",nr1," and ",nr2   SET sum=0 SECTION checkif...
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 ...
#Sidef
Sidef
class Automaton(rule, cells) {   method init { rule = sprintf("%08b", rule).chars.map{.to_i}.reverse }   method next { var previous = cells.map{_} var len = previous.len cells[] = rule[ previous.range.map { |i| 4*previous[i-1 % len]...
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 iterat...
#WebAssembly
WebAssembly
  (module  ;; recursive (func $fac (param f64) (result f64) get_local 0 f64.const 1 f64.lt if (result f64) f64.const 1 else get_local 0 get_local 0 f64.const 1 f64.sub call $fac f64.mul end) (export "fac" (func $fac)))  
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 local...
#Racket
Racket
  #lang racket (define listener (tcp-listen 12321)) (let echo-server () (define-values [I O] (tcp-accept listener)) (thread (λ() (copy-port I O) (close-output-port O))) (echo-server))  
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 billio...
#Raku
Raku
use Lingua::EN::Numbers;   sub nban ($seq, $n = 'e') { ($seq).map: { next if .&cardinal.contains(any($n.lc.comb)); $_ } }   sub enumerate ($n, $upto) { my @ban = [nban(1 .. 99, $n)],; my @orders; (2 .. $upto).map: -> $o { given $o % 3 { # Compensate for irregulars: 11 - 19 when 1 { @ord...
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 ...
#Java
Java
import java.awt.*; import java.awt.event.ActionEvent; import static java.lang.Math.*; import javax.swing.*;   public class RotatingCube extends JPanel { double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1}, {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};   int[][] edges = {{0, 1}, {1, 3},...
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 ...
#Perl
Perl
package Elementwise;   use Exporter 'import';   use overload '=' => sub { $_[0]->clone() }, '+' => sub { $_[0]->add($_[1]) }, '-' => sub { $_[0]->sub($_[1]) }, '*' => sub { $_[0]->mul($_[1]) }, '/' => sub { $_[0]->div($_[1]) }, '**' => sub { $_[0]->exp($_[1]) }, ;   sub new { my ($class, $v) = @_; return bless ...
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
#AWK
AWK
  # syntax: GAWK -f DRAW_A_SPHERE.AWK # converted from VBSCRIPT BEGIN { draw_sphere(20,4,0.1) draw_sphere(10,2,0.4) exit(0) } function draw_sphere(radius,k,ambient, b,i,intensity,j,leng_shades,light,line,shades,vec,x,y) { leng_shades = split0(".:!*oe&#%@",shades,"") split("30,30,-50",light,",") ...
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 inse...
#Fortran
Fortran
module dlList public :: node, insertAfter, getNext   type node real :: data type( node ), pointer :: next => null() type( node ), pointer :: previous => null() end type node   contains subroutine insertAfter(nodeBefore, value) type( node ), intent(inout), target :: nodeBe...
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: Def...
#Clojure
Clojure
(def dl (double-list [:a :b :c :d])) ;=> #'user/dl   ((juxt seq rseq) dl) ;=> [(:a :b :c :d) (:d :c :b :a)]   (take-while identity (iterate get-next (get-head dl))) ;=> (#:double_list.Node{:prev nil,  :next #<Object...>, :data :a, :key #<Object...>} ;=> #:double_list.Node{:prev #<Object...>, :next #<Object...>...
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: Def...
#D
D
void main() { import std.stdio, std.container, std.range;   auto dll = DList!dchar("DCBA"d.dup);   dll[].writeln; dll[].retro.writeln; }
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 ...
#BBC_BASIC
BBC BASIC
DIM node{pPrev%, pNext%, iData%}  
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 ...
#Bracmat
Bracmat
link=(prev=) (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 ...
#C
C
struct Node { struct Node *next; struct Node *prev; void *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 fla...
#C_sharp
C_sharp
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace RosettaCode { class Program { static void QuickSort(IComparable[] elements, int left, int right) { int i = left, j = right; IComparable pivot = elements[left + (right - left)...
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. R...
#Brlcad
Brlcad
opendb cuboid.g y # Create a database to hold our shapes units cm # Set the unit of measure in cuboid.s rpp 0 2 0 3 0 4 # Create a 2 x 3 x 4 cuboid named cuboid.s
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Perl
Perl
print "Enter a variable name: "; $varname = <STDIN>; # type in "foo" on standard input chomp($varname); $$varname = 42; # when you try to dereference a string, it will be # treated as a "symbolic reference", where they # take the string as the name of the variable print "$foo\n"; # print...
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Phix
Phix
constant globals = new_dict()   while 1 do string name = prompt_string("Enter name or press Enter to quit:") if length(name)=0 then exit end if bool bExists = (getd_index(name,globals)!=NULL) string prompt = iff(not bExists?"No such name, enter a value:"  :sprintf("Already exists, new ...
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.
#PHP
PHP
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "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
#M2000_Interpreter
M2000 Interpreter
      Module CheckIt { Module PlotPixel (a as single, b as single) { Move a*TwipsX, b*TwipsX Draw TwipsX, TwipsY } Cls 5,0 \\ clear console with Magenta (5) and set split screen from 0 (no split screen) Pen #55FF77 { PlotPixel 1000, 200 } Wait 10...
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
#Nim
Nim
import rapid/gfx   var window = initRWindow() .size(320, 240) .title("Rosetta Code - draw a pixel") .open() surface = window.openGfx()   surface.loop: draw ctx, step: ctx.clear(gray(0)) ctx.begin() ctx.point((100.0, 100.0, rgb(255, 0, 0))) ctx.draw(prPoints) discard step # Prevent ...
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...
#Quackery
Quackery
[ dup 0 = if [ $ "Cannot divide by zero." fail ] [] unrot [ 2dup < not while rot over swap join unrot dup + again ] drop swap dup size [] 1 rot times [ tuck swap join swap dup + ] drop temp put 0 swap witheach [ over + ...
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...
#R
R
Egyptian_division <- function(num, den){ pow2 = 0 row = 1   Table = data.frame(powers_of_2 = 2^pow2, doubling = den)   while(Table$doubling[nrow(Table)] < num){ row = row + 1 pow2 = pow2 + 1   Table[row, 1] <- 2^pow2 Table[row, 2] <- 2^pow2 * den }   Table <- Table[-nrow...
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...
#Racket
Racket
#lang racket (define (real->egyptian-list R) (define (inr r rv) (match* ((exact-floor r) (numerator r) (denominator r)) [(0 0 1) (reverse rv)] [(0 1 d) (reverse (cons (/ d) rv))] [(0 x y) (let ((^y/x (exact-ceiling (/ y x)))) (inr (/ (modulo (- y) x) (* y ^y/x)) (cons (/ ^y/x) r...
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 ...
#TypeScript
TypeScript
  // Ethiopian multiplication   function intToString(n: number, wdth: number): string { sn = Math.floor(n).toString(); len = sn.length; return (wdth < len ? "#".repeat(wdth) : " ".repeat(wdth - len) + sn); }   function double(a: number): number { return 2 * a; }   function halve(a: number): number { return Ma...
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 ...
#Tcl
Tcl
package require Tcl 8.6   oo::class create ElementaryAutomaton { variable rules # Decode the rule number to get a collection of state mapping rules. # In effect, "compiles" the rule number constructor {ruleNumber} { set ins {111 110 101 100 011 010 001 000} set bits [split [string range [format %08b $...
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 iterat...
#Wortel
Wortel
@fac 10
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 local...
#Raku
Raku
my $socket = IO::Socket::INET.new: :localhost<localhost>, :localport<12321>, :listen;   while $socket.accept -> $conn { say "Accepted connection"; start { while $conn.recv -> $stuff { say "Echoing $stuff"; $conn.print($stuff); } $conn.close; } }
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 billio...
#REXX
REXX
/*REXX program to display eban numbers (those that don't have an "e" their English name)*/ numeric digits 20 /*support some gihugic numbers for pgm.*/ parse arg $ /*obtain optional arguments from the cL*/ if $='' then $= '1 1000 1000 4000 1 -10000...