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 a n n n n -- n c-function sdl-drawpoint SDL_RenderDrawPoint a n n -- n c-function sdl-renderpresent SDL_RenderPresent a -- void c-function sdl-delay SDL_Delay n -- void   : pixel ( -- ) $20 sdl-init drop s\" Rosetta Task : Draw a pixel\x0" drop 0 0 320 240 $0 sdl-createwindow ( window ) -1 $2 sdl-createrenderer   dup ( renderer ) 255 0 0 255 sdl-setdrawcolor drop dup ( renderer ) 100 100 sdl-drawpoint drop ( renderer ) sdl-renderpresent   5000 sdl-delay sdl-quit ;   pixel
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#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 = 100, y = 100   ' what is color depth ScreenInfo ,,depth   If depth = 8 Then PSet(x, y), 40 ' palette, index 40 = RGB(255, 0, 0) Else PSet(x, y), RGB(255, 0, 0) ' red End If   ' empty keyboard buffer While Inkey <> "" : Wend WindowTitle IIf(depth = 8, "Palette","True Color") + ", hit any key to end program" Sleep End
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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], [i + i, x + x] ]); const collapse = ([i, x], [q, r]) => x < r ? ( [q + i, r - x] ) : [q, r]; return foldr( collapse, [0, m], unfoldr(expansion, [1, n]) ); };   // TEST ---------------------------------------------   // main :: IO () const main = () => showLog( eqyptianQuotRem(580, 34) ); // -> [17, 2]       // GENERIC FUNCTIONS --------------------------------   // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x });   // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, });   // flip :: (a -> b -> c) -> b -> a -> c const flip = f => 1 < f.length ? ( (a, b) => f(b, a) ) : (x => y => f(y)(x));     // foldr :: (a -> b -> b) -> b -> [a] -> b const foldr = (f, a, xs) => xs.reduceRight(flip(f), a);     // unfoldr :: (b -> Maybe (a, b)) -> b -> [a] const unfoldr = (f, v) => { let xr = [v, v], xs = []; while (true) { const mb = f(xr[1]); if (mb.Nothing) { return xs } else { xr = mb.Just; xs.push(xr[0]) } } };   // showLog :: a -> IO () const showLog = (...args) => console.log( args .map(JSON.stringify) .join(' -> ') );   // MAIN --- return main(); })();
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#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]], InputForm], "[" <> ToString[Length[l]] <> "]"]], " + "] <> " = " <> ToString[Numerator[Total[f]]] <> "/" <> ToString[Denominator[Total[f]]]; Print[disp[frac[43/48]]]; Print[disp[frac[5/121]]]; Print[disp[frac[2014/59]]]; fracs = Flatten[Table[frac[p/q], {q, 99}, {p, q}], 1]; Print[disp[MaximalBy[fracs, Length@*Union][[1]]]]; Print[disp[MaximalBy[fracs, Denominator@*Last][[1]]]]; fracs = Flatten[Table[frac[p/q], {q, 999}, {p, q}], 1]; Print[disp[MaximalBy[fracs, Length@*Union][[1]]]]; Print[disp[MaximalBy[fracs, Denominator@*Last][[1]]]];
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#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 bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#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 Lst) D (dictionary N)) (do 10 (prinl Lst) (setq Lst (make (map '((L) (let Y (head 3 L) (and (cddr Y) (link (if (member Y D) "#" ".")) ) ) ) (conc (cons (last Lst)) Lst (cons (car Lst))) ) ) ) ) ) ) (cellular ".........#........." 90 )
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#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_rules(In, Out) :- apply1st(In, First), Out = [First|_], apply(In, First, First, Out).   apply1st([A,B|T], A1) :- last([A,B|T], Last), r(Last,A,B,A1). apply([A,B], Prev, First, [Prev, This]) :- r(A,B,First,This). apply([A,B,C|T], Prev, First, [Prev,This|Rest]) :- r(A,B,C,This), apply([B,C|T], This, First, [This|Rest]).   writ(0) :- write('.'). writ(1) :- write(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 iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#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); -- set and reset N : IN STD_LOGIC_VECTOR(Nbin-1 DOWNTO 0) ; -- max number Fn : OUT STD_LOGIC_VECTOR(Nbou-1 DOWNTO 0)); -- factorial of "n"   END Factorial ;   ARCHITECTURE Behavior OF Factorial IS ---------------------- Program Multiplication -------------------------------- FUNCTION Mult ( CONSTANT MFa : IN UNSIGNED ; CONSTANT MI : IN UNSIGNED ) RETURN UNSIGNED IS VARIABLE Z : UNSIGNED(MFa'RANGE) ; VARIABLE U : UNSIGNED(MI'RANGE) ; BEGIN Z := TO_UNSIGNED(0, MFa'LENGTH) ; -- to obtain the multiplication U := MI ; -- regressive counter LOOP Z := Z + MFa ; -- make multiplication U := U - 1 ; EXIT WHEN U = 0 ; END LOOP ; RETURN Z ; END Mult ; -------------------Program Factorial --------------------------------------- FUNCTION Fact (CONSTANT Nx : IN NATURAL ) RETURN UNSIGNED IS VARIABLE C : NATURAL RANGE 0 TO 2**Nbin-1 ; VARIABLE I : UNSIGNED(Nbin-1 DOWNTO 0) ; VARIABLE Fa : UNSIGNED(Nbou-1 DOWNTO 0) ; BEGIN C := 0 ; -- counter I := TO_UNSIGNED(1, Nbin) ; Fa := TO_UNSIGNED(1, Nbou) ; LOOP EXIT WHEN C = Nx ; -- end loop C := C + 1 ; -- progressive couter Fa := Mult (Fa , I ); -- call function to make a multiplication I := I + 1 ; -- END LOOP ; RETURN Fa ; END Fact ; --------------------- Program TO Call Factorial Function ------------------------------------------------------ TYPE Table IS ARRAY (0 TO 2**Nbin-1) OF UNSIGNED(Nbou-1 DOWNTO 0) ; FUNCTION Call_Fact RETURN Table IS VARIABLE Fc : Table ; BEGIN FOR c IN 0 TO 2**Nbin-1 LOOP Fc(c) := Fact(c) ; END LOOP ; RETURN Fc ; END FUNCTION Call_Fact;   CONSTANT Result : Table := Call_Fact ; ------------------------------------------------------------------------------------------------------------ SIGNAL Nin : STD_LOGIC_VECTOR(N'RANGE) ; BEGIN -- start of architecture     Nin <= N WHEN RISING_EDGE(clk) AND sr = "10" ELSE (OTHERS => '0') WHEN RISING_EDGE(clk) AND sr = "01" ELSE UNAFFECTED;   Fn <= STD_LOGIC_VECTOR(Result(TO_INTEGER(UNSIGNED(Nin)))) WHEN RISING_EDGE(clk) ;   END Behavior ;
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#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 {ServerSocket bind(takePort:12321)} {System.showInfo "Socket bound."}   {ServerSocket listen} {System.showInfo "Started listening."}   for do ClientHost ClientPort ClientSocket = {ServerSocket accept(accepted:$ acceptClass:TextSocket host:?ClientHost port:?ClientPort )} in {System.showInfo "Connection accepted from "#ClientHost#":"#ClientPort#"."} thread {Echo ClientSocket}   {System.showInfo "Connection lost: "#ClientHost#":"#ClientPort#"."} {ClientSocket close} end end
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 billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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) { List<Range> rgs = List.of( new Range(2, 1000, true), new Range(1000, 4000, true), new Range(2, 10_000, false), new Range(2, 100_000, false), new Range(2, 1_000_000, false), new Range(2, 10_000_000, false), new Range(2, 100_000_000, false), new Range(2, 1_000_000_000, false) ); for (Range rg : rgs) { if (rg.start == 2) { System.out.printf("eban numbers up to and including %d\n", rg.end); } else { System.out.printf("eban numbers between %d and %d\n", rg.start, rg.end); } int count = 0; for (int i = rg.start; i <= rg.end; ++i) { int b = i / 1_000_000_000; int r = i % 1_000_000_000; int m = r / 1_000_000; r = i % 1_000_000; int t = r / 1_000; r %= 1_000; if (m >= 30 && m <= 66) m %= 10; if (t >= 30 && t <= 66) t %= 10; if (r >= 30 && r <= 66) r %= 10; if (b == 0 || b == 2 || b == 4 || b == 6) { if (m == 0 || m == 2 || m == 4 || m == 6) { if (t == 0 || t == 2 || t == 4 || t == 6) { if (r == 0 || r == 2 || r == 4 || r == 6) { if (rg.print) System.out.printf("%d ", i); count++; } } } } } if (rg.print) { System.out.println(); } System.out.printf("count = %d\n\n", count); } } }
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#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 { Public declarations } end;   var Form1: TForm1; nodes: TArray<TArray<double>> = [[-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1], [1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1]]; edges: TArray<TArray<Integer>> = [[0, 1], [1, 3], [3, 2], [2, 0], [4, 5], [5, 7], [7, 6], [6, 4], [0, 4], [1, 5], [2, 6], [3, 7]];   implementation   {$R *.dfm}   procedure Scale(factor: TArray<double>); begin if Length(factor) <> 3 then exit; for var i := 0 to High(nodes) do for var f := 0 to High(factor) do nodes[i][f] := nodes[i][f] * factor[f]; end;   procedure RotateCuboid(angleX, angleY: double); begin var sinX := sin(angleX); var cosX := cos(angleX); var sinY := sin(angleY); var cosY := cos(angleY);   for var i := 0 to High(nodes) do begin var x := nodes[i][0]; var y := nodes[i][1]; var z := nodes[i][2];   nodes[i][0] := x * cosX - z * sinX; nodes[i][2] := z * cosX + x * sinX;   z := nodes[i][2];   nodes[i][1] := y * cosY - z * sinY; nodes[i][2] := z * cosY + y * sinY; end; end;   function DrawCuboid(x, y, w, h: Integer): TBitmap; var offset: TPoint; begin Result := TBitmap.Create; Result.SetSize(w, h); rotateCuboid(PI / 180, 0); offset := TPoint.Create(x, y); with Result.canvas do begin Brush.Color := clBlack; Pen.Color := clWhite;   Lock; FillRect(ClipRect);   for var edge in edges do begin var p1 := (nodes[edge[0]]); var p2 := (nodes[edge[1]]); moveTo(trunc(p1[0]) + offset.x, trunc(p1[1]) + offset.y); lineTo(trunc(p2[0]) + offset.x, trunc(p2[1]) + offset.y); end; Unlock; end; end;   procedure TForm1.FormCreate(Sender: TObject); begin ClientHeight := 360; ClientWidth := 640; DoubleBuffered := true; scale([100, 100, 100]); rotateCuboid(PI / 4, ArcTan(sqrt(2))); end;   procedure TForm1.tmr1Timer(Sender: TObject); var buffer: TBitmap; begin buffer := DrawCuboid(ClientWidth div 2, ClientHeight div 2, ClientWidth, ClientHeight); Canvas.Draw(0, 0, buffer); buffer.Free; end;   end.
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#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 + 0.5 I x * x + y * y <= r * r V vec = normalize((x, y, sqrt(r * r - x * x - y * y))) V b = dotp(light, vec) ^ k + ambient V intensity = Int((1 - b) * (:shades.len - 1)) line ‘’= I intensity C 0 .< :shades.len {:shades[intensity]} E :shades[0] E line ‘’= ‘ ’   print(line)   V light = normalize((30.0, 30.0, -50.0)) draw_sphere(20, 4, 0.1, light) draw_sphere(10, 2, 0.4, 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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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 : script "Custom Iterative Ternary Merge Sort"   on DutchNationalFlagProblem(numberOfBalls) -- A local "owner" for the potentially long 'balls' list. Speeds up references to its items and properties. script o property colours : {"red", "white", "blue"} -- Initialise the balls list with at least one instance of each colour — but not in Dutch flag order! property balls : reverse of my colours end script   -- Randomly fill the list from the three colours to the required number of balls (min = 3). -- The task description doesn't say if there should be equal numbers of each colour, but it makes no difference to the solution. repeat numberOfBalls - 3 times set end of o's balls to some item of o's colours end repeat log o's balls -- Log the pre-sort order.   -- Custom comparer for the sort. Decides whether or not ball 'a' should go after ball 'b'. script redsThenWhitesThenBlues on isGreater(a, b) return ((a is not equal to b) and ((a is "blue") or (b is "red"))) end isGreater end script -- Sort items 1 thru -1 of the balls (ie. the whole list) using the above comparer. tell sorter to sort(o's balls, 1, -1, {comparer:redsThenWhitesThenBlues})   -- Return the sorted list. return o's balls end DutchNationalFlagProblem   DutchNationalFlagProblem(100)
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#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*dsize) OD FOR i=1 TO d DO Plot(x+i*dsize,y-i*dsize) DrawTo(x+w*wsize+i*dsize,y-i*dsize) DrawTo(x+w*wsize+i*dsize,y+h*hsize-i*dsize) OD RETURN   PROC Main() BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6   Graphics(8+16) COLOR1=$0C COLOR2=$02 Color=1   DrawCuboid(60,45,2,3,4) DrawCuboid(130,40,2,4,3) DrawCuboid(205,50,3,2,4) DrawCuboid(55,120,3,4,2) DrawCuboid(120,130,4,2,3) DrawCuboid(200,125,4,3,2)   DO UNTIL CH#$FF OD CH=$FF RETURN
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 println("OK, enter the variable names and their values, below") do { println("\n Variable $i") print(" Name  : ") name = readLine()!! if (map.containsKey(name)) { println(" Sorry, you've already created a variable of that name, try again") continue } print(" Value : ") value = readLine()!!.toInt() map.put(name, value) i++ } while (i <= n)   println("\nEnter q to quit") var v: Int? while (true) { print("\nWhich variable do you want to inspect : ") name = readLine()!! if (name.toLowerCase() == "q") return v = map[name] if (v == null) println("Sorry there's no variable of that name, try again") else println("It's value is $v") } }
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 a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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 = 0 for i in ind:-1:0 if acc + doublings[i+1] ≤ dividend acc += doublings[i+1] ans += powers[i+1] end end   return ans, dividend - acc end   q, r = egyptiandivision(580, 34) println("580 ÷ 34 = $q (remains $r)")   using Base.Test   @testset "Equivalence to divrem builtin function" begin for x in rand(1:100, 100), y in rand(1:100, 10) @test egyptiandivision(x, y) == divrem(x, y) end end
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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) var doubling = divisor while (true) { doubling *= 2 if (doubling > dividend) break powersOfTwo.add(powersOfTwo[powersOfTwo.lastIndex] * 2) doublings.add(doubling) } var answer = 0 var accumulator = 0 for (i in doublings.size - 1 downTo 0) { if (accumulator + doublings[i] <= dividend) { accumulator += doublings[i] answer += powersOfTwo[i] if (accumulator == dividend) break } } return DivMod(answer, dividend - accumulator) }   fun main(args: Array<String>) { val dividend = 580 val divisor = 34 val (quotient, remainder) = egyptianDivide(dividend, divisor) println("$dividend divided by $divisor is $quotient with remainder $remainder") }
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#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=y*k If i=1 Then tt=tt+"+1/"+j EndIf 'n=gcd(i,j) x=i y=j gcd() n=ret x=i/n y=j/n EndWhile EndIf TextWindow.WriteLine(xx+"/"+yy+"="+Text.GetSubTextToEnd(tt,2))   Sub modulo wr=Math.Remainder(u,v) While wr<0 wr=wr+v EndWhile ret=wr EndSub   Sub gcd wx=i wy=j wr=1 While wr<>0 wr=Math.Remainder(wx,wy) wx=wy wy=wr EndWhile ret=wx EndSub
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#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 }) displayNl ]. result := 0. [ multiplier >= 1 ] whileTrue: [ multiplier even ifFalse: [ result := result + multiplicand. tutor ifTrue: [ ('%1, %2 kept' % { multiplier. multiplicand }) displayNl ] ] ifTrue: [ tutor ifTrue: [ ('%1, %2 struck' % { multiplier. multiplicand }) displayNl ] ]. multiplier := multiplier halve. multiplicand := multiplicand double. ]. ^result ] ethiopianMultiplyBy: aNumber [ ^ self ethiopianMultiplyBy: aNumber withTutor: false ] ].
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#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[c[i-1:i+2]] for i in range(1,lencells+1)), '0']) yield c[1:-1]   if __name__ == '__main__': lines, start, rules = 50, '0000000001000000000', (90, 30, 122) zipped = [range(lines)] + [eca(start, rule) for rule in rules] print('\n Rules: %r' % (rules,)) for data in zip(*zipped): i = data[0] cells = data[1:] print('%2i: %s' % (i, ' '.join(cells).replace('0', '.').replace('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 iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#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 localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#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 Reuse => 1, ) or die "socket: $!"; # no newline, so perl appends stuff   $SIG{CHLD} = 'IGNORE' if $use_fork; # let perl deal with zombies   print "listening...\n"; while (1) { # declare $con 'my' so it's closed by parent every loop my $con = $sock->accept() or die "accept: $!"; fork and next if $use_fork; # following are for child only   print "incoming..\n"; print $con $_ while(<$con>); # read each line and write back print "done\n";   last if $use_fork; # if not forking, loop }   # child will reach here and close its copy of $sock before exit
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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 "eban numbers up to and including \($rg[1]):" else "eban numbers between \($rg[0]) and \($rg[1]) (inclusive):" end, ( foreach (range( $rg[0]; 1 + $rg[1]; 2), null) as $i ( { count: 0 }; .emit = false | if $i == null then .total = .count else quotient($i; 1e9; .b; .r) | quotient(.r; 1e6; .m; .r) | quotient(.r; 1e3; .t; .r) | update(.m) | update(.t) | update(.r) | if all(.b, .m, .t, .r; IN(0, 2, 4, 6)) then .count += 1 | if ($rg[2]) then .emit=$i else . end else . end end; if .emit then .emit else empty end, if .total then "count = \(.count)\n" else empty end) );   task
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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:") println(join(filter(iseban, 1:100), ", "))   println("eban numbers between 1000 and 4000 (inclusive):") println(join(filter(iseban, 1000:4000), ", "))   println("eban numbers up to and including 10000: ", count(iseban, 1:10000)) println("eban numbers up to and including 100000: ", count(iseban, 1:100000)) println("eban numbers up to and including 1000000: ", count(iseban, 1:1000000)) println("eban numbers up to and including 10000000: ", count(iseban, 1:10000000)) println("eban numbers up to and including 100000000: ", count(iseban, 1:100000000)) println("eban numbers up to and including 1000000000: ", count(iseban, 1:1000000000))  
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#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 . . . func rotate angx angy . . sinx = sin angx cosx = cos angx siny = sin angy cosy = cos angy for i range len node[][] x = node[i][0] z = node[i][2] node[i][0] = x * cosx - z * sinx y = node[i][1] z = z * cosx + x * sinx node[i][1] = y * cosy - z * siny node[i][2] = z * cosy + y * siny . . len nd[] 3 func draw . . clear m = 999 mi = -1 for i range len node[][] if node[i][2] < m m = node[i][2] mi = i . . ix = 0 for i range len edge[][] if edge[i][0] = mi nd[ix] = edge[i][1] ix += 1 elif edge[i][1] = mi nd[ix] = edge[i][0] ix += 1 . . for ni range len nd[] for i range len edge[][] if edge[i][0] = nd[ni] or edge[i][1] = nd[ni] x1 = node[edge[i][0]][0] y1 = node[edge[i][0]][1] x2 = node[edge[i][1]][0] y2 = node[edge[i][1]][1] move x1 + 50 y1 + 50 line x2 + 50 y2 + 50 . . . . call scale 25 call rotate 45 atan sqrt 2 call draw on animate call rotate 1 0 call draw .
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#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 961 1369)  
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#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) { DoubleArray(this[0].size) } for (i in 0 until this.size) { for (j in 0 until this[0].size) result[i][j] = this[i][j].op(other[i][j]) } return result }   fun Matrix.elementwiseOp(d: Double, op: Op): Matrix { val result = Array(this.size) { DoubleArray(this[0].size) } for (i in 0 until this.size) { for (j in 0 until this[0].size) result[i][j] = this[i][j].op(d) } return result }   fun Matrix.print(name: Char?, scalar: Boolean? = false) { println(when (scalar) { true -> "m $name s" false -> "m $name m" else -> "m" } + ":") for (i in 0 until this.size) println(this[i].asList()) println() }   fun main(args: Array<String>) { val ops = listOf(Double::plus, Double::minus, Double::times, Double::div, Double::dPow) val names = "+-*/^" val m = arrayOf( doubleArrayOf(3.0, 5.0, 7.0), doubleArrayOf(1.0, 2.0, 3.0), doubleArrayOf(2.0, 4.0, 6.0) ) m.print(null, null) for ((i, op) in ops.withIndex()) m.elementwiseOp(m, op).print(names[i]) val s = 2.0 println("s = $s:\n") for ((i, op) in ops.withIndex()) m.elementwiseOp(s, op).print(names[i], true) }
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#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 251 252 253 254 254 255 255 255 256 256 256 256]   INT FUNC Sin(INT a) WHILE a<0 DO a==+360 OD WHILE a>360 DO a==-360 OD IF a<=90 THEN RETURN (SinTab(a)) ELSEIF a<=180 THEN RETURN (SinTab(180-a)) ELSEIF a<=270 THEN RETURN (-SinTab(a-180)) ELSE RETURN (-SinTab(360-a)) FI RETURN (0)   INT FUNC Cos(INT a) RETURN (Sin(a-90))   PROC Ellipse(INT x0,y0,rx,ry) INT i CARD x BYTE y   x=x0+rx*Sin(0)/256 y=y0+ry*Cos(0)/256 Plot(x,y) FOR i=5 TO 360 STEP 5 DO x=x0+rx*Sin(i)/256 y=y0+ry*Cos(i)/256 DrawTo(x,y) OD RETURN   PROC Main() BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6 INT cx=[160],cy=[96],r=[90],r2 BYTE i   Graphics(8+16) COLOR1=$0C COLOR2=$02 Color=1   Ellipse(cx,cy,r,r) FOR i=10 TO 90 STEP 10 DO r2=r*Cos(i)/256 Ellipse(cx,cy,r,r2) Ellipse(cx,cy,r2,r) OD   DO UNTIL CH#$FF OD CH=$FF 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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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; end Insert;
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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: ( # DOWN do link OF splice OF self; to make thread safe # REF LINK next = next OF prev; HEAP LINK new link := LINK(prev, next, new data); next OF prev := prev OF next := new link; # UP do link OF splice OF self; # new link );   PROC insert before = (REF LINK #self,# next, DATA new data)LINK: insert after(#self,# prev OF next, new data);   # END rosettacode task specimen code #   # Test case: # MODE DATA = STRUCT(INT year elected, STRING name); FORMAT data fmt = $dddd": "g"; "$;   test:(   # manually initialise the back splices # LINK presidential splice; presidential splice := (presidential splice, presidential splice, SKIP);   # manually build the chain # LINK previous, incumbent, elect; previous := (presidential splice, incumbent, DATA(1993, "Clinton")); incumbent:= (previous, elect, DATA(2001, "Bush" )); elect := (incumbent, presidential splice, DATA(2008, "Obama" ));   insert after(incumbent, LOC DATA := DATA(2004, "Cheney"));   REF LINK node := previous; WHILE REF LINK(node) ISNT presidential splice DO printf((data fmt, value OF node)); node := next OF node OD; print(new line) )
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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 250 PRINT SPC( S)C$(B%(N)); 260 LET S = 1 270 RETURN
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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)","White"),"(3)","Blue")
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#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 + Depth + 3) := (others => (others => ' ')); begin -- points Result (1, 1)  := '+'; Result (Height + 2, 1)  := '+'; Result (1, 2 * Width + 2)  := '+'; Result (Height + 2, 2 * Width + 2)  := '+'; Result (Height + Depth + 3, Depth + 2)  := '+'; Result (Depth + 2, 2 * Width + Depth + 3)  := '+'; Result (Height + Depth + 3, 2 * Width + Depth + 3) := '+'; -- width lines for I in 1 .. 2 * Width loop Result (1, I + 1)  := '-'; Result (Height + 2, I + 1)  := '-'; Result (Height + Depth + 3, Depth + I + 2) := '-'; end loop; -- height lines for I in 1 .. Height loop Result (I + 1, 1)  := '|'; Result (I + 1, 2 * Width + 2)  := '|'; Result (Depth + I + 2, 2 * Width + Depth + 3) := '|'; end loop; -- depth lines for I in 1 .. Depth loop Result (Height + 2 + I, 1 + I)  := '/'; Result (1 + I, 2 * Width + 2 + I)  := '/'; Result (Height + 2 + I, 2 * Width + 2 + I) := '/'; end loop; return Result; end Create_Cuboid;   procedure Print_Cuboid (Width, Height, Depth : Positive) is Cuboid : Char_Matrix := Create_Cuboid (Width, Height, Depth); begin for Row in reverse Cuboid'Range (1) loop for Col in Cuboid'Range (2) loop Ada.Text_IO.Put (Cuboid (Row, Col)); end loop; Ada.Text_IO.New_Line; end loop; end Print_Cuboid; begin Print_Cuboid (2, 3, 4); end Main;
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 runtime like this: obj[varName] = 23 -- or obj.setProp(varName, 23)
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)   // Set color of pixel at (100, 100) to red red := color.RGBA{255, 0, 0, 255} img.Set(100, 100, red)   // Check it worked. cmap := map[color.Color]string{green: "green", red: "red"} c1 := img.At(0, 0) c2 := img.At(100, 100) fmt.Println("The color of the pixel at ( 0, 0) is", cmap[c1], "\b.") fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.") }
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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 accum = accum + dbls[i] ans = ans + pwrs[i] end end   return ans, math.abs(accum - dividend) end   local i, j = 580, 34 local d, m = egyptian_divmod(i, j) print(i.." divided by "..j.." using the Egyptian method is "..d.." remainder "..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 is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#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.num) let rquo = newRat(1, iquo) result = fracs & rquo let num2 = cmod(-rat.denom, rat.num) if num2 < Zero: num2 += rat.num let denom2 = rat.denom * iquo let f = newRat(num2, denom2) if f.num == One: result.add(f) else: result = f.toEgyptianrecursive(result)   #---------------------------------------------------------------------------------------------------   proc toEgyptian(rat: Rat): seq[Rat] =   if rat.num.isZero: return @[rat]   if abs(rat.num) >= rat.denom: let iquo = rat.num div rat.denom let rquo = newRat(iquo, 1) let rrem = rat - rquo result = rrem.toEgyptianrecursive(@[rquo]) else: result = rat.toEgyptianrecursive(@[])   #———————————————————————————————————————————————————————————————————————————————————————————————————   for frac in [newRat(43, 48), newRat(5, 121), newRat(2014, 59)]: let list = frac.toEgyptian() if list[0].denom == One: let first = fmt"[{list[0].num}]" let rest = list[1..^1].join(" + ") echo fmt"{frac} -> {first} + {rest}" else: let all = list.join(" + ") echo fmt"{frac} -> {all}"   for r in [98, 998]: if r == 98: echo "\nFor proper fractions with 1 or 2 digits:" else: echo "\nFor proper fractions with 1, 2 or 3 digits:"   var maxSize = 0 var maxSizeFracs: seq[Rat] var maxDen = Zero var maxDenFracs: seq[Rat] var sieve = newSeq[seq[bool]](r + 1) # To eliminate duplicates.   for item in sieve.mitems: item.setLen(r + 2) for i in 1..r: for j in (i + 1)..(r + 1): if sieve[i][j]: continue   let f = newRat(i, j) let list = f.toEgyptian() let listSize = list.len if listSize > maxSize: maxSize = listSize maxSizeFracs.setLen(0) maxSizeFracs.add(f) elif listSize == maxSize: maxSizeFracs.add(f)   let listDen = list[^1].denom() if listDen > maxDen: maxDen = listDen maxDenFracs.setLen(0) maxDenFracs.add(f) elif listDen == maxDen: maxDenFracs.add(f)   if i < r div 2: var k = 2 while j * k <= r + 1: sieve[i * k][j * k] = true inc k   echo fmt" largest number of items = {maxSize}" echo fmt" fraction(s) with this number : {maxSizeFracs.join("", "")}" let md = $maxDen echo fmt" largest denominator = {md.len} digits, {md[0..19]}...{md[^20..^1]}" echo fmt" fraction(s) with this denominator : {maxDenFracs.join("", "")}"
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#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) r = trim(input) s = 0 next s = odd(l) s + r r = double(r) l = halve(l) :s(next) stop output = s end
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#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 swap 1 >> ] drop swap dup size swap 0 swap reverse witheach [ char # = dip [ 1 << ] + ] ] is make-ca ( $ n --> R S C )   [ $ "" unrot swap times [ dup 1 & iff [ char # ] else [ char . ] rot join swap 1 >> ] drop echo$ cr ] is echo-ca ( S C --> )   [ dip bit 2dup 1 & iff | else drop 1 << swap over & 0 != | ] is wrap ( S C --> C )   [ rot temp put dip dup 0 unrot wrap rot times [ dup 7 & temp share swap peek if [ i^ bit rot | swap ] 1 >> ] drop temp release ] is next-ca ( R S C --> C )   [ dip [ over echo$ cr make-ca ] 1 - times [ dip 2dup next-ca 2dup echo-ca ] 2drop drop ] is generations ( $ n n --> )   say "Rule 30, 50 generations:" cr cr   $ ".........#........." 30 50 generations
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#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)) (define 2^u-b-1 (fxlshift 1 usable-bits/fixnum-1)) (define (fxior3 a b c) (fxior (fxior a b) c)) (define (if-bit-set n i [result 1]) (if (bitwise-bit-set? n i) result 0))   (define (shift-right-1-bit-with-lsb-L L n) (fxior (if-bit-set L 0 2^u-b-1) (fxrshift n 1)))   (define (shift-left-1-bit-with-msb-R n R) (fxior (fxand usable-bits/mask (fxlshift n 1)) (if-bit-set R usable-bits/fixnum-1)))   (define ((CA-next-bit-state rule) L n R) (for/fold ([n+ 0]) ([b (in-range usable-bits/fixnum-1 -1 -1)]) (define rule-bit (fxior3 (if-bit-set (shift-right-1-bit-with-lsb-L L n) b 4) (if-bit-set n b 2) (if-bit-set (shift-left-1-bit-with-msb-R n R) b))) (fxior (fxlshift n+ 1) (if-bit-set rule rule-bit))))   ;; CA-next-generation generates a function which takes: ;; v-in  : an fxvector representing the CA's current state as a bit field. This may be mutated ;; offset : the offset of the leftmost element of v-in; this is used in infinite CA to allow the CA ;; to occupy negative indices ;; wrap-rule : provided for automata that are not an integer number of usable-bits/fixnum bits wide ;; wrap-rule = #f - v-in and offset are unchanged ;; wrap-rule : (v-in vl-1 offset) -> (values v-out vl-1+ offset-) ;; v-in as passed into CA-next-generation ;; vl-1=(sub1 (length v-in)), since its precomputed vaule is needed ;; offset as passed into CA-next-generation ;; v-out: either a new copy of v-in, or v-in itself (which might be mutated) ;; vl-1+: (sub1 (length v-out)) ;; offset- : a new value for offset (it will have decreased since the CA grows to the left ;; with offset, and to the right with (length v-out) (define (CA-next-generation rule #:wrap-rule (wrap-rule values)) (define next-state (CA-next-bit-state rule)) (lambda (v-in offset) (define vl-1 (fx- (fxvector-length v-in) 1)) (define-values [v+ v+l-1 offset-] (wrap-rule v-in vl-1 offset)) (define rv (for/fxvector ([l (in-sequences (in-value (fxvector-ref v+ v+l-1)) (in-fxvector v+))] [n (in-fxvector v+)] [r (in-sequences (in-fxvector v+ 1) (in-value (fxvector-ref v+ 0)))]) (next-state l n r))) (values rv offset-)))   ;; CA-next-generation with the default (non) wrap rule wraps the MSB of the left-hand word (L) and the ;; LSB of the right-hand word (R) in the CA. If the CA is not a multiple of usable-bits/fixnum wide, ;; then we use this function to put these bits where they can be used... i.e. the actual MSB is copied ;; to the word's MSB and the LSB is copied to the bit that is to the left of the actual MSB. (define (wrap-rule-truncate-left-word sig-bits) (define wlb-mask (fx- (fxlshift 1 sig-bits) 1)) (unless (fx< sig-bits (fx- usable-bits/fixnum 1)) (error "we need at least 2 bits in the top of the word to do this safely")) (lambda (v-in vl-1 offset) (define v0 (fxvector-ref v-in 0))  ;; this must wrap to wlb of the first word (define last-bit (fxlshift (fxand 1 (fxvector-ref v-in vl-1)) sig-bits))  ;; this must wrap to the extreme left of the first word (define first-bit (if-bit-set v0 (fx- sig-bits 1) 2^u-b-1)) (fxvector-set! v-in 0 (fxior3 last-bit first-bit (fxand v0 wlb-mask))) (values v-in vl-1 offset)))   ;; This displays a state of the CA (define (show-automaton v #:step (step #f) #:sig-bits (sig-bits #f) #:push-right (push-right #f)) (when step (printf "[~a] " (~a #:align 'right #:width 10 step))) (when push-right (display (make-string (* usable-bits/fixnum push-right) #\.))) (when (number? sig-bits) (display (~a #:width sig-bits #:align 'right #:pad-string "0" (number->string (fxvector-ref v 0) 2)))) (for ([n (in-fxvector v (if sig-bits 1 0))]) (display (~a #:width usable-bits/fixnum #:align 'right #:pad-string "0" (number->string n 2)))))   (module+ main (define ng/122/19-bits (CA-next-generation 122 #:wrap-rule (wrap-rule-truncate-left-word 19))) (for/fold ([v (fxvector #b1000000000)] [o 0]) ([step (in-range 40)]) (show-automaton v #:step step #:sig-bits 19) (newline) (ng/122/19-bits v o)))
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#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 Then FactRec = 1# Else FactRec = n * FactRec(n - 1) End If End Function 'FactRec Private Function FactIter(n As Variant) Dim i As Variant, f As Variant f = 1# For i = 1# To CDec(n) f = f * i Next i FactIter = f End Function 'FactIter
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#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 if first then bytes_sent = send(sockd, s) -- partial echo, see note first = false end if buffer &= s if s[$]='\n' then bytes_sent = send(sockd, buffer) buffer = "" end if end while ?{"socket disconnected",sockd} end procedure atom list_s = socket(AF_INET,SOCK_STREAM,NULL), pSockAddr = sockaddr_in(AF_INET, "", 12321) if list_s<0 then ?9/0 end if if bind(list_s, pSockAddr)=SOCKET_ERROR then crash("bind (%v)",{get_socket_error()}) end if if listen(list_s,100)=SOCKET_ERROR then crash("listen (%v)",{get_socket_error()}) end if puts(1,"echo server started, press escape or q to exit\n") while not find(get_key(),{ESCAPE,'q','Q'}) do {integer code} = select({list_s},{},{},250000) -- (0.25s) if code=SOCKET_ERROR then crash("select (%v)",{get_socket_error()}) end if if code>0 then -- (not timeout) atom conn_s = accept(list_s) if conn_s=SOCKET_ERROR then ?9/0 end if atom hThread = create_thread(echo,{conn_s}) end if end while list_s = closesocket(list_s) WSACleanup()
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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), Range(2, 100_000_000, false), Range(2, 1_000_000_000, false) ) for (rg in rgs) { val (start, end, prnt) = rg if (start == 2) { println("eban numbers up to and including $end:") } else { println("eban numbers between $start and $end (inclusive):") } var count = 0 for (i in start..end step 2) { val b = i / 1_000_000_000 var r = i % 1_000_000_000 var m = r / 1_000_000 r = i % 1_000_000 var t = r / 1_000 r %= 1_000 if (m >= 30 && m <= 66) m %= 10 if (t >= 30 && t <= 66) t %= 10 if (r >= 30 && r <= 66) r %= 10 if (b == 0 || b == 2 || b == 4 || b == 6) { if (m == 0 || m == 2 || m == 4 || m == 6) { if (t == 0 || t == 2 || t == 4 || t == 6) { if (r == 0 || r == 2 || r == 4 || r == 6) { if (prnt) print("$i ") count++ } } } } } if (prnt) println() println("count = $count\n") } }
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#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*PI/2, 11*PI/6, PI/2, 7*PI/6}   sub drawcube( x() as double, colour as uinteger ) for i as uinteger = 0 to 2 line (SIZE/2, SIZE/2-SCALE/zoff) - (x(i), SIZE/2-SCALE*zoff), colour line (SIZE/2, SIZE/2+SCALE/zoff) - (x(5-i), SIZE/2+SCALE*zoff), colour line ( x(i), SIZE/2-SCALE*zoff ) - ( x(i mod 3 + 3), SIZE/2+SCALE*zoff ), colour line ( x(i), SIZE/2-SCALE*zoff ) - ( x((i+1) mod 3 + 3), SIZE/2+SCALE*zoff ), colour next i end sub   while inkey="" lasttime = timer for i as uinteger = 0 to 5 x(i) = SIZE/2 + SCALE*cylr*cos(cylphi(i)+theta) next i drawcube x(), 15   while timer < lasttime + dt wend theta += dtheta*(timer-lasttime) drawcube x(),0 wend end
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#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; Cr  : Cairo_Context; Pat  : Cairo_Pattern; Status_Out : Cairo_Status; M_Pi  : constant Dub := Dub (Ada.Numerics.Pi);   begin Surface := Create (Cairo_Format_ARGB32, 512, 512); Cr  := Create (Surface); Pat  := Cairo.Pattern.Create_Radial (230.4, 204.8, 51.1, 204.8, 204.8, 256.0); Cairo.Pattern.Add_Color_Stop_Rgba (Pat, 0.0, 1.0, 1.0, 1.0, 1.0); Cairo.Pattern.Add_Color_Stop_Rgba (Pat, 1.0, 0.0, 0.0, 0.0, 1.0); Cairo.Set_Source (Cr, Pat); Cairo.Arc (Cr, 256.0, 256.0, 153.6, 0.0, 2.0 * M_Pi); Cairo.Fill (Cr); Cairo.Pattern.Destroy (Pat); Status_Out := Write_To_Png (Surface, "SphereAda.png"); pragma Assert (Status_Out = Cairo_Status_Success); end Sphere;
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 other element types  %  % inserts a new element into the list, before e  % reference(DListIElement) procedure insertIntoDListIBefore( reference(DListIElement) value e  ; integer value v ); begin reference(DListIElement) newElement; newElement := DListIElement( null, v, e ); if e not = null then begin  % the element we are inserting before is not null  % reference(DListIElement) ePrev; ePrev  := prev(e); prev(newElement) := ePrev; prev(e)  := newElement; if ePrev not = null then next(ePrev) := newElement end if_e_ne_null ; newElement end insertIntoDListiAfter ;
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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_Lists.List; begin My_List.Append ('R'); My_List.Append ('o'); My_List.Append ('s'); My_List.Append ('e'); My_List.Append ('t'); My_List.Append ('t'); My_List.Append ('a');   My_List.Iterate (Print'Access); Ada.Text_IO.New_Line;   My_List.Reverse_Iterate (Print'Access); Ada.Text_IO.New_Line; end Traversing;
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 beginning of the list ---# PRIO PREPEND = 1; OP PREPEND = (REF LIST list, DATA data) VOID: ( HEAP NODE n := (data, NIL, NIL); IF head OF list IS REF NODE(NIL) THEN head OF list := tail OF list := n ELSE next OF n := head OF list; prev OF head OF list := head OF list := n FI ); #--- APPEND - Adds a node to the end of the list ---# PRIO APPEND = 1; OP APPEND = (REF LIST list, DATA data) VOID: ( HEAP NODE n := (data, NIL, NIL); IF head OF list IS REF NODE(NIL) THEN head OF list := tail OF list := n ELSE prev OF n := tail OF list; next OF tail OF list := tail OF list := n FI );   #--- REMOVE_FIRST - removes & returns node at end of the list ---# PRIO REMOVE_FIRST = 1; OP REMOVE_FIRST = (REF LIST list) DATA: ( IF head OF list ISNT REF NODE(NIL) THEN DATA d := data OF head OF list; prev OF next OF head OF list := NIL; head OF list := next OF head OF list; d # return d # FI ); #--- REMOVE_LAST: removes & returns node at front of list --- # PRIO REMOVE_LAST = 1; OP REMOVE_LAST = (REF LIST list) DATA: ( IF head OF list ISNT REF NODE(NIL) THEN DATA d := data OF tail OF list; next OF prev OF tail OF list := NIL; tail OF list := prev OF tail OF list; d # return d # FI ); #--- PURGE - removes all elements from the list ---# PRIO PURGE = 2; OP PURGE = (REF LIST list) VOID: ( head OF list := tail OF list := NIL );   #--- returns the data at the end of the list ---# PRIO LAST_IN = 2; OP LAST_IN = (REF LIST list) DATA: ( IF head OF list ISNT REF NODE(NIL) THEN data OF tail OF list FI );   #--- returns the data at the front of the list ---# PRIO FIRST_IN = 2; OP FIRST_IN = (REF LIST list) DATA: ( IF head OF list ISNT REF NODE(NIL) THEN data OF head OF list FI );   #--- Traverses through the list forwards ---# PROC forward traversal = (LIST list) VOID: ( REF NODE travel := head OF list; WHILE travel ISNT REF NODE(NIL) DO list visit(data OF travel); travel := next OF travel OD );   #--- Traverses through the list backwards ---# PROC backward traversal = (LIST list) VOID: ( REF NODE travel := tail OF list; WHILE travel ISNT REF NODE(NIL) DO list visit(data OF travel); travel := prev OF travel OD )
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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 += 1 _ArraySwap($avArray[$i], $avArray[$arraypos]) $i += 1 ElseIf $avArray[$i] >= $high Then _ArraySwap($avArray[$i], $avArray[$p]) $p -= 1 Else $i += 1 EndIf WEnd _ArrayDisplay($avArray) EndFunc ;==>Dutch_Flag  
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#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 y "+-|" loop 0..((4*z)-y)-3 'i -> cline 0 x y "| |" cline 0 x y "| +" loop (y-1)..0 'i -> cline 0 x i "| /" cline 0 x 0 "+-\n" ]   cuboid 2 3 4 cuboid 1 1 1 cuboid 6 2 1
http://rosettacode.org/wiki/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).   ?- o1::current_predicate(foo/1). true.   | ?- o1::foo(X). X = 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 a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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]] <= dividend, accumulator += t[[2]]; answer += t[[1]] ] , {t, Reverse@table} ]; {answer, dividend - accumulator} ] EgyptianDivide[580, 34]
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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 : INTEGER; BEGIN FOR i:=0 TO SZ-1 DO powers[i] := 1 SHL i; doublings[i] := divisor SHL i; IF doublings[i] > dividend THEN BREAK END END;   answer := 0; accumulator := 0; FOR i:=i-1 TO 0 BY -1 DO IF accumulator + doublings[i] <= dividend THEN accumulator := accumulator + doublings[i]; answer := answer + powers[i] END END;   remainder := dividend - accumulator; RETURN answer END EgyptianDivision;   VAR buf : ARRAY[0..63] OF CHAR; div,rem : LONGCARD; BEGIN div := EgyptianDivision(580, 34, rem); FormatString("580 divided by 34 is %l remainder %l\n", buf, div, rem); WriteString(buf);   ReadChar END EgyptianDivision.
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#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; term=#v); if(v[#v]>denom, denomAt=a/b; denom=v[#v]))); print("Most terms is "termAt" with "term); print("Biggest denominator is "denomAt" with "denom) apply(show, [43/48, 5/121, 2014/59]); best(9) best(99) best(999)  
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#SNUSP
SNUSP
/==!/==atoi==@@@-@-----# | | /-\ /recurse\ #/?\ zero $>,@/>,@/?\<=zero=!\?/<=print==!\@\>?!\@/<@\.!\-/ < @ # | \=/ \=itoa=@@@+@+++++# /==\ \===?!/===-?\>>+# halve ! /+ !/+ !/+ !/+ \ mod10 #  ! @ | #>>\?-<+>/ /<+> -\!?-\!?-\!?-\!?-\! /-<+>\ > ? />+<<++>-\ \?!\-?!\-?!\-?!\-?!\-?/\ div10 ?down? | \-<<<!\=======?/\ add & # +/! +/! +/! +/! +/ \>+<-/ | \=<<<!/====?\=\ | double ! # | \<++>-/ | | \=======\!@>============/!/
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#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)  »+« 2 «*« @!cells  »+«  @!cells.rotate(1) ] ) } }   my @padding = 0 xx 10;   my Automaton $a .= new: :rule(30), :cells(flat @padding, 1, @padding);   say $a++ for ^10;
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#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 Integer) As ULong ' Iterative ULfactorialI = 1 : For i As Integer = 1 To n : ULfactorialI *= i : Next End Function   ' Type Decimal:   Function DefactorialI(n As Integer) As Decimal ' Iterative DefactorialI = 1 : For i As Integer = 1 To n : DefactorialI *= i : Next End Function   ' Extends precision by "dehydrating" and "rehydrating" the powers of ten Function DxfactorialI(n As Integer) As String ' Iterative Dim factorial as Decimal = 1, zeros as integer = 0 For i As Integer = 1 To n : factorial *= i If factorial Mod 10 = 0 Then factorial /= 10 : zeros += 1 Next : Return factorial.ToString() & New String("0", zeros) End Function   ' Arbitrary Precision:   Function FactorialI(n As Integer) As BigInteger ' Iterative factorialI = 1 : For i As Integer = 1 To n : factorialI *= i : Next End Function   Function Factorial(number As Integer) As BigInteger ' Functional Return Enumerable.Range(1, number).Aggregate(New BigInteger(1), Function(acc, num) acc * num) End Function   Sub Main() Console.WriteLine("Double  : {0}! = {1:0}", 20, DoFactorialI(20)) Console.WriteLine("ULong  : {0}! = {1:0}", 20, ULFactorialI(20)) Console.WriteLine("Decimal : {0}! = {1:0}", 27, DeFactorialI(27)) Console.WriteLine("Dec.Ext : {0}! = {1:0}", 32, DxFactorialI(32)) Console.WriteLine("Arb.Prec: {0}! = {1}", 250, Factorial(250)) End Sub End Module
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#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 "Client {$client_count} ({$client_name}) connected\n"; $pid = pcntl_fork(); if($pid == -1) die('Could not fork'); if($pid){ pcntl_waitpid(-1, $status, WNOHANG); continue; }   //In a child process while(true){ if($input = socket_read($client, 1024)){ socket_write($client, $input); } else { socket_shutdown($client); socket_close($client); echo "Client {$client_count} ({$client_name}) disconnected\n"; exit(); } } }
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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( 2, 10000000, false), makeInterval( 2, 100000000, false), makeInterval( 2, 1000000000, false) } for _,intv in pairs(intervals) do if intv.start == 2 then print("eban numbers up to and including " .. intv.end_ .. ":") else print("eban numbers between " .. intv.start .. " and " .. intv.end_ .. " (inclusive)") end   local count = 0 for i=intv.start,intv.end_,2 do local b = math.floor(i / 1000000000) local r = i % 1000000000 local m = math.floor(r / 1000000) r = i % 1000000 local t = math.floor(r / 1000) r = r % 1000 if m >= 30 and m <= 66 then m = m % 10 end if t >= 30 and t <= 66 then t = t % 10 end if r >= 30 and r <= 66 then r = r % 10 end if b == 0 or b == 2 or b == 4 or b == 6 then if m == 0 or m == 2 or m == 4 or m == 6 then if t == 0 or t == 2 or t == 4 or t == 6 then if r == 0 or r == 2 or r == 4 or r == 6 then if intv.print_ then io.write(i .. " ") end count = count + 1 end end end end end   if intv.print_ then print() end print("count = " .. count) print() end end   main()
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#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 ) glColor3d( 1.0, 0.0, 0.3 ) glLineWidth( 1.5 ) glutWireCube( 1.0 ) end fn   // Main program dim as GLint           attrib(2) dim as CGrafPtr        port dim as AGLPixelFormat  fmt dim as AGLContext      glContext dim as EventRecord     ev dim as GLboolean       yesOK   window 1, @"Rotating Cube", (0,0) - (500,500)   attrib(0) = _AGLRGBA attrib(1) = _AGLDOUBLEBUFFER attrib(2) = _AGLNONE   fmt = fn aglChoosePixelFormat( 0, 0, attrib(0) ) glContext = fn aglCreateContext( fmt, 0 ) aglDestroyPixelFormat( fmt )   port = window( _wndPort ) yesOK = fn aglSetDrawable( glContext, port ) yesOK = fn aglSetCurrentContext( glContext )   glClearColor( 0.0, 0.0, 0.0, 0.0 )   poke long event - 8, 1 do glClear( _GLCOLORBUFFERBIT ) fn AnimateCube aglSwapBuffers( glContext ) HandleEvents until gFBQuit  
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#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}, {29/10, 31/10, 37/10}} ->{{282475249, 25937424601, 137858491849}, {2015993900449, 6131066257801, 41426511213649}, {420707233300201, 819628286980801, 4808584372417849}}   ->{{14, 22, 26}, {34, 38, 46}, {58, 62, 74}} ->{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}} ->{{49, 121, 169}, {289, 361, 529}, {841, 961, 1369}} ->{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}} ->{{823543, 285311670611, 302875106592253}, {827240261886336764177, 1978419655660313589123979, 20880467999847912034355032910567}, {2567686153161211134561828214731016126483469, 17069174130723235958610643029059314756044734431, 10555134955777783414078330085995832946127396083370199442517}}
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 = x then tmp + 1 else tmp end ciel ;  % returns the absolute value of the dot product of x and y or 0 if it is not negative  % real procedure dot( real array x, y ( * ) ) ; begin real tmp; tmp := x( 1 ) * y( 1 ) + x( 2 ) * y( 2 ) + x( 3 ) * y( 3 ); if tmp < 0 then - tmp else 0 end dot ;  % normalises the vector v  % procedure normalize( real array v ( * ) ) ; begin real tmp; tmp := sqrt( v( 1 ) * v( 1 ) + v( 2 ) * v( 2 ) + v( 3 ) * v( 3 ) ); for i := 1 until 3 do v( i ) := v( i ) / tmp end normalize ;  % draws a sphere using ASCII art  % procedure drawSphere( real value radius  ; integer value k  ; real value ambient  ; real array light ( * )  ; string(10) value shades ) ; begin real array vec ( 1 :: 3 ); integer intensity, maxShades; real diameter, r2; maxShades  := 9; diameter  := 2 * radius; r2  := radius * radius; for i := entier( - radius ) until ceil( radius ) do begin real x, x2; integer linePos; string(256) line; linePos := 0; x  := i + 0.5; x2  := x * x; line  := ""; for j := entier( - diameter ) until ceil( diameter ) do begin real y, y2; y  := j / 2 + 0.5; y2 := y * y; if x2 + y2 <= r2 then begin real b, dp; vec( 1 )  := x; vec( 2 )  := y; vec( 3 )  := sqrt( r2 - x2 - y2 ); normalize( vec ); dp  := dot( light, vec ); b  := dp; for p := 2 until k do b := b * dp; b  := b + ambient; intensity := round( ( 1 - b ) * maxShades ); if intensity < 0 then intensity := 0; if intensity > maxShades then intensity := maxShades; line( linePos // 1 ) := shades( intensity // 1 ); end else line( linePos // 1 ) := " "  ; if linePos < 255 then linePos := linePos + 1 end for_j ; write( s_w := 0, line( 0 // 1 ) ); for c := 1 until if linePos > 255 then 255 else linePos - 1 do writeon( s_w := 0, line( c // 1 ) ) end for_i end drawSphere ;  % test drawSphere  % begin real array light ( 1 :: 3 ); integer maxShades; light( 1 )  := 30; light( 2 )  := 30; light( 3 )  := -59; normalize( light ); drawSphere( 20, 4, 0.1, light, ".:!*oe#%&@" ); drawSphere( 10, 2, 0.4, light, ".:!*oe#%&@" ) end test end.
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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{} new.pNext% = here.pNext% new.pPrev% = here{}  !(^temp{}+4) = new.pNext% temp.pPrev% = new{} here.pNext% = new{} ENDPROC  
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C.23
C#
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: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 for other element types  %  % inserts a new element into the list, before e  % reference(DListIElement) procedure insertIntoDListIBefore( reference(DListIElement) value e  ; integer value v ); begin reference(DListIElement) newElement; newElement := DListIElement( null, v, e ); if e not = null then begin  % the element we are inserting before is not null  % reference(DListIElement) ePrev; ePrev  := prev(e); prev(newElement) := ePrev; prev(e)  := newElement; if ePrev not = null then next(ePrev) := newElement end if_e_ne_null ; newElement end insertIntoDListiAfter ;   begin reference(DListIElement) head, e, last; head := null; head := insertIntoDListIBefore( head, 1701 ); head := insertIntoDListIBefore( head, 9000 ); e  := insertIntoDListIBefore( next(head), 90210 ); e  := insertIntoDListIBefore( next(e), 4077 ); e  := head; last := null; write( "Forward:" ); while e not = null do begin write( i_w := 1, s_w := 0, " ", iValue(e) ); last := e; e  := next(e) end while_e_ne_null ; write( "Backward:" ); e := last; while e not = null do begin write( i_w := 1, s_w := 0, " ", iValue(e) ); last := e; e  := prev(e) end while_e_ne_null end end.
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 .equ WRITE, 4   /*******************************************/ /* Structures */ /********************************************/ /* structure Doublylinkedlist*/ .struct 0 dllist_head: @ head node .struct dllist_head + 4 dllist_tail: @ tail node .struct dllist_tail + 4 dllist_fin: /* 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 NDlist_value + 4 NDlist_fin: /* Initialized data */ .data szMessInitListe: .asciz "List initialized.\n" szMessListInv: .asciz "Display list inverse :\n" szCarriageReturn: .asciz "\n" szMessErreur: .asciz "Error detected.\n" /* datas message display */ szMessResult: .ascii "Result value :" sValue: .space 12,' ' .asciz "\n" /* UnInitialized data */ .bss dllist1: .skip dllist_fin @ list memory place   /* code section */ .text .global main main: ldr r0,iAdrdllist1 bl newDList @ create new list ldr r0,iAdrszMessInitListe bl affichageMess ldr r0,iAdrdllist1 @ list address mov r1,#10 @ value bl insertHead @ insertion at head cmp r0,#-1 beq 99f ldr r0,iAdrdllist1 mov r1,#20 bl insertTail @ insertion at tail cmp r0,#-1 beq 99f ldr r0,iAdrdllist1 @ list address mov r1,#10 @ value to after insered mov r2,#15 @ new value bl insertAfter cmp r0,#-1 beq 99f ldr r0,iAdrdllist1 @ list address mov r1,#20 @ value to after insered mov r2,#25 @ new value bl insertAfter cmp r0,#-1 beq 99f ldr r0,iAdrdllist1 bl transHeadTail @ display value head to tail ldr r0,iAdrszMessListInv bl affichageMess ldr r0,iAdrdllist1 bl transTailHead @ display value tail to head b 100f 99: ldr r0,iAdrszMessErreur bl affichageMess 100: @ standard end of the program mov r7, #EXIT @ request to exit program svc 0 @ perform system call iAdrszMessInitListe: .int szMessInitListe iAdrszMessErreur: .int szMessErreur iAdrszMessListInv: .int szMessListInv iAdrszCarriageReturn: .int szCarriageReturn iAdrdllist1: .int dllist1 /******************************************************************/ /* create new list */ /******************************************************************/ /* r0 contains the address of the list structure */ newDList: push {r1,lr} @ save registers mov r1,#0 str r1,[r0,#dllist_tail] str r1,[r0,#dllist_head] pop {r1,lr} @ restaur registers bx lr @ return /******************************************************************/ /* list is empty ? */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r0 return 0 if empty else return 1 */ isEmpty: //push {r1,lr} @ save registers ldr r0,[r0,#dllist_head] cmp r0,#0 movne r0,#1 //pop {r1,lr} @ restaur registers bx lr @ return /******************************************************************/ /* insert value at list head */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r1 contains value */ insertHead: push {r1-r4,lr} @ save registers mov r4,r0 @ save address mov r0,r1 @ value bl createNode cmp r0,#-1 @ allocation error ? beq 100f ldr r2,[r4,#dllist_head] @ load address first node str r2,[r0,#NDlist_next] @ store in next pointer on new node mov r1,#0 str r1,[r0,#NDlist_prev] @ store zero in previous pointer on new node str r0,[r4,#dllist_head] @ store address new node in address head list cmp r2,#0 @ address first node is null ? strne r0,[r2,#NDlist_prev] @ no store adresse new node in previous pointer streq r0,[r4,#dllist_tail] @ else store new node in tail address 100: pop {r1-r4,lr} @ restaur registers bx lr @ return /******************************************************************/ /* insert value at list tail */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r1 contains value */ insertTail: push {r1-r4,lr} @ save registers mov r4,r0 @ save list address mov r0,r1 @ value bl createNode @ new node cmp r0,#-1 beq 100f @ allocation error ldr r2,[r4,#dllist_tail] @ load address last node str r2,[r0,#NDlist_prev] @ store in previous pointer on new node mov r1,#0 @ store null un next pointer str r1,[r0,#NDlist_next] str r0,[r4,#dllist_tail] @ store address new node on list tail cmp r2,#0 @ address last node is null ? strne r0,[r2,#NDlist_next] @ no store address new node in next pointer streq r0,[r4,#dllist_head] @ else store in head list 100: pop {r1-r4,lr} @ restaur registers bx lr @ return /******************************************************************/ /* insert value after other element */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r1 contains value to search*/ /* r2 contains value to insert */ insertAfter: push {r1-r5,lr} @ save registers mov r4,r0 bl searchValue @ search node with this value in r1 cmp r0,#-1 beq 100f @ not found -> error mov r5,r0 @ save address of node find mov r0,r2 @ new value bl createNode @ create new node cmp r0,#-1 beq 100f @ allocation error ldr r2,[r5,#NDlist_next] @ load pointer next of find node str r0,[r5,#NDlist_next] @ store new node in pointer next str r5,[r0,#NDlist_prev] @ store address find node in previous pointer on new node str r2,[r0,#NDlist_next] @ store pointer next of find node on pointer next on new node cmp r2,#0 @ next pointer is null ? strne r0,[r2,#NDlist_prev] @ no store address new node in previous pointer streq r0,[r4,#dllist_tail] @ else store in list tail 100: pop {r1-r5,lr} @ restaur registers bx lr @ return /******************************************************************/ /* search value */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r1 contains the value to search */ /* r0 return address of node or -1 if not found */ searchValue: push {r2,lr} @ save registers ldr r0,[r0,#dllist_head] @ load first node 1: cmp r0,#0 @ null -> end search not found moveq r0,#-1 beq 100f ldr r2,[r0,#NDlist_value] @ load node value cmp r2,r1 @ equal ? beq 100f ldr r0,[r0,#NDlist_next] @ load addresse next node b 1b @ and loop 100: pop {r2,lr} @ restaur registers bx lr @ return /******************************************************************/ /* transversal for head to tail */ /******************************************************************/ /* r0 contains the address of the list structure */ transHeadTail: push {r2,lr} @ save registers ldr r2,[r0,#dllist_head] @ load first node 1: ldr r0,[r2,#NDlist_value] ldr r1,iAdrsValue bl conversion10S ldr r0,iAdrszMessResult bl affichageMess ldr r2,[r2,#NDlist_next] cmp r2,#0 bne 1b 100: pop {r2,lr} @ restaur registers bx lr @ return iAdrszMessResult: .int szMessResult iAdrsValue: .int sValue /******************************************************************/ /* transversal for tail to head */ /******************************************************************/ /* r0 contains the address of the list structure */ transTailHead: push {r2,lr} @ save registers ldr r2,[r0,#dllist_tail] @ load last node 1: ldr r0,[r2,#NDlist_value] ldr r1,iAdrsValue bl conversion10S ldr r0,iAdrszMessResult bl affichageMess ldr r2,[r2,#NDlist_prev] cmp r2,#0 bne 1b 100: pop {r2,lr} @ restaur registers bx lr @ return /******************************************************************/ /* Create new node */ /******************************************************************/ /* r0 contains the value */ /* r0 return node address or -1 if allocation error*/ createNode: push {r1-r7,lr} @ save registers mov r4,r0 @ save value @ allocation place on the heap mov r0,#0 @ allocation place heap mov r7,#0x2D @ call system 'brk' svc #0 mov r5,r0 @ save address heap for output string add r0,#NDlist_fin @ reservation place one element mov r7,#0x2D @ call system 'brk' svc #0 cmp r0,#-1 @ allocation error beq 100f mov r0,r5 str r4,[r0,#NDlist_value] @ store value mov r2,#0 str r2,[r0,#NDlist_next] @ store zero to pointer next str r2,[r0,#NDlist_prev] @ store zero to pointer previous 100: pop {r1-r7,lr} @ restaur registers bx lr @ return /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"    
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#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 actually # a prettyfied one-liner do for (i = 1; i <= ballnr; i++) do balls[i] = int(3 * rand() + 1) # These conditions ensure the 3 first balls contains # a white, blue and red ball. Removing 'i < 4' would # hit performance a lot. while ( (i < 4 && i > 1 && balls[i] == balls[i - 1]) || (i < 4 && i > 2 && balls[i] == balls[i - 2]) ) while (is_dnf(balls, ballnr))   printf("BEFORE: ") print_balls(balls, ballnr, weight)   # Using gawk default quicksort. Using variants of PROCINFO["sorted_in"] # wasn't faster than a simple call to asort(). asort(balls)   printf("\n\nAFTER : ") print_balls(balls, ballnr, weight)   sorting = is_dnf(balls, ballnr) ? "valid" : "invalid" print("\n\nSorting is " sorting ".") }   function print_balls(balls, ballnr, weight ,i) { for (i = 1; i <= ballnr; i++) printf("%-7s", weight[balls[i]]) }   function is_dnf(balls, ballnr) { # Checking if the balls are sorted in the Dutch national flag order, # using a simple scan with weight comparison for (i = 2; i <= ballnr; i++) if (balls[i - 1] > balls[i]) return 0 return 1 }  
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#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 := 700 TopX := (A_ScreenWidth - WinWidth) //2, TopY := (A_ScreenHeight - WinHeight) //2   Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs Gui, 1: Show, NA hwnd1 := WinExist(), hbm := CreateDIBSection(WinWidth, WinHeight), hdc := CreateCompatibleDC() , obm := SelectObject(hdc, hbm), G := Gdip_GraphicsFromHDC(hdc), Gdip_SetSmoothingMode(G, 4)   Points := A "," B "|" A+W "," B "|" A+W "," B-H "|" A "," B-H , DrawFace(Points, 0xff0066ff, G)   Points := A+W "," B "|" A+W+LX "," B-LY "|" A+W+LX "," B-LY-H "|" A+W "," B-H , DrawFace(Points, 0xff00d400, G)   Points := A "," B-H "|" A+W "," B-H "|" A+W+LX "," B-LY-H "|" A+LX "," B-LY-H , DrawFace(Points, 0xffd40055, G)   UpdateLayeredWindow(hwnd1, hdc, TopX, TopY, WinWidth, WinHeight)   SelectObject(hdc, obm), DeleteObject(hbm), DeleteDC(hdc) , Gdip_DeleteGraphics(G) return   DrawFace(Points, Color, G) { pBrush := Gdip_BrushCreateSolid(Color) , Gdip_FillPolygon(G, pBrush, Points, 1) , Gdip_DeleteBrush(pBrush) return }   Esc:: Exit: Gdip_Shutdown(pToken) ExitApp
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 \\ use of a$ as pointer to variable a$.+=100 Print eval(a$)=1100 \\ list of variables List } Keyboard "George"+chr$(13) DynamicVariable  
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 Color(255, 0, 0)); g.drawRect(100, 100, 1, 1); } public static void main(String[] args) { new DrawAPixel(); } }  
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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(int) * 8, int]   for i, _ in powersOfTwo: powersOfTwo[i] = 1 shl i doublings[i] = divisor shl i if doublings[i] > dividend: break   var answer = 0 var accumulator = 0 for i in countdown(len(doublings) - 1, 0): if accumulator + doublings[i] <= dividend: inc accumulator, doublings[i] inc answer, powersOfTwo[i] if accumulator == dividend: break (answer, dividend - accumulator)   let dividend = 580 let divisor = 34 var (quotient, remainder) = egyptianDivision(dividend, divisor) echo fmt"{dividend} divided by {divisor} is {quotient} with remainder {remainder}"
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#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]; $accumulator += 1 << $k; $dividend -= $table[$k]; } $accumulator, $dividend; }   for ([580,34], [578,34], [7532795332300578,235117]) { my($n,$d) = @$_; printf "Egyption divmod %s %% %s = %s remainder %s\n", $n, $d, egyptian_divmod( $n, $d ) }
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#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; return; } if($nr > $de){ printf int($nr/$de) . " + "; isEgyption($nr%$de, $de); return; } # Floor to find ceiling and print as fraction my $tmp = int($de/$nr) + 1; printf "1/" . $tmp . " + "; isEgyption($nr*$tmp-$de, $de*$tmp); }   my $nrI = 2014; my $deI = 59; printf "\nEgyptian Fraction Representation of " . $nrI . "/" . $deI . " is: \n\n"; isEgyption($nrI,$deI);  
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#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> ^right <y> ^return-to <r>)}   sp {multiply*propose*recurse (state <s> ^name multiply ^left <x> > 0 ^right <y> ^return-to <r> -^multiply-done) --> (<s> ^operator <o> +) (<o> ^name multiply ^left (div <x> 2) ^right (* <y> 2) ^return-to <s>)}   sp {multiply*elaborate*mod (state <s> ^name multiply ^left <x>) --> (<s> ^left-mod-2 (mod <x> 2))}   sp {multiply*elaborate*recursion-done-even (state <s> ^name multiply ^left <x> ^right <y> ^multiply-done <temp> ^left-mod-2 0) --> (<s> ^answer <temp>)}   sp {multiply*elaborate*recursion-done-odd (state <s> ^name multiply ^left <x> ^right <y> ^multiply-done <temp> ^left-mod-2 1) --> (<s> ^answer (+ <temp> <y>))}   sp {multiply*elaborate*zero (state <s> ^name multiply ^left 0) --> (<s> ^answer 0)}   sp {multiply*elaborate*done (state <s> ^name multiply ^return-to <r> ^answer <a>) --> (<r> ^multiply-done <a>)}
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#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 = @cur[-1] + @cur + @cur[0] @cur = @cur.size.times.map {|i| @patterns[str[i,3]]}.join end end   end   eca = ElemCellAutomat.new('1'.center(39, "0"), 18, true) eca.take(30).each{|line| puts line.tr("01", ".#")}
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#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 localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#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) # Echo lines (out Sock (prinl (line))) ) )   (prinl (stamp) " -- (Pid " *Pid ") Client disconnected") (bye) # Terminate child
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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..66: r mod 10 else: r return {b, m, t, r} <= {0, 2, 4, 6}   echo "eban numbers up to and including 1000:" for i in 0..100: if iseban(i): stdout.write(&"{i} ")   echo "\n\neban numbers between 1000 and 4000 (inclusive):" for i in 1_000..4_000: if iseban(i): stdout.write(&"{i} ")   var count = 0 for i in 0..10_000: if iseban(i): inc count echo &"\n\nNumber of eban numbers up to and including {10000:8}: {count:4}"   count = 0 for i in 0..100_000: if iseban(i): inc count echo &"\nNumber of eban numbers up to and including {100000:8}: {count:4}"   count = 0 for i in 0..1_000_000: if iseban(i): inc count echo &"\nNumber of eban numbers up to and including {1000000:8}: {count:4}"   count = 0 for i in 0..10_000_000: if iseban(i): inc count echo &"\nNumber of eban numbers up to and including {10000000:8}: {count:4}"   count = 0 for i in 0..100_000_000: if iseban(i): inc count echo &"\nNumber of eban numbers up to and including {100000000:8}: {count:4}"
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#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]...$/ or /[135].....$/; push @n, $_ unless num2en($_) =~ /e/; } @n; }   my @OK = e_ban(my $max = 7);   my @a = grep { $_ <= 1000 } @OK; say "Number of eban numbers up to and including 1000: @{[1+$#a]}"; say join(', ',@a); say '';   my @b = grep { $_ >= 1000 && $_ <= 4000 } @OK; say "Number of eban numbers between 1000 and 4000 (inclusive): @{[1+$#b]}"; say join(', ',@b); say '';   for my $exp (4..$max) { my $n = + grep { $_ <= 10**$exp } @OK; printf "Number of eban numbers and %10s: %d\n", comma(10**$exp), $n; }