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/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Vim_Script
Vim Script
Sub Main() End Sub
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.
#Factor
Factor
USING: arrays formatting fry io kernel math math.functions math.order math.ranges prettyprint sequences ;   : eban? ( n -- ? ) 1000000000 /mod 1000000 /mod 1000 /mod [ dup 30 66 between? [ 10 mod ] when ] tri@ 4array [ { 0 2 4 6 } member? ] all? ;   : .eban ( m n -- ) "eban numbers in [%d, %d]: " printf ; : eban ( m n q -- o ) '[ 2dup .eban [a,b] [ eban? ] @ ] call ; inline : .eban-range ( m n -- ) [ filter ] eban "%[%d, %]\n" printf ; : .eban-count ( m n -- ) "count of " write [ count ] eban . ;   1 1000 1000 4000 [ .eban-range ] 2bi@ 4 9 [a,b] [ [ 1 10 ] dip ^ .eban-count ] each
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.
#FreeBASIC
FreeBASIC
  ' Eban_numbers ' Un número eban es un número que no tiene la letra e cuando el número está escrito en inglés. ' O más literalmente, los números escritos que contienen la letra e están prohibidos. ' ' Usaremos la versión americana de los números de ortografía (a diferencia de los británicos). ' 2000000000 son dos billones, no dos millardos (mil millones). '   Data 2, 1000, 1 Data 1000, 4000, 1 Data 2, 10000, 0 Data 2, 100000, 0 Data 2, 1000000, 0 Data 2, 10000000, 0 Data 2, 100000000, 0 Data 0, 0, 0   Dim As Double tiempo = Timer Dim As Integer start, ended, printable, count Dim As Long i, b, r, m, t Do Read start, ended, printable   If start = 0 Then Exit Do If start = 2 Then Print "eban numbers up to and including"; ended; ":" Else Print "eban numbers between "; start; " and "; ended; " (inclusive):" End If   count = 0 For i = start To ended Step 2 b = Int(i / 1000000000) r = (i Mod 1000000000) m = Int(r / 1000000) r = (i Mod 1000000) t = Int(r / 1000) r = (r Mod 1000) If m >= 30 And m <= 66 Then m = (m Mod 10) If t >= 30 And t <= 66 Then t = (t Mod 10) If r >= 30 And r <= 66 Then r = (r Mod 10) 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 printable Then Print i; count += 1 End If End If End If End If Next i If printable Then Print Print "count = "; count & Chr(10) Loop tiempo = Timer - tiempo Print "Run time: " & (tiempo) & " seconds." 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.
