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/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.
#Julia
Julia
print("Insert the variable name: ")   variable = Symbol(readline(STDIN)) expression = quote $variable = 42 println("Inside quote:") @show $variable end   eval(expression)   println("Outside quote:") @show variable println("If I named the variable x:") @show x
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
#Forth
Forth
\ Bindings to SDL2 functions s" SDL2" add-lib \c #include <SDL2/SDL.h> c-function sdl-init SDL_Init n -- n c-function sdl-quit SDL_Quit -- void c-function sdl-createwindow SDL_CreateWindow a n n n n n -- a c-function sdl-createrenderer SDL_CreateRenderer a n n -- a c-function sdl-setdrawcolor SDL_SetRenderDrawColor...
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
#FreeBASIC
FreeBASIC
' version 27-06-2018 ' compile with: fbc -s console ' or: fbc -s gui   Screen 13 ' Screen 18: 320x200, 8bit colordepth 'ScreenRes 320, 200, 24 ' Screenres: 320x200, 24bit colordepth   If ScreenPtr = 0 Then Print "Error setting video mode!" End End If   Dim As UInteger depth, x = 1...
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...
#JavaScript
JavaScript
(() => { 'use strict';   // EGYPTIAN DIVISION --------------------------------   // eqyptianQuotRem :: Int -> Int -> (Int, Int) const eqyptianQuotRem = (m, n) => { const expansion = ([i, x]) => x > m ? ( Nothing() ) : Just([ [i, x], ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
frac[n_] /; IntegerQ[1/n] := frac[n] = {n}; frac[n_] := frac[n] = With[{p = Numerator[n], q = Denominator[n]}, Prepend[frac[Mod[-q, p]/(q Ceiling[1/n])], 1/Ceiling[1/n]]]; disp[f_] := StringRiffle[ SequenceCases[f, l : {_, 1 ...} :> If[Length[l] == 1 && l[[1]] < 1, ToString[l[[1]], Input...
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 ...
#Sidef
Sidef
func double (n) { n << 1 } func halve (n) { n >> 1 } func isEven (n) { n&1 == 0 }   func ethiopian_mult(a, b) { var r = 0 while (a > 0) { r += b if !isEven(a) a = halve(a) b = double(b) } return r }   say ethiopian_mult(17, 34)
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 ...
#PicoLisp
PicoLisp
(de dictionary (N) (extract '((A B) (and (= "1" B) (mapcar '((L) (if (= "1" L) "#" ".")) A ) ) ) (mapcar '((N) (chop (pad 3 (bin N)))) (range 7 0) ) (chop (pad 8 (bin N))) ) ) (de cellular (Lst N) (let (Lst (chop Ls...
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 ...
#Prolog
Prolog
play :- initial(I), do_auto(50, I).   initial([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0]).   do_auto(0, _) :- !. do_auto(N, I) :- maplist(writ, I), nl, apply_rules(I, Next), succ(N1, N), do_auto(N1, Next).   r(0,0,0,0). r(0,0,1,1). r(0,1,0,0). r(0,1,1,1). r(1,0,0,1). r(1,0,1,0). r(1,1,0,1). r(1,1,1,0).   apply...
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...
#VHDL
VHDL
LIBRARY ieee; USE ieee.std_logic_1164.ALL; USE ieee.numeric_std.ALL;   ENTITY Factorial IS GENERIC ( Nbin : INTEGER := 3 ; -- number of bit to input number Nbou : INTEGER := 13) ; -- number of bit to output factorial   PORT ( clk : IN STD_LOGIC ; -- clock of circuit sr : IN STD_LOGIC_VECTOR(1 DOWNTO 0); -...
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...
#Oz
Oz
declare ServerSocket = {New Open.socket init}   proc {Echo Socket} case {Socket getS($)} of false then skip [] Line then {System.showInfo "Received line: "#Line} {Socket write(vs:Line#"\n")} {Echo Socket} end end   class TextSocket from Open.socket Open.text end in {Serv...
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Zoea
Zoea
  program: empty  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Zoea_Visual
Zoea Visual
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Zoomscript
Zoomscript
 
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...
#Java
Java
import java.util.List;   public class Main { private static class Range { int start; int end; boolean print;   public Range(int s, int e, boolean p) { start = s; end = e; print = p; } }   public static void main(String[] args) { ...
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 ...
#Delphi
Delphi
  unit main;   interface   uses Winapi.Windows, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, System.Math, System.Classes;   type TForm1 = class(TForm) tmr1: TTimer; procedure FormCreate(Sender: TObject); procedure tmr1Timer(Sender: TObject); private { Private declarations } public ...
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 ...
#Julia
Julia
@show [1 2 3; 3 2 1] .+ [2 1 2; 0 2 1] @show [1 2 3; 2 1 2] .+ 1 @show [1 2 3; 2 2 1] .- [1 1 1; 2 1 0] @show [1 2 1; 1 2 3] .* [3 2 1; 1 0 1] @show [1 2 3; 3 2 1] .* 2 @show [9 8 6; 3 2 3] ./ [3 1 2; 2 1 2] @show [3 2 2; 1 2 3] .^ [1 2 3; 2 1 2]
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#11l
11l
V shades = [‘.’, ‘:’, ‘!’, ‘*’, ‘o’, ‘e’, ‘&’, ‘#’, ‘%’, ‘@’]   F dotp(v1, v2) V d = dot(v1, v2) R I d < 0 {-d} E 0.0   F draw_sphere(r, k, ambient, light) L(i) Int(floor(-r)) .< Int(ceil(r) + 1) V x = i + 0.5 V line = ‘’   L(j) Int(floor(-2 * r)) .< Int(ceil(2 * r) + 1) V y = j / 2 ...
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#Action.21
Action!
SET EndProg=*
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...
#AppleScript
AppleScript
use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later — for these 'use' commands! -- This script uses a customisable AppleScript sort available at <https://macscripter.net/viewtopic.php?pid=194430#p194430>. -- It's assumed that scripters will know how and where to install it as a library. use sorter : scrip...
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...
#Action.21
Action!
PROC DrawCuboid(CARD x,y BYTE w,h,d) BYTE wsize=[10],hsize=[10],dsize=[5] BYTE i   FOR i=0 TO w DO Plot(x+i*wsize,y+h*hsize) DrawTo(x+i*wsize,y) DrawTo(x+i*wsize+d*dsize,y-d*dsize) OD FOR i=0 TO h DO Plot(x,y+i*hsize) DrawTo(x+w*wsize,y+i*hsize) DrawTo(x+w*wsize+d*dsize,y+i*hsize-d...
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.
#Kotlin
Kotlin
// version 1.1.4   fun main(args: Array<String>) { var n: Int do { print("How many integer variables do you want to create (max 5) : ") n = readLine()!!.toInt() } while (n < 1 || n > 5)   val map = mutableMapOf<String, Int>() var name: String var value: Int var i = 1 ...
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
#GB_BASIC
GB BASIC
10 color 1 20 point 100,100
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
#GML
GML
draw_point(100, 100);
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...
#Julia
Julia
function egyptiandivision(dividend::Int, divisor::Int) N = 64 powers = Vector{Int}(N) doublings = Vector{Int}(N)   ind = 0 for i in 0:N-1 powers[i+1] = 1 << i doublings[i+1] = divisor << i if doublings[i+1] > dividend ind = i-1; break end end   ans = acc = ...
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...
#Kotlin
Kotlin
// version 1.1.4   data class DivMod(val quotient: Int, val remainder: Int)   fun egyptianDivide(dividend: Int, divisor: Int): DivMod { require (dividend >= 0 && divisor > 0) if (dividend < divisor) return DivMod(0, dividend) val powersOfTwo = mutableListOf(1) val doublings = mutableListOf(divisor) ...
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...
#Microsoft_Small_Basic
Microsoft Small Basic
'Egyptian fractions - 26/07/2018 xx=2014 yy=59 x=xx y=yy If x>=y Then q=Math.Floor(x/y) tt="+("+q+")" x=Math.Remainder(x,y) EndIf If x<>0 Then While x<>1 'i=modulo(-y,x) u=-y v=x modulo() i=ret k=Math.Ceiling(y/x) m=m+1 tt=tt+"+1/"+k j=...
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 ...
#Smalltalk
Smalltalk
Number extend [ double [ ^ self * 2 ] halve [ ^ self // 2 ] ethiopianMultiplyBy: aNumber withTutor: tutor [ |result multiplier multiplicand| multiplier := self. multiplicand := aNumber. tutor ifTrue: [ ('ethiopian multiplication of %1 and %2' % { multiplier. multiplicand })...
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 ...
#Python
Python
def eca(cells, rule): lencells = len(cells) c = "0" + cells + "0" # Zero pad the ends rulebits = '{0:08b}'.format(rule) neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)} yield c[1:-1] while True: c = ''.join(['0', ''.join(neighbours2next[...
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...
#Vim_Script
Vim Script
function! Factorial(n) if a:n < 2 return 1 else return a:n * Factorial(a:n-1) endif endfunction
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...
#Perl
Perl
use IO::Socket; my $use_fork = 1;   my $sock = new IO::Socket::INET ( LocalHost => '127.0.0.1', LocalPort => '12321', Proto => 'tcp', Listen => 1, # maximum queued connections ...
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...
#jq
jq
# quotient and remainder def quotient($a; $b; f; g): f = (($a/$b)|floor) | g = $a % $b;   def tasks: [2, 1000, true], [1000, 4000, true], (1e4, 1e5, 1e6, 1e7, 1e8 | [2, ., false]) ;   def task: def update(f): if (f >= 30 and f <= 66) then f %= 10 else . end;   tasks as $rg | if $rg[0] == 2 then "e...
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...
#Julia
Julia
  function iseban(n::Integer) b, r = divrem(n, oftype(n, 10 ^ 9)) m, r = divrem(r, oftype(n, 10 ^ 6)) t, r = divrem(r, oftype(n, 10 ^ 3)) m, t, r = (30 <= x <= 66 ? x % 10 : x for x in (m, t, r)) return all(in((0, 2, 4, 6)), (b, m, t, r)) end   println("eban numbers up to and including 1000:") print...
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 ...
#EasyLang
EasyLang
node[][] = [ [ -1 -1 -1 ] [ -1 -1 1 ] [ -1 1 -1 ] [ -1 1 1 ] [ 1 -1 -1 ] [ 1 -1 1 ] [ 1 1 -1 ] [ 1 1 1 ] ] edge[][] = [ [ 0 1 ] [ 1 3 ] [ 3 2 ] [ 2 0 ] [ 4 5 ] [ 5 7 ] [ 7 6 ] [ 6 4 ] [ 0 4 ] [ 1 5 ] [ 2 6 ] [ 3 7 ] ] # func scale f . . for i range len node[][] for d range 3 node[i][d] *= f . . . fun...
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 ...
#K
K
scalar: 10 vector: 2 3 5 matrix: 3 3 # 7 11 13 17 19 23 29 31 37   scalar * scalar 100 scalar * vector 20 30 50 scalar * matrix (70 110 130 170 190 230 290 310 370)   vector * vector 4 9 25 vector * matrix (14 22 26 51 57 69 145 155 185)   matrix * matrix (49 121 169 289 361 529 841 9...
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 ...
#Kotlin
Kotlin
// version 1.1.51   typealias Matrix = Array<DoubleArray> typealias Op = Double.(Double) -> Double   fun Double.dPow(exp: Double) = Math.pow(this, exp)   fun Matrix.elementwiseOp(other: Matrix, op: Op): Matrix { require(this.size == other.size && this[0].size == other[0].size) val result = Array(this.size) { Do...
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
#Action.21
Action!
INT ARRAY SinTab=[ 0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83 88 92 96 100 104 108 112 116 120 124 128 132 136 139 143 147 150 154 158 161 165 168 171 175 178 181 184 187 190 193 196 199 202 204 207 210 212 215 217 219 222 224 226 228 230 232 234 236 237 239 241 242 243 245 246 247 248 249 250...
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...
#Ada
Ada
procedure Insert (Anchor : Link_Access; New_Link : Link_Access) is begin if Anchor /= Null and New_Link /= Null then New_Link.Next := Anchor.Next; New_Link.Prev := Anchor; if New_Link.Next /= Null then New_Link.Next.Prev := New_Link; end if; Anchor.Next := New_Link; end if; ...
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...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   # SEMA do link OF splice = LEVEL 1 # MODE LINK = STRUCT ( REF LINK prev, REF LINK next, DATA value );   # BEGIN rosettacode task specimen code: can handle insert both before the first, and after the last link #   PROC insert after = (REF LINK #self,# prev, DATA new data)LINK: ...
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...
#Action.21
Action!
SET EndProg=*
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...
#Applesoft_BASIC
Applesoft BASIC
100 READ C$(0),C$(1),C$(2) 110 DATARED,WHITE,BLUE,0 120 PRINT "RANDOM: 130 FOR N = 0 TO 9 140 LET B%(N) = RND (1) * 3 150 GOSUB 250 160 NEXT N 170 PRINT 180 READ S 190 PRINT "SORTED: 200 FOR I = 0 TO 2 210 FOR N = 0 TO 9 220 ON B%(N) = I GOSUB 250 230 NEXT N,I 240 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 fla...
#AutoHotkey
AutoHotkey
RandGen(MaxBalls){ Random,k,3,MaxBalls Loop,% k{ Random,k,1,3 o.=k }return o } While((!InStr(o,1)||!InStr(o,2)||!InStr(o,3))||!RegExReplace(o,"\b1+2+3+\b")) o:=RandGen(3) Loop,% StrLen(o) F.=SubStr(o,A_Index,1) "," F:=RTrim(F,",") Sort,F,N D`, MsgBox,% F:=RegExReplace(RegExReplace(RegExReplace(F,"(1)","Red"),"(2)",...
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...
#Ada
Ada
with Ada.Text_IO;   procedure Main is type Char_Matrix is array (Positive range <>, Positive range <>) of Character;   function Create_Cuboid (Width, Height, Depth : Positive) return Char_Matrix is Result : Char_Matrix (1 .. Height + Depth + 3, 1 .. 2 * Width + De...
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.
#Lasso
Lasso
local(thename = web_request->param('thename')->asString) if(#thename->size) => {^ var(#thename = math_random) var(#thename) else '<a href="?thename=xyz">Please give the variable a name!</a>' ^}
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.
#Lingo
Lingo
-- varName might contain a string that was entered by a user at runtime   -- A new global variable with a user-defined name can be created at runtime like this: (the globals)[varName] = 23 -- or (the globals).setProp(varName, 23)   -- An new instance variable (object property) with a user-defined name can be created 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.
#Logo
Logo
? make readword readword julie 12 ? show :julie 12
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
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/draw" )   func main() { rect := image.Rect(0, 0, 320, 240) img := image.NewRGBA(rect)   // Use green background, say. green := color.RGBA{0, 255, 0, 255} draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)   /...
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...
#Lua
Lua
function egyptian_divmod(dividend,divisor) local pwrs, dbls = {1}, {divisor} while dbls[#dbls] <= dividend do table.insert(pwrs, pwrs[#pwrs] * 2) table.insert(dbls, pwrs[#pwrs] * divisor) end local ans, accum = 0, 0   for i=#pwrs-1,1,-1 do if accum + dbls[i] <= dividend then ...
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...
#Nim
Nim
import strformat, strutils import bignum   let Zero = newInt(0) One = newInt(1)   #---------------------------------------------------------------------------------------------------   proc toEgyptianrecursive(rat: Rat; fracs: seq[Rat]): seq[Rat] =   if rat.isZero: return fracs   let iquo = cdiv(rat.denom, rat....
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 ...
#SNOBOL4
SNOBOL4
  define('halve(num)') :(halve_end) halve eq(num,1) :s(freturn) halve = num / 2 :(return) halve_end   define('double(num)') :(double_end) double double = num * 2 :(return) double_end   define('odd(num)') :(odd_end) odd eq(num,1) :s(return) eq(num,double(halve(num))) :s(freturn)f(return)   odd_end l = trim(input) ...
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 ...
#Quackery
Quackery
( the Cellular Automaton is on the stack as 3 items, the ) ( Rule (R), the Size of the space (S) and the Current ) ( state (C). make-ca sets this up from a string indicating ) ( the size and starting state, and a rule number. )   [ [] swap 8 times [ dup 1 & rot swap join ...
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 ...
#Racket
Racket
#lang racket (require racket/fixnum) (provide usable-bits/fixnum usable-bits/fixnum-1 CA-next-generation wrap-rule-truncate-left-word show-automaton)   (define usable-bits/fixnum 30) (define usable-bits/fixnum-1 (sub1 usable-bits/fixnum)) (define usable-bits/mask (fx- (fxlshift 1 usable-bits/fixnum) 1)) (defin...
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...
#Visual_Basic
Visual Basic
  Option Explicit   Sub Main() Dim i As Variant For i = 1 To 27 Debug.Print "Factorial(" & i & ")= , recursive : " & Format$(FactRec(i), "#,###") & " - iterative : " & Format$(FactIter(i), "#,####") Next End Sub 'Main Private Function FactRec(n As Variant) As Variant n = CDec(n) If n = 1 T...
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...
#Phix
Phix
-- demo\rosetta\EchoServer.exw without js include builtins\sockets.e constant ESCAPE = #1B procedure echo(atom sockd) ?{"socket opened",sockd} string buffer = "" integer bytes_sent bool first = true while true do {integer len, string s} = recv(sockd) if len<=0 then exit end if ...
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...
#Kotlin
Kotlin
// Version 1.3.21   typealias Range = Triple<Int, Int, Boolean>   fun main() { val rgs = listOf<Range>( Range(2, 1000, true), Range(1000, 4000, true), Range(2, 10_000, false), Range(2, 100_000, false), Range(2, 1_000_000, false), Range(2, 10_000_000, false), R...
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 ...
#FreeBASIC
FreeBASIC
#define PI 3.14159265358979323 #define SCALE 50 #define SIZE 320 #define zoff 0.5773502691896257645091487805019574556 #define cylr 1.6329931618554520654648560498039275946 screenres SIZE, SIZE, 4   dim as double theta = 0.0, dtheta = 1.5, x(0 to 5), lasttime, dt = 1./30   dim as double cylphi(0 to 5) = {PI/6, 5*PI/6, 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 ...
#Maple
Maple
# Built-in element-wise operator ~   #addition <1,2,3;4,5,6> +~ 2;   #subtraction <2,3,1,4;0,-2,-2,1> -~ 4;   #multiplication <2,3,1,4;0,-2,-2,1> *~ 4;   #division <2,3,7,9;6,8,4,5;7,0,10,11> /~ 2;   #exponentiation <1,2,0; 7,2,7; 6,11,3>^~5;
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
#Ada
Ada
with Glib; use Glib; with Cairo; use Cairo; with Cairo.Png; use Cairo.Png; with Cairo.Pattern; use Cairo.Pattern; with Cairo.Image_Surface; use Cairo.Image_Surface; with Ada.Numerics;   procedure Sphere is subtype Dub is Glib.Gdouble;   Surface  : Cairo_Surface; C...
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#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/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...
#AutoHotkey
AutoHotkey
Lbl INSERT {r₁+2}ʳ→{r₂+2}ʳ r₁→{r₂+4}ʳ r₂→{{r₂+2}ʳ+4}ʳ r₂→{r₁+2}ʳ r₁ Return
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...
#Axe
Axe
Lbl INSERT {r₁+2}ʳ→{r₂+2}ʳ r₁→{r₂+4}ʳ r₂→{{r₂+2}ʳ+4}ʳ r₂→{r₁+2}ʳ r₁ Return
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...
#Ada
Ada
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_IO;   procedure Traversing is package Char_Lists is new Ada.Containers.Doubly_Linked_Lists (Character);   procedure Print (Position : in Char_Lists.Cursor) is begin Ada.Text_IO.Put (Char_Lists.Element (Position)); end Print;   My_List : Char_Li...
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...
#ALGOL_68
ALGOL 68
# Node struct - contains next and prev NODE pointers and DATA # MODE NODE = STRUCT( DATA data, REF NODE prev, REF NODE next );   # List structure - contains head and tail NODE pointers # MODE LIST = STRUCT( REF NODE head, REF NODE tail );   # --- PREPEND - Adds a node to the beginni...
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...
#AutoIt
AutoIt
  #include <Array.au3> Dutch_Flag(50) Func Dutch_Flag($arrayitems) Local $avArray[$arrayitems] For $i = 0 To UBound($avArray) - 1 $avArray[$i] = Random(1, 3, 1) Next Local $low = 2, $high = 3, $i = 0 Local $arraypos = -1 Local $p = UBound($avArray) - 1 While $i < $p if $avArray[$i] < $low Then $arraypos...
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...
#Arturo
Arturo
cline: function [n,a,b,cde][ print (pad to :string first cde n+1) ++ (repeat to :string cde\1 dec 9*a)++ (to :string cde\0)++ (2 < size cde)? -> pad to :string cde\2 b+1 -> "" ]   cuboid: function [x,y,z][ cline y+1 x 0 "+-" loop 1..y 'i -> cline 1+y-i x i-1 "/ |" cline 0 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.
#Logtalk
Logtalk
  | ?- create_object(Id, [], [set_logtalk_flag(dynamic_declarations,allow)], []), write('Variable name: '), read(Name), write('Variable value: '), read(Value), Fact =.. [Name, Value], Id::assertz(Fact).   Variable name: foo. Variable value: 42. Id = o1, Name = foo, Value = 42, Fact = foo(42).   ?...
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.
#Lua
Lua
_G[io.read()] = 5 --puts 5 in a global variable named by the user
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
#Icon_and_Unicon
Icon and Unicon
# # draw-pixel.icn # procedure main() &window := open("pixel", "g", "size=320,240") Fg("#ff0000") DrawPoint(100, 100) Event() end
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#IS-BASIC
IS-BASIC
100 SET VIDEO X 40:SET VIDEO Y 26:SET VIDEO MODE 5:SET VIDEO COLOR 0 110 OPEN #101:"video:" 120 DISPLAY #101:AT 1 FROM 1 TO 26 130 SET PALETTE BLACK,RED 140 PLOT 100,100
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[EgyptianDivide] EgyptianDivide[dividend_, divisor_] := Module[{table, i, answer, accumulator}, table = {{1, divisor}}; i = 1; While[Last[Last[table]] < dividend, AppendTo[table, 2^i {1, divisor}]; i++ ]; table //= Most; answer = 0; accumulator = 0; Do[ If[accumulator + t[[2]] <= divid...
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...
#Modula-2
Modula-2
MODULE EgyptianDivision; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,ReadChar;   PROCEDURE EgyptianDivision(dividend,divisor : LONGCARD; VAR remainder : LONGCARD) : LONGCARD; CONST SZ = 64; VAR powers,doublings : ARRAY[0..SZ] OF LONGCARD; answer,accumulator : LONGCARD; i : IN...
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...
#PARI.2FGP
PARI/GP
  efrac(f)=my(v=List());while(f,my(x=numerator(f),y=denominator(f));listput(v,ceil(y/x));f=(-y)%x/y/v[#v]);Vec(v); show(f)=my(n=f\1,v=efrac(f-n)); print1(f" = ["n"; "v[1]); for(i=2,#v,print1(", "v[i])); print("]"); best(n)=my(denom,denomAt,term,termAt,v); for(a=1,n-1,for(b=a+1,n, v=efrac(a/b); if(#v>term, termAt=a/b; t...
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 ...
#SNUSP
SNUSP
/==!/==atoi==@@@-@-----# | | /-\ /recurse\ #/?\ zero $>,@/>,@/?\<=zero=!\?/<=print==!\@\>?!\@/<@\.!\-/ < @ # | \=/ \=itoa=@@@+@+++++# /==\ \===?!/===-?\>>+# halve ! /+ !/+ !/+ !/+ \ mod10 #  ! @ | #>>\?-<+>/ /<+> -\!?-\!?-\!?-\!?-...
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 ...
#Raku
Raku
class Automaton { has $.rule; has @.cells; has @.code = $!rule.fmt('%08b').flip.comb».Int;   method gist { "|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" }   method succ { self.new: :$!rule, :@!code, :cells( @!code[ 4 «*« @!cells.rotate(-1)  »+«...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System Imports System.Numerics Imports System.Linq   Module Module1   ' Type Double:   Function DofactorialI(n As Integer) As Double ' Iterative DofactorialI = 1 : For i As Integer = 1 To n : DofactorialI *= i : Next End Function   ' Type Unsigned Long:   Function ULfactorialI(n As I...
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...
#PHP
PHP
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); socket_bind($socket, '127.0.0.1', 12321); socket_listen($socket);   $client_count = 0; while (true){ if (($client = socket_accept($socket)) === false) continue; $client_count++;   $client_name = 'Unknown'; socket_getpeername($client, $client_name); echo "C...
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...
#Lua
Lua
function makeInterval(s,e,p) return {start=s, end_=e, print_=p} end   function main() local intervals = { makeInterval( 2, 1000, true), makeInterval(1000, 4000, true), makeInterval( 2, 10000, false), makeInterval( 2, 1000000, false), makeInterval...
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 ...
#FutureBasic
FutureBasic
  include "Tlbx agl.incl" include "Tlbx glut.incl"   output file "Rotating Cube"   local fn AnimateCube '~'1 begin globals dim as double  sRotation end globals   // Speed of rotation sRotation += 2.9 glMatrixMode( _GLMODELVIEW )   glLoadIdentity() glTranslated( 0.0, 0.0, 0.0 ) glRotated( sRotation, -0.45, -0.8, -0.6 ) ...
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 ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
S = 10 ; M = {{7, 11, 13}, {17 , 19, 23} , {29, 31, 37}}; M + S M - S M * S M / S M ^ S   M + M M - M M * M M / M M ^ M   Gives:   ->{{17, 21, 23}, {27, 29, 33}, {39, 41, 47}} ->{{-3, 1, 3}, {7, 9, 13}, {19, 21, 27}} ->{{70, 110, 130}, {170, 190, 230}, {290, 310, 370}} ->{{7/10, 11/10, 13/10}, {17/10, 19/10, 23/10}, {2...
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#ALGOL_W
ALGOL W
begin  % draw a sphere  %  % returns the next integer larger than x or x if x is an integer  % integer procedure ceil( real value x ) ; begin integer tmp; tmp := truncate( x ); if tmp not =...
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...
#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% = 456 c.iData% = 789   PROCinsert(a{}, c{}) END   DEF PROCinsert(here{}, new{}) LOCAL temp{} : DIM temp{} = 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...
#C
C
void insert(link* anchor, link* newlink) { newlink->next = anchor->next; newlink->prev = anchor; (newlink->next)->prev = newlink; anchor->next = newlink; }
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.23
C#
static void InsertAfter(Link prev, int i) { if (prev.next != null) { prev.next.prev = new Link() { item = i, prev = prev, next = prev.next }; prev.next = prev.next.prev; } else prev.next = new Link() { item = i, prev = prev }; }
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Def...
#ALGOL_W
ALGOL W
begin  % 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 fo...
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...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program transDblList.s */ /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10S see at end of this program the instruction include */   /* Constantes */ .equ STDOUT, 1 ...
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#AWK
AWK
  BEGIN { weight[1] = "red"; weight[2] = "white"; weight[3] = "blue"; # ballnr must be >= 3. Using very high numbers here may make your computer # run out of RAM. (10 millions balls ~= 2.5GiB RAM on x86_64) ballnr = 10   srand() # Generating a random pool of balls. This python-like loop is actua...
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...
#AutoHotkey
AutoHotkey
Angle := 45 C := 0.01745329252 W := 200 H := 300 L := 400 LX := L * Cos(Angle * C), LY := L * Sin(Angle * C)   If !pToken := Gdip_Startup() { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp } OnExit, Exit   A := 50, B := 650, WinWidth := 700, WinHeight :=...
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.
#M2000_Interpreter
M2000 Interpreter
  Module DynamicVariable { input "Variable Name:", a$ a$=filter$(a$," ,+-*/^~'\({=<>})|!$&"+chr$(9)+chr$(127)) While a$ ~ "..*" {a$=mid$(a$, 2)} If len(a$)=0 then Error "No name found" If chrcode(a$)<65 then Error "Not a Valid name" Inline a$+"=1000" Print eval(a$)=1000 ...
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.
#M4
M4
Enter foo, please. define(`inp',esyscmd(`echoinp')) define(`trim',substr(inp,0,decr(len(inp)))) define(trim,42) foo
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
varname = InputString["Enter a variable name"]; varvalue = InputString["Enter a value"]; ReleaseHold[ Hold[Set["nameholder", "value"]] /. {"nameholder" -> Symbol[varname], "value" -> varvalue}]; Print[varname, " is now set to ", Symbol[varname]]
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#J
J
require 'gl2' coinsert 'jgl2' wd'pc Rosetta closeok;cc task isidraw; set task wh 320 200;pshow' glpaint glpixel 100 100 [ glpen 1 1 [ glrgb 255 0 0 [ glclear ''  
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
#Java
Java
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame;   public class DrawAPixel extends JFrame{ public DrawAPixel() { super("Red Pixel"); setSize(320, 240); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } @Override public void paint(Graphics g) { g.setColor(new Co...
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...
#Nim
Nim
import strformat   func egyptianDivision(dividend, divisor: int): tuple[quotient, remainder: int] = if dividend < 0 or divisor <= 0: raise newException(IOError, "Invalid argument(s)") if dividend < divisor: return (0, dividend)   var powersOfTwo: array[sizeof(int) * 8, int] var doublings: array[sizeof(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...
#Perl
Perl
sub egyptian_divmod { my($dividend, $divisor) = @_; die "Invalid divisor" if $divisor <= 0;   my @table = ($divisor); push @table, 2*$table[-1] while $table[-1] <= $dividend;   my $accumulator = 0; for my $k (reverse 0 .. $#table) { next unless $dividend >= $table[$k]; $accumulat...
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...
#Perl
Perl
use strict; use warnings; use bigint; sub isEgyption{ my $nr = int($_[0]); my $de = int($_[1]); if($nr == 0 or $de == 0){ #Invalid input return; } if($de % $nr == 0){ # They divide so print printf "1/" . int($de/$nr); return; } if($nr % $de == 0){ # Invalid fraction printf $nr/$de; 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 ...
#Soar
Soar
########################################## # multiply takes ^left and ^right numbers # and a ^return-to sp {multiply*elaborate*initialize (state <s> ^superstate.operator <o>) (<o> ^name multiply ^left <x> ^right <y> ^return-to <r>) --> (<s> ^name multiply ^left <x> ^righ...
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 ...
#Ruby
Ruby
class ElemCellAutomat include Enumerable   def initialize (start_str, rule, disp=false) @cur = start_str @patterns = Hash[8.times.map{|i|["%03b"%i, "01"[rule[i]]]}] puts "Rule (#{rule}) : #@patterns" if disp end   def each return to_enum unless block_given? loop do yield @cur str...
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...
#Vlang
Vlang
const max_size = 10   fn factorial_i() { mut facs := [0].repeat(max_size + 1) facs[0] = 1 println('The 0-th Factorial number is: 1') for i := 1; i <= max_size; i++ { facs[i] = i * facs[i - 1] num := facs[i] println('The $i-th Factorial number is: $num') } }   fn main() { factorial_i() }
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...
#PicoLisp
PicoLisp
(setq Port (port 12321))   (loop (setq Sock (listen Port)) # Listen (NIL (fork) (close Port)) # Accepted (close Sock) ) # Parent: Close socket and continue   # Child: (prinl (stamp) " -- (Pid " *Pid ") Client connected from " *Adr)   (in Sock (until (eof) ...
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...
#Nim
Nim
import strformat   proc iseban(n: int): bool = if n == 0: return false var b = n div 1_000_000_000 var r = n mod 1_000_000_000 var m = r div 1_000_000 r = r mod 1_000_000 var t = r div 1_000 r = r mod 1_000 m = if m in 30..66: m mod 10 else: m t = if t in 30..66: t mod 10 else: t r = if r in 30....
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...
#Perl
Perl
use strict; use warnings; use feature 'say'; use Lingua::EN::Numbers qw(num2en);   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   sub e_ban { my($power) = @_; my @n; for (1..10**$power) { next unless 0 == $_%2; next if $_ =~ /[789]/ or /[12].$/ or /[135]..$/ or /[135...