#Groovy
Groovy
class NaiveMatrix {   List<List<Number>> contents = []   NaiveMatrix(Iterable<Iterable<Number>> elements) { contents.addAll(elements.collect{ row -> row.collect{ cell -> cell } }) assertWellFormed() }   void assertWellFormed() { assert contents != null assert contents.size() > 0 def nCols = contents[0].size() assert nCols > 0 assert contents.every { it != null && it.size() == nCols } }   Map getOrder() { [r: contents.size() , c: contents[0].size()] }   void assertConformable(NaiveMatrix that) { assert this.order == that.order }   NaiveMatrix unaryOp(Closure op) { new NaiveMatrix(contents.collect{ row -> row.collect{ cell -> op(cell) } } ) } NaiveMatrix binaryOp(NaiveMatrix m, Closure op) { assertConformable(m) new NaiveMatrix( (0..<(this.order.r)).collect{ i -> (0..<(this.order.c)).collect{ j -> op(this.contents[i][j],m.contents[i][j]) } } ) } NaiveMatrix binaryOp(Number n, Closure op) { assert n != null new NaiveMatrix(contents.collect{ row -> row.collect{ cell -> op(cell,n) } } ) }   def plus = this.&binaryOp.rcurry { a, b -> a+b }   def minus = this.&binaryOp.rcurry { a, b -> a-b }   def multiply = this.&binaryOp.rcurry { a, b -> a*b }   def div = this.&binaryOp.rcurry { a, b -> a/b }   def mod = this.&binaryOp.rcurry { a, b -> a%b }   def power = this.&binaryOp.rcurry { a, b -> a**b }   def negative = this.&unaryOp.curry { - it }   def recip = this.&unaryOp.curry { 1/it }   String toString() { contents.toString() }   boolean equals(Object other) { if (other == null || ! other instanceof NaiveMatrix) return false def that = other as NaiveMatrix this.contents == that.contents }   int hashCode() { contents.hashCode() } }
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.
#Factor
Factor
42 readln set
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.
#Forth
Forth
s" VARIABLE " pad swap move ." Variable name: " pad 9 + 80 accept pad swap 9 + evaluate
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type DynamicVariable As String name As String value End Type   Function FindVariableIndex(a() as DynamicVariable, v as String, nElements As Integer) As Integer v = LCase(Trim(v)) For i As Integer = 1 To nElements If a(i).name = v Then Return i Next Return 0 End Function   Dim As Integer n, index Dim As String v Cls   Do Input "How many variables do you want to create (max 5) "; n Loop Until n > 0 AndAlso n < 6   Dim a(1 To n) As DynamicVariable Print Print "OK, enter the variable names and their values, below"   For i As Integer = 1 to n Print Print " Variable"; i Input " Name  : ", a(i).name a(i).name = LCase(Trim(a(i).name)) ' variable names are not case sensitive in FB If i > 0 Then index = FindVariableIndex(a(), a(i).name, i - 1) If index > 0 Then Print " Sorry, you've already created a variable of that name, try again" i -= 1 Continue For End If End If Input " Value : ", a(i).value a(i).value = LCase(Trim(a(i).value)) Next   Print Print "Press q to quit" Do Print Input "Which variable do you want to inspect "; v If v = "q" OrElse v = "Q" Then Exit Do index = FindVariableIndex(a(), v, n) If index = 0 Then Print "Sorry there's no variable of that name, try again" Else Print "It's value is "; a(index).value End If Loop 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
#AutoHotkey
AutoHotkey
Gui, Add, Picture, x100 y100 w2 h2 +0x4E +HWNDhPicture CreatePixel("FF0000", hPicture) Gui, Show, w320 h240, Example return   CreatePixel(Color, Handle) { VarSetCapacity(BMBITS, 4, 0), Numput("0x" . Color, &BMBITS, 0, "UInt") hBM := DllCall("Gdi32.dll\CreateBitmap", "Int", 1, "Int", 1, "UInt", 1, "UInt", 24, "Ptr", 0, "Ptr") hBM := DllCall("User32.dll\CopyImage", "Ptr", hBM, "UInt", 0, "Int", 0, "Int", 0, "UInt", 0x2008, "Ptr") DllCall("Gdi32.dll\SetBitmapBits", "Ptr", hBM, "UInt", 3, "Ptr", &BMBITS) DllCall("User32.dll\SendMessage", "Ptr", Handle, "UInt", 0x172, "Ptr", 0, "Ptr", hBM) }
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
#FreeBASIC
FreeBASIC
' version 09-08-2017 ' compile with: fbc -s console   Data 580, 34   Dim As UInteger dividend, divisor, answer, accumulator, i ReDim As UInteger table(1 To 32, 1 To 2)   Read dividend, divisor   i = 1 table(i, 1) = 1 : table(i, 2) = divisor   While table(i, 2) < dividend i += 1 table(i, 1) = table(i -1, 1) * 2 table(i, 2) = table(i -1, 2) * 2 Wend   i -= 1 answer = table(i, 1) accumulator = table(i, 2)   While i > 1 i -= 1 If table(i,2)+ accumulator <= dividend Then answer += table(i, 1) accumulator += table(i, 2) End If Wend   Print Str(dividend); " divided by "; Str(divisor); " using Egytian division"; Print " returns "; Str(answer); " mod(ulus) "; Str(dividend-accumulator)   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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
#Haskell
Haskell
import Data.Ratio (Ratio, (%), denominator, numerator)   egyptianFraction :: Integral a => Ratio a -> [Ratio a] egyptianFraction n | n < 0 = map negate (egyptianFraction (-n)) | n == 0 = [] | x == 1 = [n] | x > y = (x `div` y % 1) : egyptianFraction (x `mod` y % y) | otherwise = (1 % r) : egyptianFraction ((-y) `mod` x % (y * r)) where x = numerator n y = denominator n r = y `div` x + 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
#Rust
Rust
fn double(a: i32) -> i32 { 2*a }   fn halve(a: i32) -> i32 { a/2 }   fn is_even(a: i32) -> bool { a % 2 == 0 }   fn ethiopian_multiplication(mut x: i32, mut y: i32) -> i32 { let mut sum = 0;   while x >= 1 { print!("{} \t {}", x, y); match is_even(x) { true => println!("\t Not Kept"), false => { println!("\t Kept"); sum += y; } } x = halve(x); y = double(y); } sum }   fn main() { let output = ethiopian_multiplication(17, 34); println!("---------------------------------"); println!("\t {}", output); }
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)
#Lua
Lua
local CA = { state = "..............................#..............................", bstr = { [0]="...", "..#", ".#.", ".##", "#..", "#.#", "##.", "###" }, new = function(self, rule) local inst = setmetatable({rule=rule}, self) for b = 0,7 do inst[inst.bstr[b]] = rule%2==0 and "." or "#" rule = math.floor(rule/2) end return inst end, evolve = function(self) local n, state, newstate = #self.state, self.state, "" for i = 1,n do local nbhd = state:sub((i+n-2)%n+1,(i+n-2)%n+1) .. state:sub(i,i) .. state:sub(i%n+1,i%n+1) newstate = newstate .. self[nbhd] end self.state = newstate end, } CA.__index = CA ca = { CA:new(18), CA:new(30), CA:new(73), CA:new(129) } for i = 1, 63 do print(string.format("%-66s%-66s%-66s%-61s", ca[1].state, ca[2].state, ca[3].state, ca[4].state)) for j = 1, 4 do ca[j]:evolve() end end
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
#Ursala
Ursala
#import nat   good_factorial = ~&?\1! product:-1^lrtPC/~& iota better_factorial = ~&?\1! ^T(~&lSL,@rS product:-1)+ ~&Z-~^*lrtPC/~& iota
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Zoea_Visual
Zoea Visual
  module Main; var x: integer; s: set; begin x := 10;writeln(x:3," is odd?",odd(x)); s := set(s);writeln(x:3," is odd?",0 in s); (* check right bit *) x := 11;writeln(x:3," is odd?",odd(x)); s := set(x);writeln(x:3," is odd?",0 in s); (* check right bit *) end Main.  
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#zonnon
zonnon
  module Main; var x: integer; s: set; begin x := 10;writeln(x:3," is odd?",odd(x)); s := set(s);writeln(x:3," is odd?",0 in s); (* check right bit *) x := 11;writeln(x:3," is odd?",odd(x)); s := set(x);writeln(x:3," is odd?",0 in s); (* check right bit *) end Main.  
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.
#Lua
Lua
local socket = require("socket")   local function has_value(tab, value) for i, v in ipairs(tab) do if v == value then return i end end return false end   local function checkOn(client) local line, err = client:receive() if line then client:send(line .. "\n") end if err and err ~= "timeout" then print(tostring(client) .. " " .. err) client:close() return true -- end this connection end return false -- do not end this connection end   local server = assert(socket.bind("*",12321)) server:settimeout(0) -- make non-blocking local connections = { } -- a list of the client connections while true do local newClient = server:accept() if newClient then newClient:settimeout(0) -- make non-blocking table.insert(connections, newClient) end local readList = socket.select({server, table.unpack(connections)}) for _, conn in ipairs(readList) do if conn ~= server and checkOn(conn) then table.remove(connections, has_value(connections, conn)) end end end
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Visual_Basic
Visual Basic
Sub Main() End Sub
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Visual_Basic_.NET
Visual Basic .NET
Module General Sub Main() End Sub End Module
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Vlang
Vlang
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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   type Range struct { start, end uint64 print bool }   func main() { rgs := []Range{ {2, 1000, true}, {1000, 4000, true}, {2, 1e4, false}, {2, 1e5, false}, {2, 1e6, false}, {2, 1e7, false}, {2, 1e8, false}, {2, 1e9, false}, } for _, rg := range rgs { if rg.start == 2 { fmt.Printf("eban numbers up to and including %d:\n", rg.end) } else { fmt.Printf("eban numbers between %d and %d (inclusive):\n", rg.start, rg.end) } count := 0 for i := rg.start; i <= rg.end; i += 2 { b := i / 1000000000 r := i % 1000000000 m := r / 1000000 r = i % 1000000 t := r / 1000 r %= 1000 if m >= 30 && m <= 66 { m %= 10 } if t >= 30 && t <= 66 { t %= 10 } if r >= 30 && r <= 66 { r %= 10 } if b == 0 || b == 2 || b == 4 || b == 6 { if m == 0 || m == 2 || m == 4 || m == 6 { if t == 0 || t == 2 || t == 4 || t == 6 { if r == 0 || r == 2 || r == 4 || r == 6 { if rg.print { fmt.Printf("%d ", i) } count++ } } } } } if rg.print { fmt.Println() } fmt.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
#Ada
Ada
with Ada.Numerics.Elementary_Functions;   with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Events.Events;   procedure Rotating_Cube is   Width  : constant := 500; Height : constant := 500; Offset : constant := 500.0 / 2.0;   Window  : SDL.Video.Windows.Window; Renderer : SDL.Video.Renderers.Renderer; Event  : SDL.Events.Events.Events; Quit  : Boolean := False;   type Node_Id is new Natural; type Point_3D is record X, Y, Z : Float; end record; type Edge_Type is record A, B  : Node_Id; end record;   Nodes : array (Node_Id range <>) of Point_3D := ((-100.0, -100.0, -100.0), (-100.0, -100.0, 100.0), (-100.0, 100.0, -100.0), (-100.0, 100.0, 100.0), (100.0, -100.0, -100.0), (100.0, -100.0, 100.0), (100.0, 100.0, -100.0), (100.0, 100.0, 100.0)); Edges : constant array (Positive range <>) of Edge_Type := ((0, 1), (1, 3), (3, 2), (2, 0), (4, 5), (5, 7), (7, 6), (6, 4), (0, 4), (1, 5), (2, 6), (3, 7));   use Ada.Numerics.Elementary_Functions;   procedure Rotate_Cube (AngleX, AngleY : in Float) is SinX : constant Float := Sin (AngleX); CosX : constant Float := Cos (AngleX); SinY : constant Float := Sin (AngleY); CosY : constant Float := Cos (AngleY); X, Y, Z : Float; begin for Node of Nodes loop X := Node.X; Y := Node.Y; Z := Node.Z; Node.X := X * CosX - Z * SinX; Node.Z := Z * CosX + X * SinX; Z := Node.Z; Node.Y := Y * CosY - Z * SinY; Node.Z := Z * CosY + Y * SinY; end loop; end Rotate_Cube;   function Poll_Quit return Boolean is use type SDL.Events.Event_Types; begin while SDL.Events.Events.Poll (Event) loop if Event.Common.Event_Type = SDL.Events.Quit then return True; end if; end loop; return False; end Poll_Quit;   procedure Draw_Cube (Quit : out Boolean) is use SDL.C; Pi : constant := Ada.Numerics.Pi; Xy1, Xy2 : Point_3D; begin Rotate_Cube (Pi / 4.0, Arctan (Sqrt (2.0))); for Frame in 0 .. 359 loop Renderer.Set_Draw_Colour ((0, 0, 0, 255)); Renderer.Fill (Rectangle => (0, 0, Width, Height));   Renderer.Set_Draw_Colour ((0, 220, 0, 255)); for Edge of Edges loop Xy1 := Nodes (Edge.A); Xy2 := Nodes (Edge.B); Renderer.Draw (Line => ((int (Xy1.X + Offset), int (Xy1.Y + Offset)), (int (Xy2.X + Offset), int (Xy2.Y + Offset)))); end loop; Rotate_Cube (Pi / 180.0, 0.0); Window.Update_Surface; Quit := Poll_Quit; exit when Quit; delay 0.020; end loop; end Draw_Cube;   begin if not SDL.Initialise (Flags => SDL.Enable_Screen) then return; end if;   SDL.Video.Windows.Makers.Create (Win => Window, Title => "Rotating cube", Position => SDL.Natural_Coordinates'(X => 10, Y => 10), Size => SDL.Positive_Sizes'(Width, Height), Flags => 0); SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);   while not Quit loop Draw_Cube (Quit); end loop;   Window.Finalize; SDL.Finalise; end Rotating_Cube;
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.
#Haskell
Haskell
{-# OPTIONS_GHC -fno-warn-duplicate-constraints #-} {-# LANGUAGE RankNTypes #-}   import Data.Array (Array, Ix) import Data.Array.Base   -- | Element-wise combine the values of two arrays 'a' and 'b' with 'f'. -- 'a' and 'b' must have the same bounds. zipWithA :: (IArray arr a, IArray arr b, IArray arr c, Ix i) => (a -> b -> c) -> arr i a -> arr i b -> arr i c zipWithA f a b = case bounds a of ba -> if ba /= bounds b then error "elemwise: bounds mismatch" else let n = numElements a in unsafeArray ba [ (i, f (unsafeAt a i) (unsafeAt b i)) | i <- [0 .. n - 1]]   -- Convenient aliases for matrix-matrix element-wise operations. type ElemOp a b c = (IArray arr a, IArray arr b, IArray arr c, Ix i) => arr i a -> arr i b -> arr i c type ElemOp1 a = ElemOp a a a   infixl 6 +:, -: infixl 7 *:, /:, `divE`   (+:), (-:), (*:) :: (Num a) => ElemOp1 a (+:) = zipWithA (+) (-:) = zipWithA (-) (*:) = zipWithA (*)   divE :: (Integral a) => ElemOp1 a divE = zipWithA div   (/:) :: (Fractional a) => ElemOp1 a (/:) = zipWithA (/)   infixr 8 ^:, **:, ^^:   (^:) :: (Num a, Integral b) => ElemOp a b a (^:) = zipWithA (^)   (**:) :: (Floating a) => ElemOp1 a (**:) = zipWithA (**)   (^^:) :: (Fractional a, Integral b) => ElemOp a b a (^^:) = zipWithA (^^)   -- Convenient aliases for matrix-scalar element-wise operations. type ScalarOp a b c = (IArray arr a, IArray arr c, Ix i) => arr i a -> b -> arr i c type ScalarOp1 a = ScalarOp a a a   samap :: (IArray arr a, IArray arr c, Ix i) => (a -> b -> c) -> arr i a -> b -> arr i c samap f a s = amap (`f` s) a   infixl 6 +., -. infixl 7 *., /., `divS`   (+.), (-.), (*.) :: (Num a) => ScalarOp1 a (+.) = samap (+) (-.) = samap (-) (*.) = samap (*)   divS :: (Integral a) => ScalarOp1 a divS = samap div   (/.) :: (Fractional a) => ScalarOp1 a (/.) = samap (/)   infixr 8 ^., **., ^^.   (^.) :: (Num a, Integral b) => ScalarOp a b a (^.) = samap (^)   (**.) :: (Floating a) => ScalarOp1 a (**.) = samap (**)   (^^.) :: (Fractional a, Integral b) => ScalarOp a b a (^^.) = samap (^^)   main :: IO () main = do let m1, m2 :: (forall a. (Enum a, Num a) => Array (Int, Int) a) m1 = listArray ((0, 0), (2, 3)) [1..] m2 = listArray ((0, 0), (2, 3)) [10..] s :: (forall a. Num a => a) s = 99 putStrLn "m1" print m1 putStrLn "m2" print m2 putStrLn "s" print s putStrLn "m1 + m2" print $ m1 +: m2 putStrLn "m1 - m2" print $ m1 -: m2 putStrLn "m1 * m2" print $ m1 *: m2 putStrLn "m1 `div` m2" print $ m1 `divE` m2 putStrLn "m1 / m2" print $ m1 /: m2 putStrLn "m1 ^ m2" print $ m1 ^: m2 putStrLn "m1 ** m2" print $ m1 **: m2 putStrLn "m1 ^^ m2" print $ m1 ^^: m2 putStrLn "m1 + s" print $ m1 +. s putStrLn "m1 - s" print $ m1 -. s putStrLn "m1 * s" print $ m1 *. s putStrLn "m1 `div` s" print $ m1 `divS` s putStrLn "m1 / s" print $ m1 /. s putStrLn "m1 ^ s" print $ m1 ^. s putStrLn "m1 ** s" print $ m1 **. s putStrLn "m1 ^^ s" print $ m1 ^^. s
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#GAP
GAP
# As is, will not work if val is a String Assign := function(var, val) Read(InputTextString(Concatenation(var, " := ", String(val), ";"))); end;
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.
#Genyris
Genyris
defvar (intern 'This is not a pipe.') 42 define |<weird>| 2009
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
#BASIC256
BASIC256
  rem http://rosettacode.org/wiki/Draw_a_pixel   graphsize 320, 240 color red plot 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
#BBC_BASIC
BBC BASIC
VDU 23, 22, 320; 240; 8, 8, 8, 0, 18, 0, 1, 25, 69, 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
#Go
Go
package main   import "fmt"   func egyptianDivide(dividend, divisor int) (quotient, remainder int) { if dividend < 0 || divisor <= 0 { panic("Invalid argument(s)") } if dividend < divisor { return 0, dividend } powersOfTwo := []int{1} doublings := []int{divisor} doubling := divisor for { doubling *= 2 if doubling > dividend { break } l := len(powersOfTwo) powersOfTwo = append(powersOfTwo, powersOfTwo[l-1]*2) doublings = append(doublings, doubling) } answer := 0 accumulator := 0 for i := len(doublings) - 1; i >= 0; i-- { if accumulator+doublings[i] <= dividend { accumulator += doublings[i] answer += powersOfTwo[i] if accumulator == dividend { break } } } return answer, dividend - accumulator }   func main() { dividend := 580 divisor := 34 quotient, remainder := egyptianDivide(dividend, divisor) fmt.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
#J
J
ef =: [: (}.~ 0={.) [: (, r2ef)/ 0 1 #: x: r2ef =: (<(<0);0) { ((] , -) >:@:<.&.%)^:((~:<.)@:%)@:{:^:a:
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
#S-BASIC
S-BASIC
  $constant true = 0FFFFH $constant false = 0   function half(n = integer) = integer end = n / 2   function twice(n = integer) = integer end = n + n   rem - return true (-1) if n is even, otherwise false function even(n = integer) = integer var one = integer one = 1 rem - only variables are compared bitwise end = ((n and one) = 0)   rem - return i * j, optionally showing steps function ethiopian(i, j, show = integer) = integer var p = integer p = 0 while i >= 1 do begin if even(i) then begin if show then print i;" ---";j end else begin if show then print i;" ";j;"+" p = p + j end i = half(i) j = twice(j) end if show then begin print "----------" print " ="; end end = p   rem - exercise the function print "Multiplying 17 times 34" print ethiopian(17,34,true)   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)
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ArrayPlot[CellularAutomaton[30, {0, 0, 0, 0, 1, 0, 0, 0}, 100]]
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)
#MATLAB
MATLAB
function init = cellularAutomaton(rule, init, n) init(n + 1, :) = 0; for k = 1 : n init(k + 1, :) = bitget(rule, 1 + filter2([4 2 1], init(k, :))); end
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
#VBA
VBA
Public Function factorial(n As Integer) As Long factorial = WorksheetFunction.Fact(n) End Function
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 FOR n=-3 TO 4: GO SUB 30: NEXT n 20 STOP 30 LET odd=FN m(n,2) 40 PRINT n;" is ";("Even" AND odd=0)+("Odd" AND odd=1) 50 RETURN 60 DEF FN m(a,b)=a-INT (a/b)*b
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
server = SocketOpen[12321]; SocketListen[server, Function[{assoc}, With[{client = assoc["SourceSocket"], input = assoc["Data"]}, WriteString[client, ByteArrayToString[input]]; ] ]]
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Wart
Wart
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#WDTE
WDTE
(module  ;;The entry point for WASI is called _start (func $main (export "_start")   ) )  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#WebAssembly
WebAssembly
(module  ;;The entry point for WASI is called _start (func $main (export "_start")   ) )  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Wee_Basic
Wee Basic
 
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.
#Go
Go
package main   import "fmt"   type Range struct { start, end uint64 print bool }   func main() { rgs := []Range{ {2, 1000, true}, {1000, 4000, true}, {2, 1e4, false}, {2, 1e5, false}, {2, 1e6, false}, {2, 1e7, false}, {2, 1e8, false}, {2, 1e9, false}, } for _, rg := range rgs { if rg.start == 2 { fmt.Printf("eban numbers up to and including %d:\n", rg.end) } else { fmt.Printf("eban numbers between %d and %d (inclusive):\n", rg.start, rg.end) } count := 0 for i := rg.start; i <= rg.end; i += 2 { b := i / 1000000000 r := i % 1000000000 m := r / 1000000 r = i % 1000000 t := r / 1000 r %= 1000 if m >= 30 && m <= 66 { m %= 10 } if t >= 30 && t <= 66 { t %= 10 } if r >= 30 && r <= 66 { r %= 10 } if b == 0 || b == 2 || b == 4 || b == 6 { if m == 0 || m == 2 || m == 4 || m == 6 { if t == 0 || t == 2 || t == 4 || t == 6 { if r == 0 || r == 2 || r == 4 || r == 6 { if rg.print { fmt.Printf("%d ", i) } count++ } } } } } if rg.print { fmt.Println() } fmt.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
#AutoHotkey
AutoHotkey
; --------------------------------------------------------------- cubeSize := 200 deltaX := A_ScreenWidth/2 deltaY := A_ScreenHeight/2 keyStep := 1 mouseStep := 0.2 zoomStep := 1.1 playSpeed := 1 playTimer := 10 penSize := 5   /* HotKeys: !p:: Play/Stop !x:: change play to x-axis !y:: change play to y-axis !z:: change play to z-axis !NumpadAdd:: Zoom in !WheelUp:: Zoom in !NumpadSub:: Zoom out !WheelDown:: Zoom out !LButton:: Rotate X-axis, follow mouse !Up:: Rotate X-axis, CCW !Down:: Rotate X-axis, CW !LButton:: Rotate Y-axis, follow mouse !Right:: Rotate Y-axis, CCW !Left:: Rotate Y-axis, CW !RButton:: Rotate Z-axis, follow mouse !PGUP:: Rotate Z-axis, CW !PGDN:: Rotate Z-axis, CCW +LButton:: Move, follow mouse ^esc:: Exitapp */ visualCube = ( 1+--------+5 |\ \ | 2+--------+6 | | | 3+ | 7+ | \ | | 4+--------+8 )   SetBatchLines, -1 coord := cubeSize/2 nodes :=[[-coord, -coord, -coord] , [-coord, -coord, coord] , [-coord, coord, -coord] , [-coord, coord, coord] , [ coord, -coord, -coord] , [ coord, -coord, coord] , [ coord, coord, -coord] , [ coord, coord, coord]]   edges := [[1, 2], [2, 4], [4, 3], [3, 1] , [5, 6], [6, 8], [8, 7], [7, 5] , [1, 5], [2, 6], [3, 7], [4, 8]]   faces := [[1,2,4,3], [2,4,8,6], [1,2,6,5], [1,3,7,5], [5,7,8,6], [3,4,8,7]]   CP := [(nodes[8,1]+nodes[1,1])/2 , (nodes[8,2]+nodes[1,2])/2]   rotateX3D(-30) rotateY3D(30) Gdip1() draw() return   ; -------------------------------------------------------------- draw() { global D := "" for i, n in nodes D .= Sqrt((n.1-CP.1)**2 + (n.2-CP.2)**2) "`t:" i ":`t" n.3 "`n" Sort, D, N p1 := StrSplit(StrSplit(D, "`n", "`r").1, ":").2 p2 := StrSplit(StrSplit(D, "`n", "`r").2, ":").2 hiddenNode := nodes[p1,3] < nodes[p2,3] ? p1 : p2   ; Draw Faces loop % faces.count() { n1 := faces[A_Index, 1] n2 := faces[A_Index, 2] n3 := faces[A_Index, 3] n4 := faces[A_Index, 4] if (n1 = hiddenNode) || (n2 = hiddenNode) || (n3 = hiddenNode) || (n4 = hiddenNode) continue points := nodes[n1,1]+deltaX "," nodes[n1,2]+deltaY . "|" nodes[n2,1]+deltaX "," nodes[n2,2]+deltaY . "|" nodes[n3,1]+deltaX "," nodes[n3,2]+deltaY . "|" nodes[n4,1]+deltaX "," nodes[n4,2]+deltaY Gdip_FillPolygon(G, FaceBrush%A_Index%, Points) }   ; Draw Node-Numbers ;~ loop % nodes.count() { ;~ Gdip_FillEllipse(G, pBrush, nodes[A_Index, 1]+deltaX, nodes[A_Index, 2]+deltaY, 4, 4) ;~ Options := "x" nodes[A_Index, 1]+deltaX " y" nodes[A_Index, 2]+deltaY "c" TextColor " Bold s" size ;~ Gdip_TextToGraphics(G, A_Index, Options, Font) ;~ }   ; Draw Edges loop % edges.count() { n1 := edges[A_Index, 1] n2 := edges[A_Index, 2] if (n1 = hiddenNode) || (n2 = hiddenNode) continue Gdip_DrawLine(G, pPen, nodes[n1,1]+deltaX, nodes[n1,2]+deltaY, nodes[n2,1]+deltaX, nodes[n2,2]+deltaY) } UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height) }   ; --------------------------------------------------------------- rotateZ3D(theta) { ; Rotate shape around the z-axis global theta *= 3.141592653589793/180 sinTheta := sin(theta) cosTheta := cos(theta) loop % nodes.count() { x := nodes[A_Index,1] y := nodes[A_Index,2] nodes[A_Index,1] := x*cosTheta - y*sinTheta nodes[A_Index,2] := y*cosTheta + x*sinTheta } Redraw() }   ; --------------------------------------------------------------- rotateX3D(theta) { ; Rotate shape around the x-axis global theta *= 3.141592653589793/180 sinTheta := sin(theta) cosTheta := cos(theta) loop % nodes.count() { y := nodes[A_Index, 2] z := nodes[A_Index, 3] nodes[A_Index, 2] := y*cosTheta - z*sinTheta nodes[A_Index, 3] := z*cosTheta + y*sinTheta } Redraw() }   ; --------------------------------------------------------------- rotateY3D(theta) { ; Rotate shape around the y-axis global theta *= 3.141592653589793/180 sinTheta := sin(theta) cosTheta := cos(theta) loop % nodes.count() { x := nodes[A_Index, 1] z := nodes[A_Index, 3] nodes[A_Index, 1] := x*cosTheta + z*sinTheta nodes[A_Index, 3] := z*cosTheta - x*sinTheta } Redraw() }   ; --------------------------------------------------------------- Redraw(){ global gdip2() gdip1() draw() }   ; --------------------------------------------------------------- gdip1(){ global If !pToken := Gdip_Startup() { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp } OnExit, Exit Width := A_ScreenWidth, Height := A_ScreenHeight Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop Gui, 1: Show, NA hwnd1 := WinExist() hbm := CreateDIBSection(Width, Height) hdc := CreateCompatibleDC() obm := SelectObject(hdc, hbm) G := Gdip_GraphicsFromHDC(hdc) Gdip_SetSmoothingMode(G, 4) TextColor:="FFFFFF00", size := 18 Font := "Arial" Gdip_FontFamilyCreate(Font) pBrush := Gdip_BrushCreateSolid(0xFFFF00FF) FaceBrush1 := Gdip_BrushCreateSolid(0xFF0000FF) ; blue FaceBrush2 := Gdip_BrushCreateSolid(0xFFFF0000) ; red FaceBrush3 := Gdip_BrushCreateSolid(0xFFFFFF00) ; yellow FaceBrush4 := Gdip_BrushCreateSolid(0xFFFF7518) ; orange FaceBrush5 := Gdip_BrushCreateSolid(0xFF00FF00) ; lime FaceBrush6 := Gdip_BrushCreateSolid(0xFFFFFFFF) ; white pPen := Gdip_CreatePen(0xFF000000, penSize) }   ; --------------------------------------------------------------- gdip2(){ global Gdip_DeleteBrush(pBrush) Gdip_DeletePen(pPen) SelectObject(hdc, obm) DeleteObject(hbm) DeleteDC(hdc) Gdip_DeleteGraphics(G) } ; Viewing Hotkeys ---------------------------------------------- ; HotKey Play/Stop --------------------------------------------- !p:: SetTimer, rotateTimer, % (toggle:=!toggle)?playTimer:"off" return   rotateTimer: axis := !axis ? "Y" : axis rotate%axis%3D(playSpeed) return   !x:: !y:: !z:: axis := SubStr(A_ThisHotkey, 2, 1) return   ; HotKey Zoom in/out ------------------------------------------- !NumpadAdd:: !NumpadSub:: !WheelUp:: !WheelDown:: loop % nodes.count() { nodes[A_Index, 1] := nodes[A_Index, 1] * (InStr(A_ThisHotkey, "Add") || InStr(A_ThisHotkey, "Up") ? zoomStep : 1/zoomStep) nodes[A_Index, 2] := nodes[A_Index, 2] * (InStr(A_ThisHotkey, "Add") || InStr(A_ThisHotkey, "Up") ? zoomStep : 1/zoomStep) nodes[A_Index, 3] := nodes[A_Index, 3] * (InStr(A_ThisHotkey, "Add") || InStr(A_ThisHotkey, "Up") ? zoomStep : 1/zoomStep) } Redraw() return   ; HotKey Rotate around Y-Axis ---------------------------------- !Right:: !Left:: rotateY3D(keyStep * (InStr(A_ThisHotkey,"right") ? 1 : -1)) return   ; HotKey Rotate around X-Axis ---------------------------------- !Up:: !Down:: rotateX3D(keyStep * (InStr(A_ThisHotkey, "Up") ? 1 : -1)) return   ; HotKey Rotate around Z-Axis ---------------------------------- !PGUP:: !PGDN:: rotateZ3D(keyStep * (InStr(A_ThisHotkey, "UP") ? 1 : -1)) return   ; HotKey, Rotate around X/Y-Axis ------------------------------- !LButton:: MouseGetPos, pmouseX, pmouseY while GetKeyState("Lbutton", "P") { MouseGetPos, mouseX, mouseY DeltaMX := mouseX - pmouseX DeltaMY := pmouseY - mouseY if (DeltaMX || DeltaMY) { MouseGetPos, pmouseX, pmouseY rotateY3D(DeltaMX) rotateX3D(DeltaMY) } } return   ; HotKey Rotate around Z-Axis ---------------------------------- !RButton:: MouseGetPos, pmouseX, pmouseY while GetKeyState("Rbutton", "P") { MouseGetPos, mouseX, mouseY DeltaMX := mouseX - pmouseX DeltaMY := mouseY - pmouseY DeltaMX *= mouseY < deltaY ? mouseStep : -mouseStep DeltaMY *= mouseX > deltaX ? mouseStep : -mouseStep if (DeltaMX || DeltaMY) { MouseGetPos, pmouseX, pmouseY rotateZ3D(DeltaMX) rotateZ3D(DeltaMY) } } return   ; HotKey, Move ------------------------------------------------- +LButton:: MouseGetPos, pmouseX, pmouseY while GetKeyState("Lbutton", "P") { MouseGetPos, mouseX, mouseY deltaX += mouseX - pmouseX deltaY += mouseY - pmouseY pmouseX := mouseX pmouseY := mouseY Redraw() } return   ; --------------------------------------------------------------- ^esc:: Exit: gdip2() Gdip_Shutdown(pToken) ExitApp Return ; ---------------------------------------------------------------
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() a := [[1,2,3],[4,5,6],[7,8,9]] b := [[9,8,7],[6,5,4],[3,2,1]] showMat(" a: ",a) showMat(" b: ",b) showMat("a+b: ",mmop("+",a,b)) showMat("a-b: ",mmop("-",a,b)) showMat("a*b: ",mmop("*",a,b)) showMat("a/b: ",mmop("/",a,b)) showMat("a^b: ",mmop("^",a,b)) showMat("a+2: ",msop("+",a,2)) showMat("a-2: ",msop("-",a,2)) showMat("a*2: ",msop("*",a,2)) showMat("a/2: ",msop("/",a,2)) showMat("a^2: ",msop("^",a,2)) end   procedure mmop(op,A,B) if (*A = *B) & (*A[1] = *B[1]) then { C := [: |list(*A[1])\*A[1] :] a1 := create !!A b1 := create !!B every (!!C) := op(@a1,@b1) return C } end   procedure msop(op,A,s) C := [: |list(*A[1])\*A[1] :] a1 := create !!A every (!!C) := op(@a1,s) return C end   procedure showMat(label, m) every writes(label | right(!!m,5) | "\n") end
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#11l
11l
V colours_in_order = ‘Red White Blue’.split(‘ ’)   F dutch_flag_sort3(items) [String] r L(colour) :colours_in_order r.extend([colour] * items.count(colour)) R r   V balls = [‘Red’, ‘Red’, ‘Blue’, ‘Blue’, ‘Blue’, ‘Red’, ‘Red’, ‘Red’, ‘White’, ‘Blue’] print(‘Original Ball order: ’balls) V sorted_balls = dutch_flag_sort3(balls) print(‘Sorted Ball Order: ’sorted_balls)
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.
#Go
Go
package main   import ( "bufio" "fmt" "log" "os" "strconv" "strings" )   func check(err error) { if err != nil { log.Fatal(err) } }   func main() { scanner := bufio.NewScanner(os.Stdin) n := 0 for n < 1 || n > 5 { fmt.Print("How many integer variables do you want to create (max 5) : ") scanner.Scan() n, _ = strconv.Atoi(scanner.Text()) check(scanner.Err()) } vars := make(map[string]int) fmt.Println("OK, enter the variable names and their values, below") for i := 1; i <= n; { fmt.Println("\n Variable", i) fmt.Print(" Name  : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if _, ok := vars[name]; ok { fmt.Println(" Sorry, you've already created a variable of that name, try again") continue } var value int var err error for { fmt.Print(" Value : ") scanner.Scan() value, err = strconv.Atoi(scanner.Text()) check(scanner.Err()) if err != nil { fmt.Println(" Not a valid integer, try again") } else { break } } vars[name] = value i++ } fmt.Println("\nEnter q to quit") for { fmt.Print("\nWhich variable do you want to inspect : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if s := strings.ToLower(name); s == "q" { return } v, ok := vars[name] if !ok { fmt.Println("Sorry there's no variable of that name, try again") } else { fmt.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
#C
C
  #include<graphics.h>   int main() { initwindow(320,240,"Red Pixel");   putpixel(100,100,RED);   getch();   return 0; }  
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Commodore_BASIC
Commodore BASIC
10 COLOR 0,0,2,2: REM BLACK BACKGROUND AND BORDER, RED TEXT AND EXTRA COLOR 20 GRAPHIC 2:SCNCLR:REM SELECT HI-RES GRAPHICS AND CLEAR THE SCREEN 30 POINT 2,640,640:REM DRAW A POINT AT 640/1024*160,640/1024*160 40 GET K$:IF K$="" THEN 40: REM WAIT FOR KEYPRESS 50 GRAPHIC 0:REM BACK TO TEXT MODE
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
#Groovy
Groovy
class EgyptianDivision { /** * Runs the method and divides 580 by 34 * * @param args not used */ static void main(String[] args) { divide(580, 34) }   /** * Divides <code>dividend</code> by <code>divisor</code> using the Egyptian Division-Algorithm and prints the * result to the console * * @param dividend * @param divisor */ static void divide(int dividend, int divisor) { List<Integer> powersOf2 = new ArrayList<>() List<Integer> doublings = new ArrayList<>()   //populate the powersof2- and doublings-columns int line = 0 while ((Math.pow(2, line) * divisor) <= dividend) { //<- could also be done with a for-loop int powerOf2 = (int) Math.pow(2, line) powersOf2.add(powerOf2) doublings.add(powerOf2 * divisor) line++ }   int answer = 0 int accumulator = 0   //Consider the rows in reverse order of their construction (from back to front of the List<>s) for (int i = powersOf2.size() - 1; i >= 0; i--) { if (accumulator + doublings.get(i) <= dividend) { accumulator += doublings.get(i) answer += powersOf2.get(i) } }   println(String.format("%d, remainder %d", answer, dividend - accumulator)) } }
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#Java
Java
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.Collections; import java.util.List;   public class EgyptianFractions { private static BigInteger gcd(BigInteger a, BigInteger b) { if (b.equals(BigInteger.ZERO)) { return a; } return gcd(b, a.mod(b)); }   private static class Frac implements Comparable<Frac> { private BigInteger num, denom;   public Frac(BigInteger n, BigInteger d) { if (d.equals(BigInteger.ZERO)) { throw new IllegalArgumentException("Parameter d may not be zero."); }   BigInteger nn = n; BigInteger dd = d; if (nn.equals(BigInteger.ZERO)) { dd = BigInteger.ONE; } else if (dd.compareTo(BigInteger.ZERO) < 0) { nn = nn.negate(); dd = dd.negate(); } BigInteger g = gcd(nn, dd).abs(); if (g.compareTo(BigInteger.ZERO) > 0) { nn = nn.divide(g); dd = dd.divide(g); } num = nn; denom = dd; }   public Frac(int n, int d) { this(BigInteger.valueOf(n), BigInteger.valueOf(d)); }   public Frac plus(Frac rhs) { return new Frac( num.multiply(rhs.denom).add(denom.multiply(rhs.num)), rhs.denom.multiply(denom) ); }   public Frac unaryMinus() { return new Frac(num.negate(), denom); }   public Frac minus(Frac rhs) { return plus(rhs.unaryMinus()); }   @Override public int compareTo(Frac rhs) { BigDecimal diff = this.toBigDecimal().subtract(rhs.toBigDecimal()); if (diff.compareTo(BigDecimal.ZERO) < 0) { return -1; } if (BigDecimal.ZERO.compareTo(diff) < 0) { return 1; } return 0; }   @Override public boolean equals(Object obj) { if (null == obj || !(obj instanceof Frac)) { return false; } Frac rhs = (Frac) obj; return compareTo(rhs) == 0; }   @Override public String toString() { if (denom.equals(BigInteger.ONE)) { return num.toString(); } return String.format("%s/%s", num, denom); }   public BigDecimal toBigDecimal() { BigDecimal bdn = new BigDecimal(num); BigDecimal bdd = new BigDecimal(denom); return bdn.divide(bdd, MathContext.DECIMAL128); }   public List<Frac> toEgyptian() { if (num.equals(BigInteger.ZERO)) { return Collections.singletonList(this); } List<Frac> fracs = new ArrayList<>(); if (num.abs().compareTo(denom.abs()) >= 0) { Frac div = new Frac(num.divide(denom), BigInteger.ONE); Frac rem = this.minus(div); fracs.add(div); toEgyptian(rem.num, rem.denom, fracs); } else { toEgyptian(num, denom, fracs); } return fracs; }   public void toEgyptian(BigInteger n, BigInteger d, List<Frac> fracs) { if (n.equals(BigInteger.ZERO)) { return; } BigDecimal n2 = new BigDecimal(n); BigDecimal d2 = new BigDecimal(d); BigDecimal[] divRem = d2.divideAndRemainder(n2, MathContext.UNLIMITED); BigInteger div = divRem[0].toBigInteger(); if (divRem[1].compareTo(BigDecimal.ZERO) > 0) { div = div.add(BigInteger.ONE); } fracs.add(new Frac(BigInteger.ONE, div)); BigInteger n3 = d.negate().mod(n); if (n3.compareTo(BigInteger.ZERO) < 0) { n3 = n3.add(n); } BigInteger d3 = d.multiply(div); Frac f = new Frac(n3, d3); if (f.num.equals(BigInteger.ONE)) { fracs.add(f); return; } toEgyptian(f.num, f.denom, fracs); } }   public static void main(String[] args) { List<Frac> fracs = List.of( new Frac(43, 48), new Frac(5, 121), new Frac(2014, 59) ); for (Frac frac : fracs) { List<Frac> list = frac.toEgyptian(); Frac first = list.get(0); if (first.denom.equals(BigInteger.ONE)) { System.out.printf("%s -> [%s] + ", frac, first); } else { System.out.printf("%s -> %s", frac, first); } for (int i = 1; i < list.size(); ++i) { System.out.printf(" + %s", list.get(i)); } System.out.println(); }   for (Integer r : List.of(98, 998)) { if (r == 98) { System.out.println("\nFor proper fractions with 1 or 2 digits:"); } else { System.out.println("\nFor proper fractions with 1, 2 or 3 digits:"); }   int maxSize = 0; List<Frac> maxSizeFracs = new ArrayList<>(); BigInteger maxDen = BigInteger.ZERO; List<Frac> maxDenFracs = new ArrayList<>(); boolean[][] sieve = new boolean[r + 1][]; for (int i = 0; i < r + 1; ++i) { sieve[i] = new boolean[r + 2]; } for (int i = 1; i < r; ++i) { for (int j = i + 1; j < r + 1; ++j) { if (sieve[i][j]) continue; Frac f = new Frac(i, j); List<Frac> list = f.toEgyptian(); int listSize = list.size(); if (listSize > maxSize) { maxSize = listSize; maxSizeFracs.clear(); maxSizeFracs.add(f); } else if (listSize == maxSize) { maxSizeFracs.add(f); } BigInteger listDen = list.get(list.size() - 1).denom; if (listDen.compareTo(maxDen) > 0) { maxDen = listDen; maxDenFracs.clear(); maxDenFracs.add(f); } else if (listDen.equals(maxDen)) { maxDenFracs.add(f); } if (i < r / 2) { int k = 2; while (true) { if (j * k > r + 1) break; sieve[i * k][j * k] = true; k++; } } } } System.out.printf(" largest number of items = %s\n", maxSize); System.out.printf("fraction(s) with this number : %s\n", maxSizeFracs); String md = maxDen.toString(); System.out.printf(" largest denominator = %s digits, ", md.length()); System.out.printf("%s...%s\n", md.substring(0, 20), md.substring(md.length() - 20, md.length())); System.out.printf("fraction(s) with this denominator : %s\n", maxDenFracs); } } }
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Scala
Scala
  def ethiopian(i:Int, j:Int):Int= pairIterator(i,j).filter(x=> !isEven(x._1)).map(x=>x._2).foldLeft(0){(x,y)=>x+y}   def ethiopian2(i:Int, j:Int):Int= pairIterator(i,j).map(x=>if(isEven(x._1)) 0 else x._2).foldLeft(0){(x,y)=>x+y}   def ethiopian3(i:Int, j:Int):Int= { var res=0; for((h,d) <- pairIterator(i,j) if !isEven(h)) res+=d; res }   def ethiopian4(i: Int, j: Int): Int = if (i == 1) j else ethiopian(halve(i), double(j)) + (if (isEven(i)) 0 else j)   def isEven(x:Int)=(x&1)==0 def halve(x:Int)=x>>>1 def double(x:Int)=x<<1   // generates pairs of values (halve,double) def pairIterator(x:Int, y:Int)=new Iterator[(Int, Int)] { var i=(x, y) def hasNext=i._1>0 def next={val r=i; i=(halve(i._1), double(i._2)); r} }  
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)
#Nim
Nim
import bitops   const Size = 32 LastBit = Size - 1 Lines = Size div 2 Rule = 90   type State = int # State is represented as an int and will be used as a bit string.   #---------------------------------------------------------------------------------------------------   template bitVal(state: State; n: typed): int = ## Return the value of a bit as an int rather than a bool. ord(state.testBit(n))   #---------------------------------------------------------------------------------------------------   proc ruleTest(x: int): bool = ## Return true if a bit must be set. (Rule and 1 shl (7 and x)) != 0   #---------------------------------------------------------------------------------------------------   proc evolve(state: var State) = ## Compute next state.   var newState: State # All bits cleared by default. if ruleTest(state.bitVal(0) shl 2 or state.bitVal(LastBit) shl 1 or state.bitVal(LastBit-1)): newState.setBit(LastBit) if ruleTest(state.bitVal(1) shl 2 or state.bitVal(0) shl 1 or state.bitVal(LastBit)): newState.setBit(0) for i in 1..<LastBit: if ruleTest(state.bitVal(i + 1) shl 2 or state.bitVal(i) shl 1 or state.bitVal(i - 1)): newState.setBit(i) state = newState   #---------------------------------------------------------------------------------------------------   proc show(state: State) = ## Show the current state. for i in countdown(LastBit, 0): stdout.write if state.testbit(i): '*' else: ' ' echo ""   #———————————————————————————————————————————————————————————————————————————————————————————————————   var state: State state.setBit(Lines) echo "Rule ", Rule for _ in 1..Lines: show(state) evolve(state)
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)
#Octave
Octave
clear all E=200; idx=round(E/2); z(1:1:E^2)=0; % init lattice z(idx)=1; % seed apex of triangle with a single cell A=2; % Number of bits-1 rule30 uses 3 so A=2 for n=1:1:E^2/2-E-2; % n=lines theta=0; % theta for a=0:1:A; theta=theta+2^a*z(n+A-a); endfor x=(asin(sin (pi/4*(theta-3/4)))); z(n+E+1)=round( (4*x+pi)/(2*pi) ); endfor imagesc(reshape(z,E,E)'); % Medland map  
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
#VBScript
VBScript
Dim lookupTable(170), returnTable(170), currentPosition, input currentPosition = 0   Do While True input = InputBox("Please type a number (-1 to quit):") MsgBox "The factorial of " & input & " is " & factorial(CDbl(input)) Loop   Function factorial (x) If x = -1 Then WScript.Quit 0 End If Dim temp temp = lookup(x) If x <= 1 Then factorial = 1 ElseIf temp <> 0 Then factorial = temp Else temp = factorial(x - 1) * x store x, temp factorial = temp End If End Function   Function lookup (x) Dim i For i = 0 To currentPosition - 1 If lookupTable(i) = x Then lookup = returnTable(i) Exit Function End If Next lookup = 0 End Function   Function store (x, y) lookupTable(currentPosition) = x returnTable(currentPosition) = y currentPosition = currentPosition + 1 End Function
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.
#Nim
Nim
import asyncnet, asyncdispatch   proc processClient(client: AsyncSocket) {.async.} = while true: let line = await client.recvLine() await client.send(line & "\c\L")   proc serve() {.async.} = var server = newAsyncSocket() server.bindAddr(Port(12321)) server.listen()   while true: let client = await server.accept() echo "Accepting connection from client", client.getLocalAddr[0] discard processClient(client)   discard serve() runForever()
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Wren
Wren
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#X86_Assembly
X86 Assembly
section .text global _start   _start: mov eax, 1 int 0x80 ret
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#XPL0
XPL0
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#XQuery
XQuery
.
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.
#Groovy
Groovy
class Main { private static class Range { int start int end boolean print   Range(int s, int e, boolean p) { start = s end = e print = p } }   static void main(String[] args) { List<Range> rgs = Arrays.asList( 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) { println("eban numbers up to and including $rg.end") } else { println("eban numbers between $rg.start and $rg.end") } int count = 0 for (int i = rg.start; i <= rg.end; ++i) { int b = (int) (i / 1_000_000_000) int r = i % 1_000_000_000 int m = (int) (r / 1_000_000) r = i % 1_000_000 int t = (int) (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) { print("$i ") } count++ } } } } } if (rg.print) { println() } println("count = $count") println() } } }
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related tasks Draw a cuboid write language name in 3D ASCII
#BASIC256
BASIC256
global escala global tam global zoff global cylr   escala = 50 tam = 320 zoff = 0.5773502691896257645091487805019574556 cylr = 1.6329931618554520654648560498039275946   clg graphsize tam, tam   dim x(6) theta = 0.0 dtheta = 1.5 dt = 1.0 / 30 dim cylphi = {PI/6, 5*PI/6, 3*PI/2, 11*PI/6, PI/2, 7*PI/6}   while key = "" lasttime = msec for i = 0 to 5 x[i] = tam/2 + escala *cylr * cos(cylphi[i] + theta) next i clg call drawcube(x)   while msec < lasttime + dt end while theta += dtheta*(msec-lasttime) pause .4 call drawcube(x) end while   subroutine drawcube(x) for i = 0 to 2 color rgb(0,0,0) #black line tam/2, tam/2 - escala / zoff, x[i], tam/2 - escala * zoff line tam/2, tam/2 + escala / zoff, x[5-i], tam/2 + escala * zoff line x[i], tam/2 - escala * zoff, x[(i % 3) + 3], tam/2 + escala * zoff line x[i], tam/2 - escala * zoff, x[((i+1)%3) + 3], tam/2 + escala * zoff next i end subroutine
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.
#J
J
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/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)
#ABAP
ABAP
  report z_dutch_national_flag_problem.   interface sorting_problem. methods: generate_unsorted_sequence importing lenght_of_sequence type int4 returning value(unsorted_sequence) type string,   sort_sequence changing sequence_to_be_sorted type string,   is_sorted importing sequence_to_check type string returning value(sorted) type abap_bool. endinterface.     class dutch_national_flag_problem definition. public section. interfaces: sorting_problem.     constants: begin of dutch_flag_colors, red type char1 value 'R', white type char1 value 'W', blue type char1 value 'B', end of dutch_flag_colors. endclass.     class dutch_national_flag_problem implementation. method sorting_problem~generate_unsorted_sequence. data(random_int_generator) = cl_abap_random_int=>create( seed = cl_abap_random=>seed( ) min = 0 max = 2 ).   do lenght_of_sequence - 1 times. data(random_int) = random_int_generator->get_next( ).   data(next_color) = cond char1( when random_int eq 0 then dutch_flag_colors-red when random_int eq 1 then dutch_flag_colors-white when random_int eq 2 then dutch_flag_colors-blue ).   unsorted_sequence = |{ unsorted_sequence }{ next_color }|. enddo.   if strlen( unsorted_sequence ) > 0. random_int = random_int_generator->get_next( ).   next_color = cond char1( when random_int eq 0 or random_int eq 2 then dutch_flag_colors-red when random_int eq 1 then dutch_flag_colors-white ).   unsorted_sequence = |{ unsorted_sequence }{ next_color }|. endif. endmethod.     method sorting_problem~sort_sequence. data(low_index) = 0. data(middle_index) = 0. data(high_index) = strlen( sequence_to_be_sorted ) - 1.   while middle_index <= high_index. data(current_color) = sequence_to_be_sorted+middle_index(1).   if current_color eq dutch_flag_colors-red. data(buffer) = sequence_to_be_sorted+low_index(1).   sequence_to_be_sorted = replace( val = sequence_to_be_sorted off = middle_index len = 1 with = buffer ).   sequence_to_be_sorted = replace( val = sequence_to_be_sorted off = low_index len = 1 with = current_color ).   low_index = low_index + 1.   middle_index = middle_index + 1. elseif current_color eq dutch_flag_colors-blue. buffer = sequence_to_be_sorted+high_index(1).   sequence_to_be_sorted = replace( val = sequence_to_be_sorted off = middle_index len = 1 with = buffer ).   sequence_to_be_sorted = replace( val = sequence_to_be_sorted off = high_index len = 1 with = current_color ).   high_index = high_index - 1. else. middle_index = middle_index + 1. endif. endwhile. endmethod.     method sorting_problem~is_sorted. sorted = abap_true.   do strlen( sequence_to_check ) - 1 times. data(current_character_index) = sy-index - 1. data(current_color) = sequence_to_check+current_character_index(1). data(next_color) = sequence_to_check+sy-index(1).   sorted = cond abap_bool( when ( current_color eq dutch_flag_colors-red and ( next_color eq current_color or next_color eq dutch_flag_colors-white or next_color eq dutch_flag_colors-blue ) ) or ( current_color eq dutch_flag_colors-white and ( next_color eq current_color or next_color eq dutch_flag_colors-blue ) ) or ( current_color eq dutch_flag_colors-blue and current_color eq next_color ) then sorted else abap_false ).   check sorted eq abap_false. return. enddo. endmethod. endclass.     start-of-selection. data dutch_national_flag_problem type ref to sorting_problem.   dutch_national_flag_problem = new dutch_national_flag_problem( ).   data(sequence) = dutch_national_flag_problem->generate_unsorted_sequence( 20 ).   write:|{ sequence }, is sorted? -> { dutch_national_flag_problem->is_sorted( sequence ) }|, /.   dutch_national_flag_problem->sort_sequence( changing sequence_to_be_sorted = sequence ).   write:|{ sequence }, is sorted? -> { dutch_national_flag_problem->is_sorted( sequence ) }|, /.  
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.
#Groovy
Groovy
def varname = 'foo' def value = 42   new GroovyShell(this.binding).evaluate("${varname} = ${value}")   assert foo == 42
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Haskell
Haskell
data Var a = Var String a deriving Show main = do putStrLn "please enter you variable name" vName <- getLine let var = Var vName 42 putStrLn $ "this is your variable: " ++ show var
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
#Delphi
Delphi
  program Draw_a_pixel;   {$APPTYPE CONSOLE}   {$R *.res}   uses Windows, Messages, SysUtils;   var Msg: TMSG; LWndClass: TWndClass; hMainHandle: HWND;   procedure Paint(Handle: hWnd); forward;   procedure ReleaseResources; begin PostQuitMessage(0); end;   function WindowProc(hWnd, Msg: Longint; wParam: wParam; lParam: lParam): Longint; stdcall; begin case Msg of WM_PAINT: Paint(hWnd); WM_DESTROY: ReleaseResources; end; Result := DefWindowProc(hWnd, Msg, wParam, lParam); end;     procedure CreateWin(W, H: Integer); begin LWndClass.hInstance := hInstance; with LWndClass do begin lpszClassName := 'OneRedPixel'; Style := CS_PARENTDC or CS_BYTEALIGNCLIENT; hIcon := LoadIcon(hInstance, 'MAINICON'); lpfnWndProc := @WindowProc; hbrBackground := COLOR_BTNFACE + 1; hCursor := LoadCursor(0, IDC_ARROW); end;   RegisterClass(LWndClass); hMainHandle := CreateWindow(LWndClass.lpszClassName, 'Draw a red pixel on (100,100)', WS_CAPTION or WS_MINIMIZEBOX or WS_SYSMENU or WS_VISIBLE, ((GetSystemMetrics(SM_CXSCREEN) - W) div 2), ((GetSystemMetrics (SM_CYSCREEN) - H) div 2), W, H, 0, 0, hInstance, nil); end;   procedure ShowModal; begin while GetMessage(Msg, 0, 0, 0) do begin TranslateMessage(Msg); DispatchMessage(Msg); end; end;   procedure Paint(Handle: hWnd); var ps: PAINTSTRUCT; Dc: HDC; begin Dc := BeginPaint(Handle, ps);   // Fill bg with white FillRect(Dc, ps.rcPaint, CreateSolidBrush($FFFFFF));   // Do the magic SetPixel(Dc, 100, 100, $FF);   EndPaint(Handle, ps); end;   begin CreateWin(320, 240); ShowModal(); 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
#Haskell
Haskell
import Data.List (unfoldr)   egyptianQuotRem :: Integer -> Integer -> (Integer, Integer) egyptianQuotRem m n = let expansion (i, x) | x > m = Nothing | otherwise = Just ((i, x), (i + i, x + x)) collapse (i, x) (q, r) | x < r = (q + i, r - x) | otherwise = (q, r) in foldr collapse (0, m) $ unfoldr expansion (1, n)   main :: IO () main = print $ egyptianQuotRem 580 34
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#Julia
Julia
struct EgyptianFraction{T<:Integer} <: Real int::T frac::NTuple{N,Rational{T}} where N end   Base.show(io::IO, ef::EgyptianFraction) = println(io, "[", ef.int, "] ", join(ef.frac, " + ")) Base.length(ef::EgyptianFraction) = !iszero(ef.int) + length(ef.frac) function Base.convert(::Type{EgyptianFraction{T}}, fr::Rational) where T fr, int::T = modf(fr) fractions = Vector{Rational{T}}(0) x::T, y::T = numerator(fr), denominator(fr) iszero(x) && return EgyptianFraction{T}(int, (x // y,)) while x != one(x) push!(fractions, one(T) // cld(y, x)) x, y = mod1(-y, x), y * cld(y, x) d = gcd(x, y) x ÷= d y ÷= d end push!(fractions, x // y) return EgyptianFraction{T}(int, tuple(fractions...)) end Base.convert(::Type{EgyptianFraction}, fr::Rational{T}) where T = convert(EgyptianFraction{T}, fr) Base.convert(::Type{EgyptianFraction{T}}, fr::EgyptianFraction) where T = EgyptianFraction{T}(convert(T, fr.int), convert.(Rational{T}, fr.frac)) Base.convert(::Type{Rational{T}}, fr::EgyptianFraction) where T = T(fr.int) + sum(convert.(Rational{T}, fr.frac)) Base.convert(::Type{Rational}, fr::EgyptianFraction{T}) where T = convert(Rational{T}, fr)   @show EgyptianFraction(43 // 48) @show EgyptianFraction{BigInt}(5 // 121) @show EgyptianFraction(2014 // 59)   function task(fractions::AbstractVector) fracs = convert(Vector{EgyptianFraction{BigInt}}, fractions) local frlenmax::EgyptianFraction{BigInt} local lenmax = 0 local frdenmax::EgyptianFraction{BigInt} local denmax = 0 for f in fracs if length(f) ≥ lenmax lenmax = length(f) frlenmax = f end if denominator(last(f.frac)) ≥ denmax denmax = denominator(last(f.frac)) frdenmax = f end end return frlenmax, lenmax, frdenmax, denmax end   fr = collect((x // y) for x in 1:100 for y in 1:100 if x != y) |> unique frlenmax, lenmax, frdenmax, denmax = task(fr) println("Longest fraction, with length $lenmax: \n", Rational(frlenmax), "\n = ", frlenmax) println("Fraction with greatest denominator\n(that is $denmax):\n", Rational(frdenmax), "\n = ", frdenmax)   println("\n# For 1 digit-integers:") fr = collect((x // y) for x in 1:10 for y in 1:10 if x != y) |> unique frlenmax, lenmax, frdenmax, denmax = task(fr) println("Longest fraction, with length $lenmax: \n", Rational(frlenmax), "\n = ", frlenmax) println("Fraction with greatest denominator\n(that is $denmax):\n", Rational(frdenmax), "\n = ", frdenmax)   println("# For 3 digit-integers:") fr = collect((x // y) for x in 1:1000 for y in 1:1000 if x != y) |> unique frlenmax, lenmax, frdenmax, denmax = task(fr) println("Longest fraction, with length $lenmax: \n", Rational(frlenmax), "\n = ", frlenmax) println("Fraction with greatest denominator\n(that is $denmax):\n", Rational(frdenmax), "\n = ", frdenmax)
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
#Scheme
Scheme
(define (halve num) (quotient num 2))   (define (double num) (* num 2))   (define (*mul-eth plier plicand acc) (cond ((zero? plier) acc) ((even? plier) (*mul-eth (halve plier) (double plicand) acc)) (else (*mul-eth (halve plier) (double plicand) (+ acc plicand)))))   (define (mul-eth plier plicand) (*mul-eth plier plicand 0))   (display (mul-eth 17 34)) (newline)
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)
#Perl
Perl
use strict; use warnings;   package Automaton { sub new { my $class = shift; my $rule = [ reverse split //, sprintf "%08b", shift ]; return bless { rule => $rule, cells => [ @_ ] }, $class; } sub next { my $this = shift; my @previous = @{$this->{cells}}; $this->{cells} = [ @{$this->{rule}}[ map { 4*$previous[($_ - 1) % @previous] + 2*$previous[$_] + $previous[($_ + 1) % @previous] } 0 .. @previous - 1 ] ]; return $this; } use overload q{""} => sub { my $this = shift; join '', map { $_ ? '#' : ' ' } @{$this->{cells}} }; }   my @a = map 0, 1 .. 91; $a[45] = 1; my $a = Automaton->new(90, @a);   for (1..40) { print "|$a|\n"; $a->next; }
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
#Verbexx
Verbexx
// ---------------- // recursive method (requires INTV_T input parm) // ----------------   fact_r @FN [n] { @CASE when:(n < 0iv) {-1iv } when:(n == 0iv) { 1iv } else: { n * (@fact_r n-1iv) } };     // ---------------- // iterative method (requires INTV_T input parm) // ----------------   fact_i @FN [n] { @CASE when:(n < 0iv) {-1iv } when:(n == 0iv) { 1iv } else: { @VAR i fact = 1iv 1iv; @LOOP while:(i <= n) { fact *= i++ }; } };     // ------------------ // Display factorials // ------------------   @VAR i = -1iv; @LOOP times:15 { @SAY «recursive  » i «! = » (@fact_r i) between:""; @SAY «iterative  » i «! = » (@fact_i i) between:"";   i = 5iv * i / 4iv + 1iv; };     /]=========================================================================================   Output:   recursive -1! = -1 iterative -1! = -1 recursive 0! = 1 iterative 0! = 1 recursive 1! = 1 iterative 1! = 1 recursive 2! = 2 iterative 2! = 2 recursive 3! = 6 iterative 3! = 6 recursive 4! = 24 iterative 4! = 24 recursive 6! = 720 iterative 6! = 720 recursive 8! = 40320 iterative 8! = 40320 recursive 11! = 39916800 iterative 11! = 39916800 recursive 14! = 87178291200 iterative 14! = 87178291200 recursive 18! = 6402373705728000 iterative 18! = 6402373705728000 recursive 23! = 25852016738884976640000 iterative 23! = 25852016738884976640000 recursive 29! = 8841761993739701954543616000000 iterative 29! = 8841761993739701954543616000000 recursive 37! = 13763753091226345046315979581580902400000000 iterative 37! = 13763753091226345046315979581580902400000000 recursive 47! = 258623241511168180642964355153611979969197632389120000000000 iterative 47! = 258623241511168180642964355153611979969197632389120000000000
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.
#Objeck
Objeck
  use Net; use Concurrency;   bundle Default { class SocketServer { id : static : Int;   function : Main(args : String[]) ~ Nil { server := TCPSocketServer->New(12321); if(server->Listen(5)) { while(true) { client := server->Accept(); service := Service->New(id->ToString()); service->Execute(client); id += 1; }; }; server->Close(); } }   class Service from Thread { New(name : String) { Parent(name); }   method : public : Run(param : Base) ~ Nil { client := param->As(TCPSocket); line := client->ReadString(); while(line->Size() > 0) { line->PrintLine(); line := client->ReadString(); }; } } }  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#XSLT
XSLT
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <!-- code goes here --> </xsl:stylesheet>
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#xTalk
xTalk
on startup end startup
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#XUL
XUL
  <?xml version="1.0"?>  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Yabasic
Yabasic
 
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.
#Haskell
Haskell
{-# LANGUAGE NumericUnderscores #-} import Data.List (intercalate) import Text.Printf (printf) import Data.List.Split (chunksOf)   isEban :: Int -> Bool isEban n = all (`elem` [0, 2, 4, 6]) z where (b, r1) = n `quotRem` (10 ^ 9) (m, r2) = r1 `quotRem` (10 ^ 6) (t, r3) = r2 `quotRem` (10 ^ 3) z = b : map (\x -> if x >= 30 && x <= 66 then x `mod` 10 else x) [m, t, r3]   ebans = map f where f x = (thousands x, thousands $ length $ filter isEban [1..x])   thousands:: Int -> String thousands = reverse . intercalate "," . chunksOf 3 . reverse . show   main :: IO () main = do uncurry (printf "eban numbers up to and including 1000: %2s\n%s\n\n") $ r [1..1000] uncurry (printf "eban numbers between 1000 and 4000: %2s\n%s\n\n") $ r [1000..4000] mapM_ (uncurry (printf "eban numbers up and including %13s: %5s\n")) ebanCounts where ebanCounts = ebans [ 10_000 , 100_000 , 1_000_000 , 10_000_000 , 100_000_000 , 1_000_000_000 ] r = ((,) <$> thousands . length <*> show) . filter isEban
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
#C
C
  #include<gl/freeglut.h>   double rot = 0; float matCol[] = {1,0,0,0};   void display(){ glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glPushMatrix(); glRotatef(30,1,1,0); glRotatef(rot,0,1,1); glMaterialfv(GL_FRONT,GL_DIFFUSE,matCol); glutWireCube(1); glPopMatrix(); glFlush(); }     void onIdle(){ rot += 0.1; glutPostRedisplay(); }   void reshape(int w,int h){ float ar = (float) w / (float) h ;   glViewport(0,0,(GLsizei)w,(GLsizei)h); glTranslatef(0,0,-10); glMatrixMode(GL_PROJECTION); gluPerspective(70,(GLfloat)w/(GLfloat)h,1,12); glLoadIdentity(); glFrustum ( -1.0, 1.0, -1.0, 1.0, 10.0, 100.0 ) ; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); }   void init(){ float pos[] = {1,1,1,0}; float white[] = {1,1,1,0}; float shini[] = {70};   glClearColor(.5,.5,.5,0); glShadeModel(GL_SMOOTH); glLightfv(GL_LIGHT0,GL_AMBIENT,white); glLightfv(GL_LIGHT0,GL_DIFFUSE,white); glMaterialfv(GL_FRONT,GL_SHININESS,shini); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); }   int main(int argC, char* argV[]) { glutInit(&argC,argV); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH); glutInitWindowSize(600,500); glutCreateWindow("Rossetta's Rotating Cube"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutIdleFunc(onIdle); glutMainLoop(); return 0; }  
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Java
Java
  import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; import java.util.stream.Stream;   @SuppressWarnings("serial") public class ElementWiseOp { static final Map<String, BiFunction<Double, Double, Double>> OPERATIONS = new HashMap<String, BiFunction<Double, Double, Double>>() { { put("add", (a, b) -> a + b); put("sub", (a, b) -> a - b); put("mul", (a, b) -> a * b); put("div", (a, b) -> a / b); put("pow", (a, b) -> Math.pow(a, b)); put("mod", (a, b) -> a % b); } }; public static Double[][] scalarOp(String op, Double[][] matr, Double scalar) { BiFunction<Double, Double, Double> operation = OPERATIONS.getOrDefault(op, (a, b) -> a); Double[][] result = new Double[matr.length][matr[0].length]; for (int i = 0; i < matr.length; i++) { for (int j = 0; j < matr[i].length; j++) { result[i][j] = operation.apply(matr[i][j], scalar); } } return result; } public static Double[][] matrOp(String op, Double[][] matr, Double[][] scalar) { BiFunction<Double, Double, Double> operation = OPERATIONS.getOrDefault(op, (a, b) -> a); Double[][] result = new Double[matr.length][Stream.of(matr).mapToInt(a -> a.length).max().getAsInt()]; for (int i = 0; i < matr.length; i++) { for (int j = 0; j < matr[i].length; j++) { result[i][j] = operation.apply(matr[i][j], scalar[i % scalar.length][j % scalar[i % scalar.length].length]); } } return result; } public static void printMatrix(Double[][] matr) { Stream.of(matr).map(Arrays::toString).forEach(System.out::println); } public static void main(String[] args) { printMatrix(scalarOp("mul", new Double[][] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } }, 3.0));   printMatrix(matrOp("div", new Double[][] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } }, new Double[][] { { 1.0, 2.0}, { 3.0, 4.0} })); } }  
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)
#Action.21
Action!
INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit   PROC PrintArray(BYTE ARRAY a BYTE len) CHAR ARRAY colors(3)=['R 'W 'B] BYTE i,index   FOR i=0 TO len-1 DO index=a(i) Put(colors(index)) OD RETURN   BYTE FUNC IsSorted(BYTE ARRAY a BYTE len) BYTE i   IF len<=1 THEN RETURN (1) FI FOR i=0 TO len-2 DO IF a(i)>a(i+1) THEN RETURN (0) FI OD RETURN (1)   PROC Randomize(BYTE ARRAY a BYTE len) BYTE i   FOR i=0 TO len-1 DO a(i)=Rand(3) OD RETURN   PROC Main() DEFINE SIZE="30" BYTE ARRAY a(SIZE)   Put(125) PutE() ;clear the screen DO Randomize(a,SIZE) UNTIL IsSorted(a,SIZE)=0 OD PrintE("Unsorted:") PrintArray(a,SIZE) PutE() PutE()   SortB(a,SIZE,0) PrintE("Sorted:") PrintArray(a,SIZE) PutE() PutE()   IF IsSorted(a,SIZE) THEN PrintE("Sorting is valid") ELSE PrintE("Sorting is invalid!") FI 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)
#Ada
Ada
with Ada.Text_IO, Ada.Numerics.Discrete_Random, Ada.Command_Line;   procedure Dutch_National_Flag is   type Colour_Type is (Red, White, Blue);   Number: Positive range 2 .. Positive'Last := Positive'Value(Ada.Command_Line.Argument(1)); -- no sorting if the Number of balls is less than 2   type Balls is array(1 .. Number) of Colour_Type;   function Is_Sorted(B: Balls) return Boolean is -- checks if balls are in order begin for I in Balls'First .. Balls'Last-1 loop if B(I) > B(I+1) then return False; end if; end loop; return True; end Is_Sorted;   function Random_Balls return Balls is -- generates an array of random balls, ensuring they are not in order package Random_Colour is new Ada.Numerics.Discrete_Random(Colour_Type); Gen: Random_Colour.Generator; B: Balls; begin Random_Colour.Reset(Gen); loop for I in Balls'Range loop B(I) := Random_Colour.Random(Gen); end loop; exit when (not Is_Sorted(B)); -- ... ensuring they are not in order end loop; return B; end Random_Balls;   procedure Print(Message: String; B: Balls) is begin Ada.Text_IO.Put(Message); for I in B'Range loop Ada.Text_IO.Put(Colour_Type'Image(B(I))); if I < B'Last then Ada.Text_IO.Put(", "); else Ada.Text_IO.New_Line; end if; end loop; end Print;   procedure Sort(Bls: in out Balls) is -- sort Bls in O(1) time   Cnt: array(Colour_Type) of Natural := (Red => 0, White => 0, Blue => 0); Col: Colour_Type;   procedure Move_Colour_To_Top(Bls: in out Balls; Colour: Colour_Type; Start: Positive; Count: Natural) is This: Positive := Start; Tmp: Colour_Type; begin for N in Start .. Start+Count-1 loop while Bls(This) /= Colour loop This := This + 1; end loop; -- This is the first index >= N with B(This) = Colour Tmp := Bls(N); Bls(N) := Bls(This); Bls(This) := Tmp; -- swap This := This + 1; end loop; end Move_Colour_To_Top;   begin for Ball in Balls'Range loop -- count how often each colour is found Col := Bls(Ball); Cnt(Col) := Cnt(Col) + 1; end loop; Move_Colour_To_Top(Bls, Red, Start => 1, Count => Cnt(Red)); Move_Colour_To_Top(Bls, White, Start => 1+Cnt(Red), Count => Cnt(White)); -- all the remaining balls are blue end Sort;   A: Balls := Random_Balls;   begin Print("Original Order: ", A);   pragma Assert(not Is_Sorted(A)); -- Check if A is unsorted   Sort(A); -- A = ((Red**Cnt(Red)= & (White**Cnt(White)) & (Blue**Cnt(Blue)))   pragma Assert(Is_Sorted(A)); -- Check if A is actually sorted   Print("After Sorting: ", A); end Dutch_National_Flag;
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.
#J
J
require 'misc' (prompt 'Enter variable name: ')=: 0
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Java
Java
public static void main(String... args){ HashMap<String, Integer> vars = new HashMap<String, Integer>(); //The variable name is stored as the String. The var type of the variable can be //changed by changing the second data type mentiones. However, it must be an object //or a wrapper class. vars.put("Variable name", 3); //declaration of variables vars.put("Next variable name", 5); Scanner sc = new Scanner(System.in); String str = sc.next(); vars.put(str, sc.nextInt()); //accpeting name and value from user   System.out.println(vars.get("Variable name")); //printing of values System.out.println(vars.get(str)); }  
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
#F.23
F#
open System.Windows.Forms open System.Drawing   let f = new Form() f.Size <- new Size(320,240) f.Paint.Add(fun e -> e.Graphics.FillRectangle(Brushes.Red, 100, 100 ,1,1)) Application.Run(f)
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
#Factor
Factor
USING: accessors arrays images images.testing images.viewer kernel literals math sequences ; IN: rosetta-code.draw-pixel   : draw-pixel ( -- ) B{ 255 0 0 } 100 100 <rgb-image> 320 240 [ 2array >>dim ] [ * ] 2bi [ { 0 0 0 } ] replicate B{ } concat-as >>bitmap [ set-pixel-at ] keep image-window ;   MAIN: draw-pixel
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
#J
J
doublings=:_1 }. (+:@]^:(> {:)^:a: (,~ 1:)) ansacc=: 1 }. (] + [ * {.@[ >: {:@:+)/@([,.doublings) egydiv=: (0,[)+1 _1*ansacc
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
#Java
Java
  import java.util.ArrayList; import java.util.List;   public class EgyptianDivision {   /** * Runs the method and divides 580 by 34 * * @param args not used */ public static void main(String[] args) {   divide(580, 34);   }   /** * Divides <code>dividend</code> by <code>divisor</code> using the Egyptian Division-Algorithm and prints the * result to the console * * @param dividend * @param divisor */ public static void divide(int dividend, int divisor) {   List<Integer> powersOf2 = new ArrayList<>(); List<Integer> doublings = new ArrayList<>();   //populate the powersof2- and doublings-columns int line = 0; while ((Math.pow(2, line) * divisor) <= dividend) { //<- could also be done with a for-loop int powerOf2 = (int) Math.pow(2, line); powersOf2.add(powerOf2); doublings.add(powerOf2 * divisor); line++; }   int answer = 0; int accumulator = 0;   //Consider the rows in reverse order of their construction (from back to front of the List<>s) for (int i = powersOf2.size() - 1; i >= 0; i--) { if (accumulator + doublings.get(i) <= dividend) { accumulator += doublings.get(i); answer += powersOf2.get(i); } }   System.out.println(String.format("%d, remainder %d", answer, dividend - accumulator)); } }    
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#Kotlin
Kotlin
// version 1.2.10   import java.math.BigInteger import java.math.BigDecimal import java.math.MathContext   val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bdZero = BigDecimal.ZERO val context = MathContext.UNLIMITED   fun gcd(a: BigInteger, b: BigInteger): BigInteger = if (b == bigZero) a else gcd(b, a % b)   class Frac : Comparable<Frac> { val num: BigInteger val denom: BigInteger   constructor(n: BigInteger, d: BigInteger) { require(d != bigZero) var nn = n var dd = d if (nn == bigZero) { dd = bigOne } else if (dd < bigZero) { nn = -nn dd = -dd } val g = gcd(nn, dd).abs() if (g > bigOne) { nn /= g dd /= g } num = nn denom = dd }   constructor(n: Int, d: Int) : this(n.toBigInteger(), d.toBigInteger())   operator fun plus(other: Frac) = Frac(num * other.denom + denom * other.num, other.denom * denom)   operator fun unaryMinus() = Frac(-num, denom)   operator fun minus(other: Frac) = this + (-other)   override fun compareTo(other: Frac): Int { val diff = this.toBigDecimal() - other.toBigDecimal() return when { diff < bdZero -> -1 diff > bdZero -> +1 else -> 0 } }   override fun equals(other: Any?): Boolean { if (other == null || other !is Frac) return false return this.compareTo(other) == 0 }   override fun toString() = if (denom == bigOne) "$num" else "$num/$denom"   fun toBigDecimal() = num.toBigDecimal() / denom.toBigDecimal()   fun toEgyptian(): List<Frac> { if (num == bigZero) return listOf(this) val fracs = mutableListOf<Frac>() if (num.abs() >= denom.abs()) { val div = Frac(num / denom, bigOne) val rem = this - div fracs.add(div) toEgyptian(rem.num, rem.denom, fracs) } else { toEgyptian(num, denom, fracs) } return fracs }   private tailrec fun toEgyptian( n: BigInteger, d: BigInteger, fracs: MutableList<Frac> ) { if (n == bigZero) return val n2 = n.toBigDecimal() val d2 = d.toBigDecimal() var divRem = d2.divideAndRemainder(n2, context) var div = divRem[0].toBigInteger() if (divRem[1] > bdZero) div++ fracs.add(Frac(bigOne, div)) var n3 = (-d) % n if (n3 < bigZero) n3 += n val d3 = d * div val f = Frac(n3, d3) if (f.num == bigOne) { fracs.add(f) return } toEgyptian(f.num, f.denom, fracs) } }   fun main(args: Array<String>) { val fracs = listOf(Frac(43, 48), Frac(5, 121), Frac(2014,59)) for (frac in fracs) { val list = frac.toEgyptian() if (list[0].denom == bigOne) { val first = "[${list[0]}]" println("$frac -> $first + ${list.drop(1).joinToString(" + ")}") } else { println("$frac -> ${list.joinToString(" + ")}") } }   for (r in listOf(98, 998)) { if (r == 98) println("\nFor proper fractions with 1 or 2 digits:") else println("\nFor proper fractions with 1, 2 or 3 digits:") var maxSize = 0 var maxSizeFracs = mutableListOf<Frac>() var maxDen = bigZero var maxDenFracs = mutableListOf<Frac>() val sieve = List(r + 1) { BooleanArray(r + 2) } // to eliminate duplicates for (i in 1..r) { for (j in (i + 1)..(r + 1)) { if (sieve[i][j]) continue val f = Frac(i, j) val list = f.toEgyptian() val listSize = list.size if (listSize > maxSize) { maxSize = listSize maxSizeFracs.clear() maxSizeFracs.add(f) } else if (listSize == maxSize) { maxSizeFracs.add(f) } val listDen = list[list.lastIndex].denom if (listDen > maxDen) { maxDen = listDen maxDenFracs.clear() maxDenFracs.add(f) } else if (listDen == maxDen) { maxDenFracs.add(f) } if (i < r / 2) { var k = 2 while (true) { if (j * k > r + 1) break sieve[i * k][j * k] = true k++ } } } } println(" largest number of items = $maxSize") println(" fraction(s) with this number : $maxSizeFracs") val md = maxDen.toString() print(" largest denominator = ${md.length} digits, ") println("${md.take(20)}...${md.takeLast(20)}") println(" fraction(s) with this denominator : $maxDenFracs") } }
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Seed7
Seed7
const proc: double (inout integer: a) is func begin a *:= 2; end func;   const proc: halve (inout integer: a) is func begin a := a div 2; end func;   const func boolean: even (in integer: a) is return not odd(a);   const func integer: peasantMult (in var integer: a, in var integer: b) is func result var integer: result is 0; begin while a <> 0 do if not even(a) then result +:= b; end if; halve(a); double(b); end while; end func;
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)
#Phix
Phix
with javascript_semantics string s = ".........#.........", t = s, r = "........" integer rule = 90, k, l = length(s) for i=1 to 8 do r[i] = iff(mod(rule,2)?'#':'.') rule = floor(rule/2) end for for i=0 to 50 do ?s for j=1 to l do k = (s[iff(j=1?l:j-1)]='#')*4 + (s[ j ]='#')*2 + (s[iff(j=l?1:j+1)]='#')+1 t[j] = r[k] end for s = t end for
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
#Verilog
Verilog
module main;   function automatic [7:0] factorial; input [7:0] i_Num; begin if (i_Num == 1) factorial = 1; else factorial = i_Num * factorial(i_Num-1); end endfunction   initial begin $display("Factorial of 1 = %d", factorial(1)); $display("Factorial of 2 = %d", factorial(2)); $display("Factorial of 3 = %d", factorial(3)); $display("Factorial of 4 = %d", factorial(4)); $display("Factorial of 5 = %d", factorial(5)); end endmodule
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.
#Ol
Ol
  (define (timestamp) (syscall 201 "%c"))   (define (on-accept name fd) (lambda () (print "# " (timestamp) "> we got new visitor: " name)   (let*((ss1 ms1 (clock))) (let loop ((str #null) (stream (force (port->bytestream fd)))) (cond ((null? stream) #false) ((function? stream) (let ((message (list->string (reverse str)))) (print "# " (timestamp) "> client " name " wrote " message) (print-to fd message)) (loop #null (force stream))) (else (loop (cons (car stream) str) (cdr stream))))) (syscall 3 fd) (let*((ss2 ms2 (clock))) (print "# " (timestamp) "> visitor leave us. It takes " (+ (* (- ss2 ss1) 1000) (- ms2 ms1)) "ms.")))))   (define (run port) (let ((socket (syscall 41))) ; bind (let loop ((port port)) (if (not (syscall 49 socket port)) ; bind (loop (+ port 2)) (print "Server binded to " port))) ; listen (if (not (syscall 50 socket)) ; listen (shutdown (print "Can't listen")))   ; accept (let loop () (if (syscall 23 socket) ; select (let ((fd (syscall 43 socket))) ; accept (fork (on-accept (syscall 51 fd) fd)))) (sleep 0) (loop))))   (run 12321)  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Yorick
Yorick
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Z80_Assembly
Z80 Assembly
ret
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Zig
Zig
pub fn main() void {}
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#zkl
zkl
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.
#J
J
  Filter =: (#~`)(`:6)   itemAmend =: (29&< *. <&67)`(,: 10&|)} iseban =: [: *./ 0 2 4 6 e.~ [: itemAmend [: |: (4#1000)&#:     (;~ #) iseban Filter >: i. 1000 ┌──┬─────────────────────────────────────────────────────┐ │19│2 4 6 30 32 34 36 40 42 44 46 50 52 54 56 60 62 64 66│ └──┴─────────────────────────────────────────────────────┘   NB. INPUT are the correct integers, head and tail shown ({. , {:) INPUT =: 1000 + i. 3001 1000 4000   (;~ #) iseban Filter INPUT ┌──┬────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │21│2000 2002 2004 2006 2030 2032 2034 2036 2040 2042 2044 2046 2050 2052 2054 2056 2060 2062 2064 2066 4000│ └──┴────────────────────────────────────────────────────────────────────────────────────────────────────────┘ (, ([: +/ [: iseban [: >: i.))&> 10000 * 10 ^ i. +:2 10000 79 100000 399 1e6 399 1e7 1599  
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
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading;   namespace RotatingCube { public partial class Form1 : Form { double[][] nodes = { new double[] {-1, -1, -1}, new double[] {-1, -1, 1}, new double[] {-1, 1, -1}, new double[] {-1, 1, 1}, new double[] {1, -1, -1}, new double[] {1, -1, 1}, new double[] {1, 1, -1}, new double[] {1, 1, 1} };   int[][] edges = { new int[] {0, 1}, new int[] {1, 3}, new int[] {3, 2}, new int[] {2, 0}, new int[] {4, 5}, new int[] {5, 7}, new int[] {7, 6}, new int[] {6, 4}, new int[] {0, 4}, new int[] {1, 5}, new int[] {2, 6}, new int[] {3, 7}};   public Form1() { Width = Height = 640; StartPosition = FormStartPosition.CenterScreen; SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);   Scale(100, 100, 100); RotateCuboid(Math.PI / 4, Math.Atan(Math.Sqrt(2)));   var timer = new DispatcherTimer(); timer.Tick += (s, e) => { RotateCuboid(Math.PI / 180, 0); Refresh(); }; timer.Interval = new TimeSpan(0, 0, 0, 0, 17); timer.Start(); }   private void RotateCuboid(double angleX, double angleY) { double sinX = Math.Sin(angleX); double cosX = Math.Cos(angleX);   double sinY = Math.Sin(angleY); double cosY = Math.Cos(angleY);   foreach (var node in nodes) { double x = node[0]; double y = node[1]; double z = node[2];   node[0] = x * cosX - z * sinX; node[2] = z * cosX + x * sinX;   z = node[2];   node[1] = y * cosY - z * sinY; node[2] = z * cosY + y * sinY; } }   private void Scale(int v1, int v2, int v3) { foreach (var item in nodes) { item[0] *= v1; item[1] *= v2; item[2] *= v3; } }   protected override void OnPaint(PaintEventArgs args) { var g = args.Graphics; g.SmoothingMode = SmoothingMode.HighQuality; g.Clear(Color.White);   g.TranslateTransform(Width / 2, Height / 2);   foreach (var edge in edges) { double[] xy1 = nodes[edge[0]]; double[] xy2 = nodes[edge[1]]; g.DrawLine(Pens.Black, (int)Math.Round(xy1[0]), (int)Math.Round(xy1[1]), (int)Math.Round(xy2[0]), (int)Math.Round(xy2[1])); }   foreach (var node in nodes) { g.FillEllipse(Brushes.Black, (int)Math.Round(node[0]) - 4, (int)Math.Round(node[1]) - 4, 8, 8); } } } }
http://rosettacode.org/wiki/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.
#jq
jq
# Occurrences of .[0] in "operator" will refer to an element in self, # and occurrences of .[1] will refer to the corresponding element in other. def elementwise( operator; other ): length as $rows | if $rows == 0 then . else . as $self | other as $other | ($self[0]|length) as $cols | reduce range(0; $rows) as $i ([]; reduce range(0; $cols) as $j (.; .[$i][$j] = ([$self[$i][$j], $other[$i][$j]] | operator) ) ) end ;
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... Task Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag. Sort the balls in a way idiomatic to your language. Check the sorted balls are in the order of the Dutch national flag. C.f. Dutch national flag problem Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#ALGOL_68
ALGOL 68
BEGIN # Dutch national flag problem: sort a set of randomly arranged red, white and blue balls into order # # ball sets are represented by STRING items, red by "R", white by "W" and blue by "B" # # returns the balls sorted into red, white and blue order # PROC sort balls = ( STRING balls )STRING: BEGIN [ 1 : ( UPB balls + 1 ) - LWB balls ]CHAR result, white, blue; INT r pos := 0, w pos := 0, b pos := 0; # copy the red balls into the result and split the white and blue # # into separate lists # FOR pos FROM LWB balls TO UPB balls DO CHAR b = balls[ pos ]; IF b = "R" THEN # red ball - add to the result # result[ r pos +:= 1 ] := b ELIF b = "W" THEN # white ball # white[ w pos +:= 1 ] := b ELSE # must be blue # blue[ b pos +:= 1 ] := b FI OD; # add the white balls to the list # IF w pos > 0 THEN # there were some white balls - add them to the result # result[ r pos + 1 : r pos + w pos ] := white[ 1 : w pos ]; r pos +:= w pos FI; # add the blue balls to the list # IF b pos > 0 THEN # there were some blue balls - add them to the end of the result # result[ r pos + 1 : r pos + b pos ] := blue[ 1 : b pos ]; r pos +:= b pos FI; result[ 1 : r pos ] END # sort balls # ; # returns TRUE if balls is sorted, FALSE otherwise # PROC sorted balls = ( STRING balls )BOOL: BEGIN BOOL result := TRUE; FOR i FROM LWB balls + 1 TO UPB balls WHILE result := ( CHAR prev = balls[ i - 1 ]; CHAR curr = balls[ i ]; prev = curr OR ( prev = "R" AND curr = "W" ) OR ( prev = "R" AND curr = "B" ) OR ( prev = "W" AND curr = "B" ) ) DO SKIP OD; result END # sorted balls # ; # constructs an unsorted random string of n balls # PROC random balls = ( INT n )STRING: BEGIN STRING result := n * "?"; WHILE FOR i TO n DO result[ i ] := IF INT r = ENTIER( next random * 3 ) + 1; r = 1 THEN "R" ELIF r = 2 THEN "W" ELSE "B" FI OD; sorted balls( result ) DO SKIP OD; result END # random balls # ; # tests # FOR i FROM 11 BY 3 TO 17 DO STRING balls; balls := random balls( i ); print( ( "before: ", balls, IF sorted balls( balls ) THEN " initially sorted??" ELSE "" FI, newline ) ); balls := sort balls( balls ); print( ( "after: ", balls, IF sorted balls( balls ) THEN "" ELSE " NOT" FI, " sorted", newline ) ) OD END
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. Related tasks draw a sphere draw a rotating cube write language name in 3D ASCII draw a Deathstar
#11l
11l
F cline(n, x, y, cde) print(String(cde[0]).rjust(n + 1)‘’ (cde[1] * (9 * x - 1))‘’ cde[0]‘’ (I cde.len > 2 {String(cde[2]).rjust(y + 1)} E ‘’))   F cuboid(x, y, z) cline(y + 1, x, 0, ‘+-’) L(i) 1 .. y cline(y - i + 1, x, i - 1, ‘/ |’) cline(0, x, y, ‘+-|’) L 0 .. 4 * z - y - 3 cline(0, x, y, ‘| |’) cline(0, x, y, ‘| +’) L(i) (y - 1 .. 0).step(-1) 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.
#JavaScript
JavaScript
var varname = 'foo'; // pretend a user input that var value = 42; eval('var ' + varname + '=' + value);
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.
#jq
jq
"Enter a variable name:", (input as $var | ("Enter a value:" , (input as $value | { ($var) : $value })))