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/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #ALGOL_68 | ALGOL 68 | print( ( 0 ^ 0, newline ) )
|
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #J | J | parse=:parse_parser_
eval=:monad define
'gerund structure'=:y
[email protected]
)
coclass 'parser'
classify=: '$()*/+-'&(((>:@#@[ # 2:) #: 2 ^ i.)&;:)
rules=: ''
patterns=: ,"0 assert 1
addrule=: dyad define
rules=: rules,;:x
patterns=: patterns,+./@classify"1 y
)
'Term' addrule '$()', '0', '+-',: '0'
'Factor' addrule '$()+-', '0', '*/',: '0'
'Parens' addrule '(', '*/+-0', ')',: ')*/+-0$'
rules=: rules,;:'Move'
buildTree=: monad define
words=: ;:'$',y
queue=: classify '$',y
stack=: classify '$$$$'
tokens=: ]&.>i.#words
tree=: ''
while.(#queue)+.6<#stack do.
rule=: rules {~ i.&1 patterns (*./"1)@:(+./"1) .(*."1)4{.stack
rule`:6''
end.
'syntax' assert 1 0 1 1 1 1 -: {:"1 stack
gerund=: literal&.> (<,'%') (I. words=<,'/')} words
gerund;1{tree
)
literal=:monad define ::]
".'t=.',y
5!:1<'t'
)
Term=: Factor=: monad define
stack=: ({.stack),(classify '0'),4}.stack
tree=: ({.tree),(<1 2 3{tree),4}.tree
)
Parens=: monad define
stack=: (1{stack),3}.stack
tree=: (1{tree),3}.tree
)
Move=: monad define
'syntax' assert 0<#queue
stack=: ({:queue),stack
queue=: }:queue
tree=: ({:tokens),tree
tokens=: }:tokens
)
parse=:monad define
tmp=: conew 'parser'
r=: buildTree__tmp y
coerase tmp
r
) |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Nim | Nim | import math
import gintro/[glib, gobject, gtk, gio, cairo]
const
Width = 601
Height = 601
Limit = 12 * math.PI
Origin = (x: float(Width div 2), y: float(Height div 2))
B = floor((Width div 2) / Limit)
#---------------------------------------------------------------------------------------------------
proc draw(area: DrawingArea; context: Context) =
## Draw the spiral.
var theta = 0.0
var delta = 0.01
var (prevx, prevy) = Origin
# Clear the region.
context.moveTo(0, 0)
context.setSource(0.0, 0.0, 0.0)
context.paint()
# Draw the spiral.
context.setSource(1.0, 1.0, 0.0)
context.moveTo(Origin.x, Origin.y)
while theta < Limit:
let r = B * theta
let x = Origin.x + r * cos(theta) # X-coordinate on drawing area.
let y = Origin.y + r * sin(theta) # Y-coordinate on drawing area.
context.lineTo(x, y)
context.stroke()
# Set data for next round.
context.moveTo(x, y)
prevx = x
prevy = y
theta += delta
#---------------------------------------------------------------------------------------------------
proc onDraw(area: DrawingArea; context: Context; data: pointer): bool =
## Callback to draw/redraw the drawing area contents.
area.draw(context)
result = true
#---------------------------------------------------------------------------------------------------
proc activate(app: Application) =
## Activate the application.
let window = app.newApplicationWindow()
window.setSizeRequest(Width, Height)
window.setTitle("Archimedean spiral")
# Create the drawing area.
let area = newDrawingArea()
window.add(area)
# Connect the "draw" event to the callback to draw the spiral.
discard area.connect("draw", ondraw, pointer(nil))
window.showAll()
#———————————————————————————————————————————————————————————————————————————————————————————————————
let app = newApplication(Application, "Rosetta.spiral")
discard app.connect("activate", activate)
discard app.run() |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #PARI.2FGP | PARI/GP |
\\ The Archimedean spiral
\\ ArchiSpiral() - Where: lps is a number of loops, c is a direction 0/1
\\ (counter-clockwise/clockwise). 6/6/16 aev
\\ Note: cartes2() can be found here on
\\ http://rosettacode.org/wiki/Polyspiral#PARI.2FGP page.
ArchiSpiral(size,lps,c=0)={
my(a=.0,ai=.1,r=.0,ri=.1,as=lps*2*Pi,n=as/ai,x,y,vc,vx=List(.0),vy=vx);
if(c<0||c>1, c=0); if(c, ai*=-1);
print(" *** The Archimedean spiral: size=",size," loops=",lps," c=",c);
for(i=1, n, vc=cartes2(r,a); x=vc[1]; y=vc[2];
listput(vx,x); listput(vy,y);
r+=ri; a+=ai;
);\\fend i
plothraw(Vec(vx),Vec(vy));
}
{\\ Executing:
ArchiSpiral(640,5); \\ArchiSpiral1.png
ArchiSpiral(640,5,1); \\ArchiSpiral2.png
}
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Arturo | Arturo | isOpen: map 1..101 => false
loop 1..100 'pass ->
loop (range.step:pass pass 100) 'door [
isOpen\[door]: not? isOpen\[door]
]
loop 1..100 'x ->
if isOpen\[x] [
print ["Door" x "is open."]
] |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. arrays.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 fixed-length-table.
03 fixed-table-elt PIC X OCCURS 5 TIMES.
01 table-length PIC 9(5) VALUE 1.
01 variable-length-table.
03 variable-table-elt PIC X OCCURS 1 TO 5 TIMES
DEPENDING ON table-length.
01 initial-value-area.
03 initial-values.
05 FILLER PIC X(10) VALUE "One".
05 FILLER PIC X(10) VALUE "Two".
05 FILLER PIC X(10) VALUE "Three".
03 initial-value-table REDEFINES initial-values.
05 initial-table-elt PIC X(10) OCCURS 3 TIMES.
01 indexed-table.
03 indexed-elt PIC X OCCURS 5 TIMES
INDEXED BY table-index.
PROCEDURE DIVISION.
*> Assigning the contents of an entire table.
MOVE "12345" TO fixed-length-table
*> Indexing an array (using an index)
MOVE 1 TO table-index
MOVE "1" TO indexed-elt (table-index)
*> Pushing a value into a variable-length table.
ADD 1 TO table-length
MOVE "1" TO variable-table-elt (2)
GOBACK
. |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #J | J | x=: 1j1
y=: 3.14159j1.2
x+y NB. addition
4.14159j2.2
x*y NB. multiplication
1.94159j4.34159
%x NB. inversion
0.5j_0.5
-x NB. negation
_1j_1
+x NB. (complex) conjugation
1j_1
|
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Lingo | Lingo | -- parent script "Frac"
property num
property denom
----------------------------------------
-- @constructor
-- @param {integer} numerator
-- @param {integer} [denominator=1]
----------------------------------------
on new (me, numerator, denominator)
if voidP(denominator) then denominator = 1
if denominator=0 then return VOID -- rule out division by zero
g = me._gcd(numerator, denominator)
if g<>0 then
numerator = numerator/g
denominator = denominator/g
else
numerator = 0
denominator = 1
end if
if denominator<0 then
numerator = -numerator
denominator = -denominator
end if
me.num = numerator
me.denom = denominator
return me
end
----------------------------------------
-- Returns string representation "<num>/<denom>"
-- @return {string}
----------------------------------------
on toString (me)
return me.num&"/"&me.denom
end
----------------------------------------
--
----------------------------------------
on _gcd (me, a, b)
if a = 0 then return b
if b = 0 then return a
if a > b then return me._gcd(b, a mod b)
return me._gcd(a, b mod a)
end |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Nim | Nim | import math
proc agm(a, g: float,delta: float = 1.0e-15): float =
var
aNew: float = 0
aOld: float = a
gOld: float = g
while (abs(aOld - gOld) > delta):
aNew = 0.5 * (aOld + gOld)
gOld = sqrt(aOld * gOld)
aOld = aNew
result = aOld
echo agm(1.0,1.0/sqrt(2.0)) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Oberon-2 | Oberon-2 |
MODULE Agm;
IMPORT
Math := LRealMath,
Out;
CONST
epsilon = 1.0E-15;
PROCEDURE Of*(a,g: LONGREAL): LONGREAL;
VAR
na,ng,og: LONGREAL;
BEGIN
na := a; ng := g;
LOOP
og := ng;
ng := Math.sqrt(na * ng);
na := (na + og) * 0.5;
IF na - ng <= epsilon THEN EXIT END
END;
RETURN ng;
END Of;
BEGIN
Out.LongReal(Of(1,1 / Math.sqrt(2)),0,0);Out.Ln
END Agm.
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #APL | APL | 0*0
1 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #AppleScript | AppleScript | return 0 ^ 0 |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Java | Java | import java.util.Stack;
public class ArithmeticEvaluation {
public interface Expression {
BigRational eval();
}
public enum Parentheses {LEFT}
public enum BinaryOperator {
ADD('+', 1),
SUB('-', 1),
MUL('*', 2),
DIV('/', 2);
public final char symbol;
public final int precedence;
BinaryOperator(char symbol, int precedence) {
this.symbol = symbol;
this.precedence = precedence;
}
public BigRational eval(BigRational leftValue, BigRational rightValue) {
switch (this) {
case ADD:
return leftValue.add(rightValue);
case SUB:
return leftValue.subtract(rightValue);
case MUL:
return leftValue.multiply(rightValue);
case DIV:
return leftValue.divide(rightValue);
}
throw new IllegalStateException();
}
public static BinaryOperator forSymbol(char symbol) {
for (BinaryOperator operator : values()) {
if (operator.symbol == symbol) {
return operator;
}
}
throw new IllegalArgumentException(String.valueOf(symbol));
}
}
public static class Number implements Expression {
private final BigRational number;
public Number(BigRational number) {
this.number = number;
}
@Override
public BigRational eval() {
return number;
}
@Override
public String toString() {
return number.toString();
}
}
public static class BinaryExpression implements Expression {
public final Expression leftOperand;
public final BinaryOperator operator;
public final Expression rightOperand;
public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
@Override
public BigRational eval() {
BigRational leftValue = leftOperand.eval();
BigRational rightValue = rightOperand.eval();
return operator.eval(leftValue, rightValue);
}
@Override
public String toString() {
return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")";
}
}
private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {
Expression rightOperand = operands.pop();
Expression leftOperand = operands.pop();
operands.push(new BinaryExpression(leftOperand, operator, rightOperand));
}
public static Expression parse(String input) {
int curIndex = 0;
boolean afterOperand = false;
Stack<Expression> operands = new Stack<>();
Stack<Object> operators = new Stack<>();
while (curIndex < input.length()) {
int startIndex = curIndex;
char c = input.charAt(curIndex++);
if (Character.isWhitespace(c))
continue;
if (afterOperand) {
if (c == ')') {
Object operator;
while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))
createNewOperand((BinaryOperator) operator, operands);
continue;
}
afterOperand = false;
BinaryOperator operator = BinaryOperator.forSymbol(c);
while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))
createNewOperand((BinaryOperator) operators.pop(), operands);
operators.push(operator);
continue;
}
if (c == '(') {
operators.push(Parentheses.LEFT);
continue;
}
afterOperand = true;
while (curIndex < input.length()) {
c = input.charAt(curIndex);
if (((c < '0') || (c > '9')) && (c != '.'))
break;
curIndex++;
}
operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));
}
while (!operators.isEmpty()) {
Object operator = operators.pop();
if (operator == Parentheses.LEFT)
throw new IllegalArgumentException();
createNewOperand((BinaryOperator) operator, operands);
}
Expression expression = operands.pop();
if (!operands.isEmpty())
throw new IllegalArgumentException();
return expression;
}
public static void main(String[] args) {
String[] testExpressions = {
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-.25"};
for (String testExpression : testExpressions) {
Expression expression = parse(testExpression);
System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval());
}
}
} |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Perl | Perl | use Imager;
use constant PI => 3.14159265;
my ($w, $h) = (400, 400);
my $img = Imager->new(xsize => $w, ysize => $h);
for ($theta = 0; $theta < 52*PI; $theta += 0.025) {
$x = $w/2 + $theta * cos($theta/PI);
$y = $h/2 + $theta * sin($theta/PI);
$img->setpixel(x => $x, y => $y, color => '#FF00FF');
}
$img->write(file => 'Archimedean-spiral.png');
|
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Phix | Phix | --
-- demo\rosetta\Archimedean_spiral.exw
-- ===================================
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
function redraw_cb(Ihandle /*ih*/)
integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE"),
a = 0, b = 5, cx = floor(w/2), cy = floor(h/2)
cdCanvasActivate(cddbuffer)
for deg=0 to 360*7 do
atom rad = deg*PI/180,
r = rad*b + a
integer x = cx + floor(r*cos(rad)),
y = cy + floor(r*sin(rad))
cdCanvasPixel(cddbuffer, x, y, #00FF00)
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
cdCanvasSetForeground(cddbuffer, CD_RED)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupCanvas("RASTERSIZE=500x500") -- initial size
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas,`TITLE="Archimedean spiral"`)
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Astro | Astro | var doors = falses(100)
for a in 1..100: for b in a..a..100:
doors[b] = not doors[b]
for a in 1..100:
print "Door $a is ${(doors[a]) ? 'open.': 'closed.'}"
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #CoffeeScript | CoffeeScript | array1 = []
array1[0] = "Dillenidae"
array1[1] = "animus"
array1[2] = "Kona"
alert "Elements of array1: " + array1 # Dillenidae,animus,Kona
array2 = ["Cepphus", "excreta", "Gansu"]
alert "Value of array2[1]: " + array2[1] # excreta |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Java | Java | public class Complex {
public final double real;
public final double imag;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
real = r;
imag = i;
}
public Complex add(Complex b) {
return new Complex(this.real + b.real, this.imag + b.imag);
}
public Complex mult(Complex b) {
// FOIL of (a+bi)(c+di) with i*i = -1
return new Complex(this.real * b.real - this.imag * b.imag,
this.real * b.imag + this.imag * b.real);
}
public Complex inv() {
// 1/(a+bi) * (a-bi)/(a-bi) = 1/(a+bi) but it's more workable
double denom = real * real + imag * imag;
return new Complex(real / denom, -imag / denom);
}
public Complex neg() {
return new Complex(-real, -imag);
}
public Complex conj() {
return new Complex(real, -imag);
}
@Override
public String toString() {
return real + " + " + imag + " * i";
}
public static void main(String[] args) {
Complex a = new Complex(Math.PI, -5); //just some numbers
Complex b = new Complex(-1, 2.5);
System.out.println(a.neg());
System.out.println(a.add(b));
System.out.println(a.inv());
System.out.println(a.mult(b));
System.out.println(a.conj());
}
} |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Lua | Lua | function gcd(a,b) return a == 0 and b or gcd(b % a, a) end
do
local function coerce(a, b)
if type(a) == "number" then return rational(a, 1), b end
if type(b) == "number" then return a, rational(b, 1) end
return a, b
end
rational = setmetatable({
__add = function(a, b)
local a, b = coerce(a, b)
return rational(a.num * b.den + a.den * b.num, a.den * b.den)
end,
__sub = function(a, b)
local a, b = coerce(a, b)
return rational(a.num * b.den - a.den * b.num, a.den * b.den)
end,
__mul = function(a, b)
local a, b = coerce(a, b)
return rational(a.num * b.num, a.den * b.den)
end,
__div = function(a, b)
local a, b = coerce(a, b)
return rational(a.num * b.den, a.den * b.num)
end,
__pow = function(a, b)
if type(a) == "number" then return a ^ (b.num / b.den) end
return rational(a.num ^ b, a.den ^ b) --runs into a problem if these aren't integers
end,
__concat = function(a, b)
if getmetatable(a) == rational then return a.num .. "/" .. a.den .. b end
return a .. b.num .. "/" .. b.den
end,
__unm = function(a) return rational(-a.num, -a.den) end}, {
__call = function(z, a, b) return setmetatable({num = a / gcd(a, b),den = b / gcd(a, b)}, z) end} )
end
print(rational(2, 3) + rational(3, 5) - rational(1, 10) .. "") --> 7/6
print((rational(4, 5) * rational(5, 9)) ^ rational(1, 2) .. "") --> 2/3
print(rational(45, 60) / rational(5, 2) .. "") --> 3/10
print(5 + rational(1, 3) .. "") --> 16/3
function findperfs(n)
local ret = {}
for i = 1, n do
sum = rational(1, i)
for fac = 2, i^.5 do
if i % fac == 0 then
sum = sum + rational(1, fac) + rational(fac, i)
end
end
if sum.den == sum.num then
ret[#ret + 1] = i
end
end
return table.concat(ret, '\n')
end
print(findperfs(2^19)) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Objeck | Objeck |
class ArithmeticMean {
function : Amg(a : Float, g : Float) ~ Nil {
a1 := a;
g1 := g;
while((a1-g1)->Abs() >= Float->Power(10, -14)) {
tmp := (a1+g1)/2.0;
g1 := Float->SquareRoot(a1*g1);
a1 := tmp;
};
a1->PrintLine();
}
function : Main(args : String[]) ~ Nil {
Amg(1,1/Float->SquareRoot(2));
}
}
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #OCaml | OCaml | let rec agm a g tol =
if tol > abs_float (a -. g) then a else
agm (0.5*.(a+.g)) (sqrt (a*.g)) tol
let _ = Printf.printf "%.16f\n" (agm 1.0 (sqrt 0.5) 1e-15) |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Applesoft_BASIC | Applesoft BASIC | ]? 0^0
1 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Arturo | Arturo | print 0 ^ 0
print 0.0 ^ 0 |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #JavaScript | JavaScript | function evalArithmeticExp(s) {
s = s.replace(/\s/g,'').replace(/^\+/,'');
var rePara = /\([^\(\)]*\)/;
var exp = s.match(rePara);
while (exp = s.match(rePara)) {
s = s.replace(exp[0], evalExp(exp[0]));
}
return evalExp(s);
function evalExp(s) {
s = s.replace(/[\(\)]/g,'');
var reMD = /\d+\.?\d*\s*[\*\/]\s*[+-]?\d+\.?\d*/;
var reM = /\*/;
var reAS = /-?\d+\.?\d*\s*[\+-]\s*[+-]?\d+\.?\d*/;
var reA = /\d\+/;
var exp;
while (exp = s.match(reMD)) {
s = exp[0].match(reM)? s.replace(exp[0], multiply(exp[0])) : s.replace(exp[0], divide(exp[0]));
}
while (exp = s.match(reAS)) {
s = exp[0].match(reA)? s.replace(exp[0], add(exp[0])) : s.replace(exp[0], subtract(exp[0]));
}
return '' + s;
function multiply(s, b) {
b = s.split('*');
return b[0] * b[1];
}
function divide(s, b) {
b = s.split('/');
return b[0] / b[1];
}
function add(s, b) {
s = s.replace(/^\+/,'').replace(/\++/,'+');
b = s.split('+');
return Number(b[0]) + Number(b[1]);
}
function subtract(s, b) {
s = s.replace(/\+-|-\+/g,'-');
if (s.match(/--/)) {
return add(s.replace(/--/,'+'));
}
b = s.split('-');
return b.length == 3? -1 * b[1] - b[2] : b[0] - b[1];
}
}
} |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Processing | Processing | float x, y;
float theta;
float rotation;
void setup() {
size(300, 300);
theta = 0;
rotation = 0.1;
background(255);
}
void draw() {
translate(width/2.0, height/2.0);
x = theta*cos(theta/PI);
y = theta*sin(theta/PI);
point(x, y);
theta = theta + rotation;
// check restart
if (x>width/2.0) frameCount=-1;
} |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #PureBasic | PureBasic | #MAXLOOP = 7*360
#XCENTER = 640/2
#YCENTER = 480/2
#SCALAR = 200
If OpenWindow(0, 100, 200, 640, 480, "Archimedean spiral")
If CreateImage(0, 640, 480,24,RGB(255,255,255))
If StartDrawing(ImageOutput(0))
i.f=0.0
While i<=#MAXLOOP
x.f=#XCENTER+Cos(Radian(i))*#SCALAR*i/#MAXLOOP
y.f=#YCENTER+Sin(Radian(i))*#SCALAR*i/#MAXLOOP
Plot(x,y,RGB(50,50,50))
i+0.05
Wend
StopDrawing()
EndIf
EndIf
ImageGadget(0, 0, 0, 0, 0, ImageID(0))
Repeat : Event = WaitWindowEvent() : Until Event = #PB_Event_CloseWindow
EndIf
End |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #11l | 11l | V n = 20
F z(=n)
I n == 0
R [0]
V fib = [2, 1]
L fib[0] < n
fib = [sum(fib[0.<2])] [+] fib
[Int] dig
L(f) fib
I f <= n
dig [+]= 1
n -= f
E
dig [+]= 0
R I dig[0] {dig} E dig[1..]
L(i) 0..n
print(‘#3: #8’.format(i, z(i).map(d -> String(d)).join(‘’))) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Asymptote | Asymptote | for(int i = 1; i < 100; ++i) {
if (i % i^2 < 11) {
write("Door ", i^2, suffix=none);
write(" is open");
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #ColdFusion | ColdFusion | <cfset arr1 = ArrayNew(1)> |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #JavaScript | JavaScript | function Complex(r, i) {
this.r = r;
this.i = i;
}
Complex.add = function() {
var num = arguments[0];
for(var i = 1, ilim = arguments.length; i < ilim; i += 1){
num.r += arguments[i].r;
num.i += arguments[i].i;
}
return num;
}
Complex.multiply = function() {
var num = arguments[0];
for(var i = 1, ilim = arguments.length; i < ilim; i += 1){
num.r = (num.r * arguments[i].r) - (num.i * arguments[i].i);
num.i = (num.i * arguments[i].r) - (num.r * arguments[i].i);
}
return num;
}
Complex.negate = function (z) {
return new Complex(-1*z.r, -1*z.i);
}
Complex.invert = function(z) {
var denom = Math.pow(z.r,2) + Math.pow(z.i,2);
return new Complex(z.r/denom, -1*z.i/denom);
}
Complex.conjugate = function(z) {
return new Complex(z.r, -1*z.i);
}
// BONUSES!
Complex.prototype.toString = function() {
return this.r === 0 && this.i === 0
? "0"
: (this.r !== 0 ? this.r : "")
+ ((this.r !== 0 || this.i < 0) && this.i !== 0
? (this.i > 0 ? "+" : "-")
: "" ) + ( this.i !== 0 ? Math.abs(this.i) + "i" : "" );
}
Complex.prototype.getMod = function() {
return Math.sqrt( Math.pow(this.r,2) , Math.pow(this.i,2) )
} |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #M2000_Interpreter | M2000 Interpreter |
Class Rational {
\\ this is a compact version for this task
numerator as decimal, denominator as decimal
gcd=lambda->0
lcm=lambda->0
operator "+" {
Read l
denom=.lcm(l.denominator, .denominator)
.numerator<=denom/l.denominator*l.numerator+denom/.denominator*.numerator
if .numerator==0 then denom=1
.denominator<=denom
}
Group Real {
value {
link parent numerator, denominator to n, d
=n/d
}
}
Group ToString$ {
value {
link parent numerator, denominator to n, d
=Str$(n)+"/"+Str$(d,"")
}
}
class:
Module Rational (.numerator, .denominator) {
if .denominator<=0 then Error "Positive only denominator"
gcd1=lambda (a as decimal, b as decimal) -> {
if a<b then swap a,b
g=a mod b
while g {
a=b:b=g: g=a mod b
}
=abs(b)
}
.gcd<=gcd1
.lcm<=lambda gcd=gcd1 (a as decimal, b as decimal) -> {
=a/gcd(a,b)*b
}
}
}
sum=rational(1, 1)
onediv=rational(1,1)
divcand=rational(1,1)
Profiler
For sum.denominator= 2 to 2**15 {
divcand.denominator=sum.denominator
For onediv.denominator=2 to sqrt(sum.denominator) {
if sum.denominator mod onediv.denominator = 0 then {
divcand.numerator=onediv.denominator
sum=sum+onediv+divcand
}
}
if sum.real=1 then Print sum.denominator;" is perfect"
sum.numerator=1
}
Print timecount
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Oforth | Oforth | : agm \ a b -- m
while( 2dup <> ) [ 2dup + 2 / -rot * sqrt ] drop ; |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #OOC | OOC |
import math // import for sqrt() function
amean: func (x: Double, y: Double) -> Double {
(x + y) / 2.
}
gmean: func (x: Double, y: Double) -> Double {
sqrt(x * y)
}
agm: func (a: Double, g: Double) -> Double {
while ((a - g) abs() > pow(10, -12)) {
(a1, g1) := (amean(a, g), gmean(a, g))
(a, g) = (a1, g1)
}
a
}
main: func {
"%.16f" printfln(agm(1., sqrt(0.5)))
}
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Asymptote | Asymptote | write("0 ^ 0 = ", 0 ** 0); |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #AutoHotkey | AutoHotkey | MsgBox % 0 ** 0 |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #jq | jq | def star(E): (E | star(E)) // .;
def plus(E): E | (plus(E) // . );
def optional(E): E // .;
def amp(E): . as $in | E | $in;
def neg(E): select( [E] == [] ); |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Jsish | Jsish | /* Arithmetic evaluation, in Jsish */
function evalArithmeticExp(s) {
s = s.replace(/\s/g,'').replace(/^\+/,'');
var rePara = /\([^\(\)]*\)/;
var exp;
function evalExp(s) {
s = s.replace(/[\(\)]/g,'');
var reMD = /[0-9]+\.?[0-9]*\s*[\*\/]\s*[+-]?[0-9]+\.?[0-9]*/;
var reM = /\*/;
var reAS = /-?[0-9]+\.?[0-9]*\s*[\+-]\s*[+-]?[0-9]+\.?[0-9]*/;
var reA = /[0-9]\+/;
var exp;
function multiply(s, b=0) {
b = s.split('*');
return b[0] * b[1];
}
function divide(s, b=0) {
b = s.split('/');
return b[0] / b[1];
}
function add(s, b=0) {
s = s.replace(/^\+/,'').replace(/\++/,'+');
b = s.split('+');
return Number(b[0]) + Number(b[1]);
}
function subtract(s, b=0) {
s = s.replace(/\+-|-\+/g,'-');
if (s.match(/--/)) {
return add(s.replace(/--/,'+'));
}
b = s.split('-');
return b.length == 3 ? -1 * b[1] - b[2] : b[0] - b[1];
}
while (exp = s.match(reMD)) {
s = exp[0].match(reM) ? s.replace(exp[0], multiply(exp[0]).toString()) : s.replace(exp[0], divide(exp[0]).toString());
}
while (exp = s.match(reAS)) {
s = exp[0].match(reA)? s.replace(exp[0], add(exp[0]).toString()) : s.replace(exp[0], subtract(exp[0]).toString());
}
return '' + s;
}
while (exp = s.match(rePara)) {
s = s.replace(exp[0], evalExp(exp[0]));
}
return evalExp(s);
}
if (Interp.conf('unitTest')) {
; evalArithmeticExp('2+3');
; evalArithmeticExp('2+3/4');
; evalArithmeticExp('2*3-4');
; evalArithmeticExp('2*(3+4)+5/6');
; evalArithmeticExp('2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10');
; evalArithmeticExp('2*-3--4+-0.25');
}
/*
=!EXPECTSTART!=
evalArithmeticExp('2+3') ==> 5
evalArithmeticExp('2+3/4') ==> 2.75
evalArithmeticExp('2*3-4') ==> 2
evalArithmeticExp('2*(3+4)+5/6') ==> 14.8333333333333
evalArithmeticExp('2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10') ==> 7000
evalArithmeticExp('2*-3--4+-0.25') ==> -2.25
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Python | Python | from turtle import *
from math import *
color("blue")
down()
for i in range(200):
t = i / 20 * pi
x = (1 + 5 * t) * cos(t)
y = (1 + 5 * t) * sin(t)
goto(x, y)
up()
done() |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Quackery | Quackery | [ $ "turtleduck.qky" loadfile ] now!
turtle
0 n->v
900 times
[ 2dup walk
1 20 v+
1 36 turn ]
2drop |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #R | R | with(list(s=seq(0, 10 * pi, length.out=500)),
plot((1 + s) * exp(1i * s), type="l")) |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #360_Assembly | 360 Assembly | * Zeckendorf number representation 04/04/2017
ZECKEN CSECT
USING ZECKEN,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,0 i=0
DO WHILE=(C,R6,LE,=A(20)) do i=0 to 20
MVC PG,=CL80'xx : ' init buffer
LA R10,PG pgi=0
XDECO R6,XDEC i
MVC 0(2,R10),XDEC+10 output i
LA R10,5(R10) pgi+=5
MVC FIB,=A(1) fib(1)=1
MVC FIB+4,=A(2) fib(2)=2
LA R7,2 j=2
LR R1,R7 j
SLA R1,2 @fib(j)
DO WHILE=(C,R6,GT,FIB-4(R1) do while fib(j)<i
LA R7,1(R7) j++
LR R1,R7 j
SLA R1,2 ~
L R2,FIB-8(R1) fib(j-1)
A R2,FIB-12(R1) fib(j-2)
ST R2,FIB-4(R1) fib(j)=fib(j-1)+fib(j-2)
LR R1,R7 j
SLA R1,2 @fib(j)
ENDDO , enddo j
LR R8,R6 k=i
MVI BB,X'00' bb=false
DO WHILE=(C,R7,GE,=A(1)) do j=j to 1 by -1
LR R1,R7 j
SLA R1,2 ~
IF C,R8,GE,FIB-4(R1) THEN if fib(j)<=k then
MVI BB,X'01' bb=true
MVC 0(1,R10),=C'1' output '1'
LA R10,1(R10) pgi+=1
LR R1,R7 j
SLA R1,2 ~
S R8,FIB-4(R1) k=k-fib(j)
ELSE , else
IF CLI,BB,EQ,X'01' THEN if bb then
MVC 0(1,R10),=C'0' output '0'
LA R10,1(R10) pgi+=1
ENDIF , endif
ENDIF , endif
BCTR R7,0 j--
ENDDO , enddo j
IF CLI,BB,NE,X'01' THEN if not bb then
MVC 0(1,R10),=C'0' output '0'
ENDIF , endif
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
FIB DS 32F Fibonnacci table
BB DS X flag
PG DS CL80 buffer
XDEC DS CL12 temp
YREGS
END ZECKEN |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Action.21 | Action! | PROC Encode(INT x CHAR ARRAY s)
INT ARRAY fib(22)=
[1 2 3 5 8 13 21 34 55 89 144 233 377 610
987 1597 2584 4181 6765 10946 17711 28657]
INT i
BYTE append
IF x=0 THEN
s(0)=1
s(1)='0
RETURN
FI
i=21 append=0
s(0)=0
WHILE i>=0
DO
IF x>=fib(i) THEN
x==-fib(i)
s(0)==+1
s(s(0))='1
append=1
ELSEIF append THEN
s(0)==+1
s(s(0))='0
FI
i==-1
OD
RETURN
PROC Main()
INT i
CHAR ARRAY s(10)
FOR i=0 TO 20
DO
Encode(i,s)
PrintF("%I -> %S%E",i,s)
OD
RETURN |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #ATS | ATS |
#include "share/atspre_staload.hats"
implement
main0((*void*)) = let
//
var A = @[bool][100](false)
val A = $UNSAFE.cast{arrayref(bool,100)}(addr@A)
//
fnx
loop
(
pass: intGte(0)
) : void =
if pass < 100
then loop2 (pass, pass)
// end of [if]
and
loop2
(
pass: natLt(100), door: intGte(0)
) : void =
if door < 100
then (A[door] := ~A[door]; loop2(pass, door+pass+1))
else loop(pass+1)
// end of [if]
//
fun
loop3
(
door: intGte(0)
) : void =
if door < 100
then (
println!("door #", door+1, " is ", (if A[door] then "open" else "closed"): string, ".");
loop3(door+1)
) (* end of [then] *)
// end of [if]
//
in
loop(0); loop3 (0)
end // end of [main0]
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Common_Lisp | Common Lisp | (let ((array (make-array 10)))
(setf (aref array 0) 1
(aref array 1) 3)
(print array)) |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #jq | jq | def real(z): if (z|type) == "number" then z else z[0] end;
def imag(z): if (z|type) == "number" then 0 else z[1] end;
def plus(x; y):
if (x|type) == "number" then
if (y|type) == "number" then [ x+y, 0 ]
else [ x + y[0], y[1]]
end
elif (y|type) == "number" then plus(y;x)
else [ x[0] + y[0], x[1] + y[1] ]
end;
def multiply(x; y):
if (x|type) == "number" then
if (y|type) == "number" then [ x*y, 0 ]
else [x * y[0], x * y[1]]
end
elif (y|type) == "number" then multiply(y;x)
else [ x[0] * y[0] - x[1] * y[1],
x[0] * y[1] + x[1] * y[0]]
end;
def multiply: reduce .[] as $x (1; multiply(.; $x));
def negate(x): multiply(-1; x);
def minus(x; y): plus(x; multiply(-1; y));
def conjugate(z):
if (z|type) == "number" then [z, 0]
else [z[0], -(z[1]) ]
end;
def invert(z):
if (z|type) == "number" then [1/z, 0]
else
( (z[0] * z[0]) + (z[1] * z[1]) ) as $d
# use "0 + ." to convert -0 back to 0
| [ z[0]/$d, (0 + -(z[1]) / $d)]
end;
def divide(x;y): multiply(x; invert(y));
def exp(z):
def expi(x): [ (x|cos), (x|sin) ];
if (z|type) == "number" then z|exp
elif z[0] == 0 then expi(z[1]) # for efficiency
else multiply( (z[0]|exp); expi(z[1]) )
end ;
def test(x;y):
"x = \( x )",
"y = \( y )",
"x+y: \( plus(x;y))",
"x*y: \( multiply(x;y))",
"-x: \( negate(x))",
"1/x: \( invert(x))",
"conj(x): \( conjugate(x))",
"(x/y)*y: \( multiply( divide(x;y) ; y) )",
"e^iπ: \( exp( [0, 4 * (1|atan) ] ) )"
;
test( [1,1]; [0,1] ) |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Maple | Maple |
> a := 3 / 5;
a := 3/5
> numer( a );
3
> denom( a );
5
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #ooRexx | ooRexx | numeric digits 20
say agm(1, 1/rxcalcsqrt(2,16))
::routine agm
use strict arg a, g
numeric digits 20
a1 = a
g1 = g
loop while abs(a1 - g1) >= 1e-14
temp = (a1 + g1)/2
g1 = rxcalcsqrt(a1*g1,16)
a1 = temp
end
return a1+0
::requires rxmath LIBRARY |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #PARI.2FGP | PARI/GP | agm(1,1/sqrt(2)) |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #AWK | AWK |
# syntax: GAWK -f ZERO_TO_THE_ZERO_POWER.AWK
BEGIN {
print(0 ^ 0)
exit(0)
}
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #BaCon | BaCon | PRINT POW(0, 0) |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Julia | Julia | julia> expr="2 * (3 -1) + 2 * 5"
"2 * (3 -1) + 2 * 5"
julia> parsed = parse(expr) #Julia provides low-level access to language parser for AST/Expr creation
:(+(*(2,-(3,1)),*(2,5)))
julia> t = typeof(parsed)
Expr
julia> names(t) #shows type fields
(:head,:args,:typ)
julia> parsed.args #Inspect our 'Expr' type innards
3-element Any Array:
:+
:(*(2,-(3,1)))
:(*(2,5))
julia> typeof(parsed.args[2]) #'Expr' types can nest
Expr
julia> parsed.args[2].args
3-element Any Array:
:*
2
:(-(3,1))
julia> parsed.args[2].args[3].args #Will nest until lowest level of AST
3-element Any Array:
:-
3
1
julia> eval(parsed)
14
julia> eval(parse("1 - 5 * 2 / 20 + 1"))
1.5
julia> eval(parse("2 * (3 + ((5) / (7 - 11)))"))
3.5 |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Racket | Racket | #lang racket/base
(require plot
racket/math)
;; x and y bounds set to centralise the circle
(define (archemedian-spiral-renderer2d a b θ/τ-max
#:samples (samples (line-samples)))
(define (f θ) (+ a (* b θ)))
(define max-dim (+ a (* θ/τ-max 2 pi b)))
(polar f
0 (* θ/τ-max 2 pi)
#:x-min (- max-dim)
#:x-max max-dim
#:y-min (- max-dim)
#:y-max max-dim
#:samples samples))
(plot (list (archemedian-spiral-renderer2d 0.0 24 4)))
;; writes to a file so hopefully, I can post it to RC...
(plot-file (list (archemedian-spiral-renderer2d 0.0 24 4))
"images/archemidian-spiral-racket.png") |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Raku | Raku | use Image::PNG::Portable;
my ($w, $h) = (400, 400);
my $png = Image::PNG::Portable.new: :width($w), :height($h);
(0, .025 ... 52*π).race.map: -> \Θ {
$png.set: |((cis( Θ / π ) * Θ).reals »+« ($w/2, $h/2))».Int, 255, 0, 255;
}
$png.write: 'Archimedean-spiral-perl6.png'; |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Ada | Ada | with Ada.Text_IO, Ada.Strings.Unbounded;
procedure Print_Zeck is
function Zeck_Increment(Z: String) return String is
begin
if Z="" then
return "1";
elsif Z(Z'Last) = '1' then
return Zeck_Increment(Z(Z'First .. Z'Last-1)) & '0';
elsif Z(Z'Last-1) = '0' then
return Z(Z'First .. Z'Last-1) & '1';
else -- Z has at least two digits and ends with "10"
return Zeck_Increment(Z(Z'First .. Z'Last-2)) & "00";
end if;
end Zeck_Increment;
use Ada.Strings.Unbounded;
Current: Unbounded_String := Null_Unbounded_String;
begin
for I in 1 .. 20 loop
Current := To_Unbounded_String(Zeck_Increment(To_String(Current)));
Ada.Text_IO.Put(To_String(Current) & " ");
end loop;
end Print_Zeck; |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #AutoHotkey | AutoHotkey | Loop, 100
Door%A_Index% := "closed"
Loop, 100 {
x := A_Index, y := A_Index
While (x <= 100)
{
CurrentDoor := Door%x%
If CurrentDoor contains closed
{
Door%x% := "open"
x += y
}
else if CurrentDoor contains open
{
Door%x% := "closed"
x += y
}
}
}
Loop, 100 {
CurrentDoor := Door%A_Index%
If CurrentDoor contains open
Res .= "Door " A_Index " is open`n"
}
MsgBox % Res |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Component_Pascal | Component Pascal |
MODULE TestArray;
(* Implemented in BlackBox Component Builder *)
IMPORT Out;
(* Static array *)
PROCEDURE DoOneDim*;
CONST M = 5;
VAR a: ARRAY M OF INTEGER;
BEGIN
a[0] := 100; (* set first element's value of array a to 100 *)
a[M-1] := -100; (* set M-th element's value of array a to -100 *)
Out.Int(a[0], 0); Out.Ln;
Out.Int(a[M-1], 0); Out.Ln;
END DoOneDim;
PROCEDURE DoTwoDim*;
VAR b: ARRAY 5, 4 OF INTEGER;
BEGIN
b[1, 2] := 100; (* second row, third column element *)
b[4, 3] := -100; (* fifth row, fourth column element *)
Out.Int(b[1, 2], 0); Out.Ln;
Out.Int(b[4, 3], 0); Out.Ln;
END DoTwoDim;
END TestArray. |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Julia | Julia | julia> z1 = 1.5 + 3im
julia> z2 = 1.5 + 1.5im
julia> z1 + z2
3.0 + 4.5im
julia> z1 - z2
0.0 + 1.5im
julia> z1 * z2
-2.25 + 6.75im
julia> z1 / z2
1.5 + 0.5im
julia> - z1
-1.5 - 3.0im
julia> conj(z1), z1' # two ways to conjugate
(1.5 - 3.0im,1.5 - 3.0im)
julia> abs(z1)
3.3541019662496847
julia> z1^z2
-1.102482955327779 - 0.38306415117199305im
julia> real(z1)
1.5
julia> imag(z1)
3.0 |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | 4/16
3/8
8/4
4Pi/2
16!/10!
Sqrt[9/16]
Sqrt[3/4]
(23/12)^5
2 + 1/(1 + 1/(3 + 1/4))
1/2+1/3+1/5
8/Pi+Pi/8 //Together
13/17 + 7/31
Sum[1/n,{n,1,100}] (*summation of 1/1 + 1/2 + 1/3 + 1/4+ .........+ 1/99 + 1/100*)
1/2-1/3
a=1/3;a+=1/7
1/4==2/8
1/4>3/8
Pi/E >23/20
1/3!=123/370
Sin[3]/Sin[2]>3/20
Numerator[6/9]
Denominator[6/9] |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Pascal | Pascal | Program ArithmeticGeometricMean;
uses
gmp;
procedure agm (in1, in2: mpf_t; var out1, out2: mpf_t);
begin
mpf_add (out1, in1, in2);
mpf_div_ui (out1, out1, 2);
mpf_mul (out2, in1, in2);
mpf_sqrt (out2, out2);
end;
const
nl = chr(13)+chr(10);
var
x0, y0, resA, resB: mpf_t;
i: integer;
begin
mpf_set_default_prec (65568);
mpf_init_set_ui (y0, 1);
mpf_init_set_d (x0, 0.5);
mpf_sqrt (x0, x0);
mpf_init (resA);
mpf_init (resB);
for i := 0 to 6 do
begin
agm(x0, y0, resA, resB);
agm(resA, resB, x0, y0);
end;
mp_printf ('%.20000Ff'+nl, @x0);
mp_printf ('%.20000Ff'+nl+nl, @y0);
end. |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #BASIC | BASIC | print "0 ^ 0 = "; 0 ^ 0 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #BBC_BASIC | BBC BASIC | PRINT 0^0 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Bc | Bc |
0 ^ 0
|
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Kotlin | Kotlin | // version 1.2.10
/* if string is empty, returns zero */
fun String.toDoubleOrZero() = this.toDoubleOrNull() ?: 0.0
fun multiply(s: String): String {
val b = s.split('*').map { it.toDoubleOrZero() }
return (b[0] * b[1]).toString()
}
fun divide(s: String): String {
val b = s.split('/').map { it.toDoubleOrZero() }
return (b[0] / b[1]).toString()
}
fun add(s: String): String {
var t = s.replace(Regex("""^\+"""), "").replace(Regex("""\++"""), "+")
val b = t.split('+').map { it.toDoubleOrZero() }
return (b[0] + b[1]).toString()
}
fun subtract(s: String): String {
var t = s.replace(Regex("""(\+-|-\+)"""), "-")
if ("--" in t) return add(t.replace("--", "+"))
val b = t.split('-').map { it.toDoubleOrZero() }
return (if (b.size == 3) -b[1] - b[2] else b[0] - b[1]).toString()
}
fun evalExp(s: String): String {
var t = s.replace(Regex("""[()]"""), "")
val reMD = Regex("""\d+\.?\d*\s*[*/]\s*[+-]?\d+\.?\d*""")
val reM = Regex( """\*""")
val reAS = Regex("""-?\d+\.?\d*\s*[+-]\s*[+-]?\d+\.?\d*""")
val reA = Regex("""\d\+""")
while (true) {
val match = reMD.find(t)
if (match == null) break
val exp = match.value
val match2 = reM.find(exp)
t = if (match2 != null)
t.replace(exp, multiply(exp))
else
t.replace(exp, divide(exp))
}
while (true) {
val match = reAS.find(t)
if (match == null) break
val exp = match.value
val match2 = reA.find(exp)
t = if (match2 != null)
t.replace(exp, add(exp))
else
t.replace(exp, subtract(exp))
}
return t
}
fun evalArithmeticExp(s: String): Double {
var t = s.replace(Regex("""\s"""), "").replace("""^\+""", "")
val rePara = Regex("""\([^()]*\)""")
while(true) {
val match = rePara.find(t)
if (match == null) break
val exp = match.value
t = t.replace(exp, evalExp(exp))
}
return evalExp(t).toDoubleOrZero()
}
fun main(arsg: Array<String>) {
listOf(
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-0.25",
"-4 - 3",
"((((2))))+ 3 * 5",
"1 + 2 * (3 + (4 * 5 + 6 * 7 * 8) - 9) / 10",
"1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5 - 22/(7 + 2*(3 - 1)) - 1)) + 1"
).forEach { println("$it = ${evalArithmeticExp(it)}") }
} |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #REXX | REXX | /*REXX pgm plots several cycles (half a spiral) of the Archimedean spiral (ASCII plot).*/
parse arg cy a b inc chr . /*obtain optional arguments from the CL*/
if cy=='' | cy=="," then cy= 3 /*Not specified? Then use the default.*/
if a=='' | a=="," then a= 1 /* " " " " " " */
if b=='' | b=="," then b= 9 /* " " " " " " */
if inc=='' | inc=="," then inc= 0.02 /* " " " " " " */
if chr=='' | chr=="," then chr= '∙' /* " " " " " " */
if length(chr)==3 then chr= d2c(chr) /*plot character coded in decimal? */
if length(chr)==2 then chr= x2c(chr) /* " " " " hexadecimal? */
cy= max(2, cy); LOx= . /*set the LOx variable (a semaphore).*/
parse value scrsize() with sd sw . /*get the size of the terminal screen. */
w= sw - 1 ; mw= w * (cy-1) * 4 /*set useable width; max width for calc*/
h= sd - 1 + cy*10; mh= h * (cy-1) /* " " depth; " depth " " */
@.= /*initialize the line based plot field.*/
do t=1 to pi()*cy by inc /*calc all the coördinates for spiral. */
r= a + b* t /* " " " R " " */
x= w + r*cos(t); xx= x % 2 /* " " " X " " */
y= h + r*sin(t); yy= y % 2 /* " " " Y " " */
if x<0 | y<0 | x>mw | y>mh then iterate /*Is X or Y out of bounds? Then skip.*/
if LOx==. then do; LOx= xx; HIx= xx; LOy= yy; HIy= yy
end /* [↑] find the minimums and maximums.*/
LOx= min(LOx, xx); HIx= max(HIx, xx) /*determine the X MIN and MAX. */
LOy= min(LOy, yy); HIy= max(HIy, yy) /* " " Y " " " */
@.yy= overlay(chr, @.yy, xx+1) /*assign the plot character (glyph). */
end /*t*/
call plot /*invoke plotting subroutine (to term).*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078; return pi
plot: do row=HIy to LOy by -1; say substr(@.row, LOx+1); end; return
r2r: return arg(1) // (pi() * 2) /*normalize radians ───► a unit circle.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
cos: procedure; parse arg x; x= r2r(x); _= 1; a= abs(x); hpi= pi * .5
numeric fuzz min(6, digits() - 3); if a=pi then return -1
if a=hpi | a=hpi*3 then return 0 if a=pi / 3 then return .5
if a=pi * 2 / 3 then return -.5; q= x*x; z= 1
do k=2 by 2 until p=z; p= z; _= -_ *q/(k*k-k); z= z+_; end; return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin: procedure; parse arg x; x= r2r(x); _= x; numeric fuzz min(5, max(1, digits() -3))
if x=pi * .5 then return 1; if x==pi*1.5 then return -1
if abs(x)=pi | x=0 then return 0; q= x*x; z= x
do k=2 by 2 until p=z; p= z; _= -_ *q/(k*k+k); z= z+_; end; return z |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #ALGOL_68 | ALGOL 68 | # print some Zeckendorf number representations #
# We handle 32-bit numbers, the maximum fibonacci number that can fit in a #
# 32 bit number is F(45) #
# build a table of 32-bit fibonacci numbers #
[ 45 ]INT fibonacci;
fibonacci[ 1 ] := 1;
fibonacci[ 2 ] := 2;
FOR i FROM 3 TO UPB fibonacci DO fibonacci[ i ] := fibonacci[ i - 1 ] + fibonacci[ i - 2 ] OD;
# returns the Zeckendorf representation of n or "?" if one cannot be found #
PROC to zeckendorf = ( INT n )STRING:
IF n = 0 THEN
"0"
ELSE
STRING result := "";
INT f pos := UPB fibonacci;
INT rest := ABS n;
# find the first non-zero Zeckendorf digit #
WHILE f pos > LWB fibonacci AND rest < fibonacci[ f pos ] DO
f pos -:= 1
OD;
# if we found a digit, build the representation #
IF f pos >= LWB fibonacci THEN
# have a digit #
BOOL skip digit := FALSE;
WHILE f pos >= LWB fibonacci DO
IF rest <= 0 THEN
result +:= "0"
ELIF skip digit THEN
# we used the previous digit #
skip digit := FALSE;
result +:= "0"
ELIF rest < fibonacci[ f pos ] THEN
# can't use the digit at f pos #
skip digit := FALSE;
result +:= "0"
ELSE
# can use this digit #
skip digit := TRUE;
result +:= "1";
rest -:= fibonacci[ f pos ]
FI;
f pos -:= 1
OD
FI;
IF rest = 0 THEN
# found a representation #
result
ELSE
# can't find a representation #
"?"
FI
FI; # to zeckendorf #
FOR i FROM 0 TO 20 DO
print( ( whole( i, -3 ), " ", to zeckendorf( i ), newline ) )
OD
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #AutoIt | AutoIt |
#include <array.au3>
$doors = 100
;door array, 0 = closed, 1 = open
Local $door[$doors +1]
For $ii = 1 To $doors
For $i = $ii To $doors Step $ii
$door[$i] = Not $door[$i]
next
Next
;display to screen
For $i = 1 To $doors
ConsoleWrite (Number($door[$i])& " ")
If Mod($i,10) = 0 Then ConsoleWrite(@CRLF)
Next
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Computer.2Fzero_Assembly | Computer/zero Assembly | load: LDA ary
ADD sum
STA sum
LDA load
ADD one
STA load
SUB end
BRZ done
JMP load
done: LDA sum
STP
one: 1
end: LDA ary+10
sum: 0
ary: 1
2
3
4
5
6
7
8
9
10 |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Kotlin | Kotlin | class Complex(private val real: Double, private val imag: Double) {
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
)
fun inv(): Complex {
val denom = real * real + imag * imag
return Complex(real / denom, -imag / denom)
}
operator fun unaryMinus() = Complex(-real, -imag)
operator fun minus(other: Complex) = this + (-other)
operator fun div(other: Complex) = this * other.inv()
fun conj() = Complex(real, -imag)
override fun toString() =
if (imag >= 0.0) "$real + ${imag}i"
else "$real - ${-imag}i"
}
fun main(args: Array<String>) {
val x = Complex(1.0, 3.0)
val y = Complex(5.0, 2.0)
println("x = $x")
println("y = $y")
println("x + y = ${x + y}")
println("x - y = ${x - y}")
println("x * y = ${x * y}")
println("x / y = ${x / y}")
println("-x = ${-x}")
println("1 / x = ${x.inv()}")
println("x* = ${x.conj()}")
} |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Maxima | Maxima | /* Rational numbers are builtin */
a: 3 / 11;
3/11
b: 117 / 17;
117/17
a + b;
1338/187
a - b;
-1236/187
a * b;
351/187
a / b;
17/429
a^5;
243/161051
num(a);
3
denom(a);
11
ratnump(a);
true |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Perl | Perl | #!/usr/bin/perl -w
my ($a0, $g0, $a1, $g1);
sub agm($$) {
$a0 = shift;
$g0 = shift;
do {
$a1 = ($a0 + $g0)/2;
$g1 = sqrt($a0 * $g0);
$a0 = ($a1 + $g1)/2;
$g0 = sqrt($a1 * $g1);
} while ($a0 != $a1);
return $a0;
}
print agm(1, 1/sqrt(2))."\n"; |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Befunge | Befunge | "PDPF"4#@(0F0FYP)@ |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #BQN | BQN | 0⋆0 |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Liberty_BASIC | Liberty BASIC |
'[RC] Arithmetic evaluation.bas
'Buld the tree (with linked nodes, in array 'cause LB has no pointers)
'applying shunting yard algorythm.
'Then evaluate tree
global stack$ 'operator/brakets stack
stack$=""
maxStack = 100
dim stack(maxStack) 'nodes stack
global SP 'stack pointer
SP = 0
'-------------------
global maxNode,curFree
global FirstOp,SecondOp,isNumber,NodeCont
global opList$
opList$ = "+-*/^"
maxNode=100
FirstOp=1 'pointers to other nodes; 0 means no pointer
SecondOp=2
isNumber=3 'like, 1 is number, 0 is operator
NodeCont=4 'number if isNumber; or mid$("+-*/^", i, 1) for 1..5 operator
dim node(NodeCont, maxNode)
'will be used from 1, 0 plays null pointer (no link)
curFree=1 'first free node
'-------------------
in$ = " 1 + 2 ^ 3 * 4 - 12 / 6 "
print "Input: "
print in$
'read tokens
token$ = "#"
while 1
i=i+1
token$ = word$(in$, i)
if token$ = "" then i=i-1: exit while
select case
case token$ = "("
'If the token is a left parenthesis, then push it onto the stack.
call stack.push token$
case token$ = ")"
'If the token is a right parenthesis:
'Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue.
'Pop the left parenthesis from the stack, but not onto the output queue.
'If the stack runs out without finding a left parenthesis, then there are mismatched parentheses.
while stack.peek$() <> "("
'if stack is empty
if stack$="" then print "Error: no matching '(' for token ";i: end
'add operator node to tree
child2=node.pop()
child1=node.pop()
call node.push addOpNode(child1,child2,stack.pop$())
wend
discard$=stack.pop$() 'discard "("
case isOperator(token$)
'If the token is an operator, o1, then:
'while there is an operator token, o2, at the top of the stack, and
'either o1 is left-associative and its precedence is equal to that of o2,
'or o1 has precedence less than that of o2,
' pop o2 off the stack, onto the output queue;
'push o1 onto the stack
op1$=token$
while(isOperator(stack.peek$()))
op2$=stack.peek$()
if (op2$<>"^" and precedence(op1$) = precedence(op2$)) _
OR (precedence(op1$) < precedence(op2$)) then
'"^" is the only right-associative operator
'add operator node to tree
child2=node.pop()
child1=node.pop()
call node.push addOpNode(child1,child2,stack.pop$())
else
exit while
end if
wend
call stack.push op1$
case else 'number
'actually, wrohg operator could end up here, like say %
'If the token is a number, then
'add leaf node to tree (number)
call node.push addNumNode(val(token$))
end select
wend
'When there are no more tokens to read:
'While there are still operator tokens in the stack:
' If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses.
' Pop the operator onto the output queue.
while stack$<>""
if stack.peek$() = "(" then print "no matching ')'": end
'add operator node to tree
child2=node.pop()
child1=node.pop()
call node.push addOpNode(child1,child2,stack.pop$())
wend
root = node.pop()
'call dumpNodes
print "Tree:"
call drawTree root, 1, 0, 3
locate 1, 10
print "Result: ";evaluate(root)
end
'------------------------------------------
function isOperator(op$)
isOperator = instr(opList$, op$)<>0 AND len(op$)=1
end function
function precedence(op$)
if isOperator(op$) then
precedence = 1 _
+ (instr("+-*/^", op$)<>0) _
+ (instr("*/^", op$)<>0) _
+ (instr("^", op$)<>0)
end if
end function
'------------------------------------------
sub stack.push s$
stack$=s$+"|"+stack$
end sub
function stack.pop$()
'it does return empty on empty stack or queue
stack.pop$=word$(stack$,1,"|")
stack$=mid$(stack$,instr(stack$,"|")+1)
end function
function stack.peek$()
'it does return empty on empty stack or queue
stack.peek$=word$(stack$,1,"|")
end function
'---------------------------------------
sub node.push s
stack(SP)=s
SP=SP+1
end sub
function node.pop()
'it does return -999999 on empty stack
if SP<1 then pop=-999999: exit function
SP=SP-1
node.pop=stack(SP)
end function
'=======================================
sub dumpNodes
for i = 1 to curFree-1
print i,
for j = 1 to 4
print node(j, i),
next
print
next
print
end sub
function evaluate(node)
if node=0 then exit function
if node(isNumber, node) then
evaluate = node(NodeCont, node)
exit function
end if
'else operator
op1 = evaluate(node(FirstOp, node))
op2 = evaluate(node(SecondOp, node))
select case node(NodeCont, node) 'opList$, "+-*/^"
case 1
evaluate = op1+op2
case 2
evaluate = op1-op2
case 3
evaluate = op1*op2
case 4
evaluate = op1/op2
case 5
evaluate = op1^op2
end select
end function
sub drawTree node, level, leftRight, offsetY
if node=0 then exit sub
call drawTree node(FirstOp, node), level+1, leftRight-1/2^level, offsetY
'print node
'count on 80 char maiwin
x = 40*(1+leftRight)
y = level+offsetY
locate x, y
'print x, y,">";
if node(isNumber, node) then
print node(NodeCont, node)
else
print mid$(opList$, node(NodeCont, node),1)
end if
call drawTree node(SecondOp, node), level+1, leftRight+1/2^level, offsetY
end sub
function addNumNode(num)
'returns new node
newNode=curFree
curFree=curFree+1
node(isNumber,newNode)=1
node(NodeCont,newNode)=num
addNumNode = newNode
end function
function addOpNode(firstChild, secondChild, op$)
'returns new node
'FirstOrSecond ignored if parent is 0
newNode=curFree
curFree=curFree+1
node(isNumber,newNode)=0
node(NodeCont,newNode)=instr(opList$, op$)
node(FirstOp,newNode)=firstChild
node(SecondOp,newNode)=secondChild
addOpNode = newNode
end function
|
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Ring | Ring |
/*
+---------------------------------------------------------------------------------------------------------
+ Program Name : Archimedean spiral
+---------------------------------------------------------------------------------------------------------
*/
Load "guilib.ring"
horzSize = 400
vertSize = 400
counter = 0 ### cycle thru colors
colorRed = new qcolor() { setrgb(255,000,000,255) }
colorGreen = new qcolor() { setrgb(000,255,000,255) }
colorBlue = new qcolor() { setrgb(000,000,255,255) }
colorYellow = new qcolor() { setrgb(255,255,000,255) }
penUseR = new qpen() { setcolor(colorRed) setwidth(1) }
penUseG = new qpen() { setcolor(colorGreen) setwidth(1) }
penUseB = new qpen() { setcolor(colorBlue) setwidth(1) }
penUseY = new qpen() { setcolor(colorYellow) setwidth(1) }
deg2rad = atan(1) * 4 / 180
screensize = 600
turns = 5
halfscrn = screensize / 2
sf = (turns * (screensize - 100)) / halfscrn
x = 1
y = 1
r = 0
inc = 0.50 ### control increment speed of r
New qapp
{
win1 = new qwidget()
{
setwindowtitle("Draw Spiral")
setgeometry(100,100,600,600)
label1 = new qlabel(win1)
{
setgeometry(10,10,600,600)
settext("")
}
Canvas = new qlabel(win1)
{
MonaLisa = new qPixMap2( 600,600)
color = new qcolor(){ setrgb(255,0,0,255) }
daVinci = new qpainter()
{
begin(MonaLisa)
penUse = new qpen() { setcolor(colorRed) setwidth(1) }
setpen(penUseR)
#endpaint() ### This will Stop the Painting
}
setpixmap(MonaLisa)
}
oTimer = new qTimer(win1)
{
setinterval(1) ### 1 millisecond
settimeoutevent("DrawCounter()")
start()
}
show() ### Will show Painting ONLY after exec
}
exec()
}
###====================================================
Func DrawCounter()
x = cos(r * deg2rad) * r / sf
y = sin(r * deg2rad) * r / sf
r += inc ### 0.20 fast, 0.90 slow
if r >= turns * 360
r = inc
x = 1
y = 1
counter++
whichColor = counter % 4
See "whichColor: "+ whichColor +nl
if whichColor = 0 daVinci.setpen(penUseR) ok
if whichColor = 1 daVinci.setpen(penUseG) ok
if whichColor = 2 daVinci.setpen(penUseB) ok
if whichColor = 3 daVinci.setpen(penUseY) ok
ok
hpoint = halfscrn + x
ypoint = halfscrn - y
daVinci.drawpoint(hpoint, ypoint)
Canvas.setpixmap(MonaLisa) ### Need this setpixmap to display imageLabel
win1.show() ### Need this show to display imageLabel
return
|
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Ruby | Ruby |
INCR = 0.1
attr_reader :x, :theta
def setup
sketch_title 'Archimedian Spiral'
@theta = 0
@x = 0
background(255)
translate(width / 2.0, height / 2.0)
begin_shape
(0..50*PI).step(INCR) do |theta|
@x = theta * cos(theta / PI)
curve_vertex(x, theta * sin(theta / PI))
end
end_shape
end
def settings
size(300, 300)
end
|
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #AppleScript | AppleScript | --------------------- ZECKENDORF NUMBERS -------------------
-- zeckendorf :: Int -> String
on zeckendorf(n)
script f
on |λ|(n, x)
if n < x then
[n, 0]
else
[n - x, 1]
end if
end |λ|
end script
if n = 0 then
{0} as string
else
item 2 of mapAccumL(f, n, |reverse|(just of tailMay(fibUntil(n)))) as string
end if
end zeckendorf
-- fibUntil :: Int -> [Int]
on fibUntil(n)
set xs to {}
set limit to n
script atLimit
property ceiling : limit
on |λ|(x)
(item 2 of x) > (atLimit's ceiling)
end |λ|
end script
script nextPair
property series : xs
on |λ|([a, b])
set nextPair's series to nextPair's series & b
[b, a + b]
end |λ|
end script
|until|(atLimit, nextPair, {0, 1})
return nextPair's series
end fibUntil
---------------------------- TEST --------------------------
on run
intercalate(linefeed, ¬
map(zeckendorf, enumFromTo(0, 20)))
end run
--------------------- GENERIC FUNCTIONS --------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- 'The mapAccumL function behaves like a combination of map and foldl;
-- it applies a function to each element of a list, passing an
-- accumulating parameter from left to right, and returning a final
-- value of this accumulator together with the new list.' (see Hoogle)
-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumL(f, acc, xs)
script
on |λ|(a, x)
tell mReturn(f) to set pair to |λ|(item 1 of a, x)
[item 1 of pair, (item 2 of a) & item 2 of pair]
end |λ|
end script
foldl(result, [acc, []], xs)
end mapAccumL
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- reverse :: [a] -> [a]
on |reverse|(xs)
if class of xs is text then
(reverse of characters of xs) as text
else
reverse of xs
end if
end |reverse|
-- tailMay :: [a] -> Maybe [a]
on tailMay(xs)
if length of xs > 1 then
{nothing:false, just:items 2 thru -1 of xs}
else
{nothing:true}
end if
end tailMay
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set mp to mReturn(p)
set v to x
tell mReturn(f)
repeat until mp's |λ|(v)
set v to |λ|(v)
end repeat
end tell
return v
end |until| |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #AWK | AWK | BEGIN {
for(i=1; i <= 100; i++)
{
doors[i] = 0 # close the doors
}
for(i=1; i <= 100; i++)
{
for(j=i; j <= 100; j += i)
{
doors[j] = (doors[j]+1) % 2
}
}
for(i=1; i <= 100; i++)
{
print i, doors[i] ? "open" : "close"
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Crystal | Crystal |
# create an array with one object in it
a = ["foo"]
# Empty array literals always need a type specification:
[] of Int32 # => Array(Int32).new
# The array's generic type argument T is inferred from the types of the elements inside the literal. When all elements of the array have the same type, T equals to that. Otherwise it will be a union of all element types.
[1, 2, 3] # => Array(Int32)
[1, "hello", 'x'] # => Array(Int32 | String | Char)
# An explicit type can be specified by immediately following the closing bracket with of and a type, each separated by whitespace. This overwrites the inferred type and can be used for example to create an array that holds only some types initially but can accept other types later.
array_of_numbers = [1, 2, 3] of Float64 | Int32 # => Array(Float64 | Int32)
array_of_numbers << 0.5 # => [1, 2, 3, 0.5]
array_of_int_or_string = [1, 2, 3] of Int32 | String # => Array(Int32 | String)
array_of_int_or_string << "foo" # => [1, 2, 3, "foo"]
# percent array literals
%w(one two three) # => ["one", "two", "three"]
%i(one two three) # => [:one, :two, :three]
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Lambdatalk | Lambdatalk |
{require lib_complex}
{def z1 {C.new 1 1}}
-> z1 = (1 1)
{C.x {z1}} -> 1
{C.y {z1}} -> 1
{C.mod {z1}} -> 1.4142135623730951
{C.arg {z1}} -> 0.7853981633974483 // 45°
{C.conj {z1}} -> (1 -1)
{C.negat {z1}} -> (-1 -1)
{C.invert {z1}} -> (0.5 -0.4999999999999999)
{C.sqrt {z1}} -> (1.0986841134678098 0.45508986056222733)
{C.exp {z1}} -> (1.4686939399158851 2.2873552871788423)
{C.log {z1}} -> (0.3465735902799727 0.7853981633974483)
{def z2 {C.new 1.5 1.5}}
-> z2 = (1.5 1.5)
{C.add {z1} {z2}} -> (2.5 2.5)
{C.sub {z1} {z2}} -> (-0.5 -0.5)
{C.mul {z1} {z2}} -> (0 3)
{C.div {z1} {z2}} -> (0.6666666666666667 0)
|
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Modula-2 | Modula-2 | DEFINITION MODULE Rational;
TYPE RAT = RECORD
numerator : INTEGER;
denominator : INTEGER;
END;
PROCEDURE IGCD( i : INTEGER; j : INTEGER ) : INTEGER;
PROCEDURE ILCM( i : INTEGER; j : INTEGER ) : INTEGER;
PROCEDURE IABS( i : INTEGER ) : INTEGER;
PROCEDURE RNormalize( i : RAT ) : RAT;
PROCEDURE RCreate( num : INTEGER; dem : INTEGER ) : RAT;
PROCEDURE RAdd( i : RAT; j : RAT ) : RAT;
PROCEDURE RSubtract( i : RAT; j : RAT ) : RAT;
PROCEDURE RMultiply( i : RAT; j : RAT ) : RAT;
PROCEDURE RDivide( i : RAT; j : RAT ) : RAT;
PROCEDURE RAbs( i : RAT ) : RAT;
PROCEDURE RInv( i : RAT ) : RAT;
PROCEDURE RNeg( i : RAT ) : RAT;
PROCEDURE RInc( i : RAT ) : RAT;
PROCEDURE RDec( i : RAT ) : RAT;
PROCEDURE REQ( i : RAT; j : RAT ) : BOOLEAN;
PROCEDURE RNE( i : RAT; j : RAT ) : BOOLEAN;
PROCEDURE RLT( i : RAT; j : RAT ) : BOOLEAN;
PROCEDURE RLE( i : RAT; j : RAT ) : BOOLEAN;
PROCEDURE RGT( i : RAT; j : RAT ) : BOOLEAN;
PROCEDURE RGE( i : RAT; j : RAT ) : BOOLEAN;
PROCEDURE RIsZero( i : RAT ) : BOOLEAN;
PROCEDURE RIsNegative( i : RAT ) : BOOLEAN;
PROCEDURE RIsPositive( i : RAT ) : BOOLEAN;
PROCEDURE RToString( i : RAT; VAR S : ARRAY OF CHAR );
PROCEDURE RToRational( s : ARRAY OF CHAR ) : RAT;
PROCEDURE WriteRational( i : RAT );
END Rational. |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Phix | Phix | function agm(atom a, atom g, atom tolerance=1.0e-15)
while abs(a-g)>tolerance do
{a,g} = {(a + g)/2,sqrt(a*g)}
printf(1,"%0.15g\n",a)
end while
return a
end function
?agm(1,1/sqrt(2)) -- (rounds to 10 d.p.)
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
1.0e-15 var tolerance
def test
over over - abs tolerance >
enddef
def agm /# n1 n2 -- n3 #/
test while
over over + 2 / rot rot * sqrt
test endwhile
enddef
1 1 2 sqrt / agm tostr ? |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Bracmat | Bracmat | 0^0 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Burlesque | Burlesque |
blsq ) 0.0 0.0?^
1.0
blsq ) 0 0?^
1
|
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Lua | Lua | require"lpeg"
P, R, C, S, V = lpeg.P, lpeg.R, lpeg.C, lpeg.S, lpeg.V
--matches arithmetic expressions and returns a syntax tree
expression = P{"expr";
ws = P" "^0,
number = C(R"09"^1) * V"ws",
lp = "(" * V"ws",
rp = ")" * V"ws",
sym = C(S"+-*/") * V"ws",
more = (V"sym" * V"expr")^0,
expr = V"number" * V"more" + V"lp" * lpeg.Ct(V"expr" * V"more") * V"rp" * V"more"}
--evaluates a tree
function eval(expr)
--empty
if type(expr) == "string" or type(expr) == "number" then return expr + 0 end
--arithmetic functions
tb = {["+"] = function(a,b) return eval(a) + eval(b) end,
["-"] = function(a,b) return eval(a) - eval(b) end,
["*"] = function(a,b) return eval(a) * eval(b) end,
["/"] = function(a,b) return eval(a) / eval(b) end}
--you could add ^ or other operators to this pretty easily
for i, v in ipairs{"*/", "+-"} do
for s, u in ipairs(expr) do
local k = type(u) == "string" and C(S(v)):match(u)
if k then
expr[s-1] = tb[k](expr[s-1],expr[s+1])
table.remove(expr, s)
table.remove(expr, s)
end
end
end
return expr[1]
end
print(eval{expression:match(io.read())}) |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #11l | 11l | V beforeTxt = |‘1100111
1100111
1100111
1100111
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1111110
0000000’
V smallrc01 =
|‘00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000’
V rc01 =
|‘00000000000000000000000000000000000000000000000000000000000
01111111111111111100000000000000000001111111111111000000000
01111111111111111110000000000000001111111111111111000000000
01111111111111111111000000000000111111111111111111000000000
01111111100000111111100000000001111111111111111111000000000
00011111100000111111100000000011111110000000111111000000000
00011111100000111111100000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111111111111110000000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000011111110000000111111000000000
01111111100000111111100000000001111111111111111111000000000
01111111100000111111101111110000111111111111111111011111100
01111111100000111111101111110000001111111111111111011111100
01111111100000111111101111110000000001111111111111011111100
00000000000000000000000000000000000000000000000000000000000’
F intarray(binstring)
‘Change a 2D matrix of 01 chars into a list of lists of ints’
R binstring.split("\n").map(line -> line.map(ch -> (I ch == ‘1’ {1} E 0)))
F chararray(intmatrix)
‘Change a 2d list of lists of 1/0 ints into lines of 1/0 chars’
R intmatrix.map(row -> row.map(p -> String(p)).join(‘’)).join("\n")
F toTxt(intmatrix)
‘Change a 2d list of lists of 1/0 ints into lines of '#' and '.' chars’
R intmatrix.map(row -> row.map(p -> (I p {‘#’} E ‘.’)).join(‘’)).join("\n")
F neighbours_array(x, y, image)
‘Return 8-neighbours of point p1 of picture, in order’
V i = image
V (x1, y1, x_1, y_1) = (x + 1, y - 1, x - 1, y + 1)
R [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1], i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]
F neighbours_tuple(x, y, image)
‘Return 8-neighbours of point p1 of picture, in order’
V i = image
V (x1, y1, x_1, y_1) = (x + 1, y - 1, x - 1, y + 1)
R (i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1], i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1])
F transitions(neighbours)
V s = 0
L(i) 7
s += Int((neighbours[i], neighbours[i + 1]) == (0, 1))
R s + Int((neighbours[7], neighbours[0]) == (0, 1))
F zhangSuen(&image)
V changing1 = [(-1, -1)]
V changing2 = [(-1, -1)]
L !changing1.empty | !changing2.empty
changing1.drop()
L(y) 1 .< image.len - 1
L(x) 1 .< image[0].len - 1
V n = neighbours_array(x, y, image)
V (P2, P3, P4, P5, P6, P7, P8, P9) = neighbours_tuple(x, y, image)
I (image[y][x] == 1 & P4 * P6 * P8 == 0 & P2 * P4 * P6 == 0 & transitions(n) == 1 & sum(n) C 2..6)
changing1.append((x, y))
L(x, y) changing1
image[y][x] = 0
changing2.drop()
L(y) 1 .< image.len - 1
L(x) 1 .< image[0].len - 1
V n = neighbours_array(x, y, image)
V (P2, P3, P4, P5, P6, P7, P8, P9) = neighbours_tuple(x, y, image)
I (image[y][x] == 1 & P2 * P6 * P8 == 0 & P2 * P4 * P8 == 0 & transitions(n) == 1 & sum(n) C 2..6)
changing2.append((x, y))
L(x, y) changing2
image[y][x] = 0
R image
L(picture) (beforeTxt, smallrc01, rc01)
V image = intarray(picture)
print("\nFrom:\n#.".format(toTxt(image)))
V after = zhangSuen(&image)
print("\nTo thinned:\n#.".format(toTxt(after))) |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Rust | Rust | #[macro_use(px)]
extern crate bmp;
use bmp::{Image, Pixel};
use std::f64;
fn main() {
let width = 600u32;
let half_width = (width / 2) as i32;
let mut img = Image::new(width, width);
let draw_color = px!(255, 128, 128);
// Constants defining the spiral size.
let a = 1.0_f64;
let b = 9.0_f64;
// max_angle = number of spirals * 2pi.
let max_angle = 5.0_f64 * 2.0_f64 * f64::consts::PI;
let mut theta = 0.0_f64;
while theta < max_angle {
theta = theta + 0.002_f64;
let r = a + b * theta;
let x = (r * theta.cos()) as i32 + half_width;
let y = (r * theta.sin()) as i32 + half_width;
img.set_pixel(x as u32, y as u32, draw_color);
}
// Save the image
let _ = img.save("archimedean_spiral.bmp").unwrap_or_else(|e| panic!("Failed to save: {}", e));
} |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #SAS | SAS | data xy;
h=constant('pi')/40;
do i=0 to 400;
t=i*h;
x=(1+t)*cos(t);
y=(1+t)*sin(t);
output;
end;
keep x y;
run;
proc sgplot;
series x=x y=y;
run; |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Arturo | Arturo | Z: function [x][
if x=0 -> return "0"
fib: new [2 1]
n: new x
while -> n > first fib
-> insert 'fib 0 fib\0 + fib\1
result: new ""
loop fib 'f [
if? f =< n [
'result ++ "1"
'n - f
]
else -> 'result ++ "0"
]
if result\0 = `0` ->
result: slice result 1 (size result)-1
return result
]
loop 0..20 'i ->
print [pad to :string i 3 pad Z i 8] |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Axiom | Axiom | (open,closed,change,open?) := (true,false,not,test);
doors := bits(100,closed);
for i in 1..#doors repeat
for j in i..#doors by i repeat
doors.j := change doors.j
[i for i in 1..#doors | open? doors.i]
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #D | D | // All D arrays are capable of bounds checks.
import std.stdio, core.stdc.stdlib;
import std.container: Array;
void main() {
// GC-managed heap allocated dynamic array:
auto array1 = new int[1];
array1[0] = 1;
array1 ~= 3; // append a second item
// array1[10] = 4; // run-time error
writeln("A) Element 0: ", array1[0]);
writeln("A) Element 1: ", array1[1]);
// Stack-allocated fixed-size array:
int[5] array2;
array2[0] = 1;
array2[1] = 3;
// array2[2] = 4; // compile-time error
writeln("B) Element 0: ", array2[0]);
writeln("B) Element 1: ", array2[1]);
// Stack-allocated dynamic fixed-sized array,
// length known only at run-time:
int n = 2;
int[] array3 = (cast(int*)alloca(n * int.sizeof))[0 .. n];
array3[0] = 1;
array3[1] = 3;
// array3[10] = 4; // run-time error
writeln("C) Element 0: ", array3[0]);
writeln("C) Element 1: ", array3[1]);
// Phobos-defined heap allocated not GC-managed array:
Array!int array4;
array4.length = 2;
array4[0] = 1;
array4[1] = 3;
// array4[10] = 4; // run-time exception
writeln("D) Element 0: ", array4[0]);
writeln("D) Element 1: ", array4[1]);
} |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #LFE | LFE |
(defrecord complex
real
img)
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Liberty_BASIC | Liberty BASIC | mainwin 50 10
print " Adding"
call cprint cadd$( complex$( 1, 1), complex$( 3.14159265, 1.2))
print " Multiplying"
call cprint cmulti$( complex$( 1, 1), complex$( 3.14159265, 1.2))
print " Inverting"
call cprint cinv$( complex$( 1, 1))
print " Negating"
call cprint cneg$( complex$( 1, 1))
end
sub cprint cx$
print "( "; word$( cx$, 1); " + i *"; word$( cx$, 2); ")"
end sub
function complex$( a , bj )
''complex number string-object constructor
complex$ = str$( a ) ; " " ; str$( bj )
end function
function cadd$( a$ , b$ )
ar = val( word$( a$ , 1 ) )
ai = val( word$( a$ , 2 ) )
br = val( word$( b$ , 1 ) )
bi = val( word$( b$ , 2 ) )
cadd$ = complex$( ar + br , ai + bi )
end function
function cmulti$( a$ , b$ )
ar = val( word$( a$ , 1 ) )
ai = val( word$( a$ , 2 ) )
br = val( word$( b$ , 1 ) )
bi = val( word$( b$ , 2 ) )
cmulti$ = complex$( ar * br - ai * bi _
, ar * bi + ai * br )
end function
function cneg$( a$)
ar = val( word$( a$ , 1 ) )
ai = val( word$( a$ , 2 ) )
cneg$ =complex$( 0 -ar, 0 -ai)
end function
function cinv$( a$)
ar = val( word$( a$ , 1 ) )
ai = val( word$( a$ , 2 ) )
D =ar^2 +ai^2
cinv$ =complex$( ar /D , 0 -ai /D )
end function |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Modula-3 | Modula-3 | INTERFACE Frac;
EXCEPTION ZeroDenominator;
TYPE
T <: Public;
Public = OBJECT
METHODS
(* initialization and conversion *)
init(a, b: INTEGER): T RAISES { ZeroDenominator };
fromInt(a: INTEGER): T;
(* unary operators *)
abs(): T;
opposite(): T;
(* binary operators *)
plus(other: T): T;
minus(other: T): T;
times(other: T): T;
dividedBy(other: T): T RAISES { ZeroDenominator };
integerDivision(other: INTEGER): T RAISES { ZeroDenominator };
(* relations *)
equals(other: T): BOOLEAN;
notEqualTo(other: T): BOOLEAN;
lessThan(other: T): BOOLEAN;
lessEqual(other: T): BOOLEAN;
greaterEqual(other: T): BOOLEAN;
greater(other: T): BOOLEAN;
(* other easily-checked properties *)
isInt(): BOOLEAN;
(* inc/decrement *)
inc(step: CARDINAL := 1);
dec(step: CARDINAL := 1);
END;
PROCEDURE One(): T;
PROCEDURE Zero(): T;
(* I/O *)
PROCEDURE PutRat(a: T);
END Frac. |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #PHP | PHP |
define('PRECISION', 13);
function agm($a0, $g0, $tolerance = 1e-10)
{
// the bc extension deals in strings and cannot convert
// floats in scientific notation by itself - hence
// this manual conversion to a string
$limit = number_format($tolerance, PRECISION, '.', '');
$an = $a0;
$gn = $g0;
do {
list($an, $gn) = array(
bcdiv(bcadd($an, $gn), 2),
bcsqrt(bcmul($an, $gn)),
);
} while (bccomp(bcsub($an, $gn), $limit) > 0);
return $an;
}
bcscale(PRECISION);
echo agm(1, 1 / bcsqrt(2));
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #C | C | #include <stdio.h>
#include <math.h>
#include <complex.h>
int main()
{
printf("0 ^ 0 = %f\n", pow(0,0));
double complex c = cpow(0,0);
printf("0+0i ^ 0+0i = %f+%fi\n", creal(c), cimag(c));
return 0;
} |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #C.23 | C# | using System;
namespace ZeroToTheZeroeth
{
class Program
{
static void Main(string[] args)
{
double k = Math.Pow(0, 0);
Console.Write("0^0 is {0}", k);
}
}
} |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #M2000_Interpreter | M2000 Interpreter |
y=100
Module CheckEval {
A$="1 + 2 * (3 + (4 * 5 + 6 * 7 * 8) - 9) / 10"
Print Eval(A$)
x=10
Print Eval("x+5")=x+5
Print Eval("A$=A$")=True
Try {
Print Eval("y") ' error: y is uknown here
}
}
Call CheckEval
|
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #Action.21 | Action! | PROC DrawImage(BYTE ARRAY image BYTE x,y,width,height)
BYTE i,j
BYTE POINTER ptr
Color=2
FOR j=0 TO height-1
DO
Plot(x,j+y) DrawTo(x+width-1,j+y)
OD
Color=1
ptr=image
FOR j=0 TO height-1
DO
FOR i=0 TO width-1
DO
IF ptr^ THEN
Plot(i+x,j+y)
FI
ptr==+1
OD
OD
RETURN
PROC Thinning(BYTE ARRAY image BYTE width,height)
DEFINE PTR="CARD"
DEFINE MAX="200"
PTR ARRAY change(MAX)
BYTE POINTER p1,p2,p3,p4,p5,p6,p7,p8,p9,p68,p24
INT count,i
BYTE x,y,sum,step1
step1=1
DO
count=0
p1=image p8=p1-1 p4=p1+1
p2=p1-width p6=p1+width
p9=p2-1 p3=p2+1
p7=p6-1 p5=p6+1
FOR y=0 TO height-1
DO
FOR x=0 TO width-1
DO
IF p1^=1 AND x>0 AND y>0 AND x<width-1 AND y<height-1 THEN
sum=p2^+p3^+p4^+p5^+p6^+p7^+p8^+p9^
IF sum>=2 AND sum<=6 THEN
sum=0
IF p3^>p2^ THEN sum==+1 FI
IF p4^>p3^ THEN sum==+1 FI
IF p5^>p4^ THEN sum==+1 FI
IF p6^>p5^ THEN sum==+1 FI
IF p7^>p6^ THEN sum==+1 FI
IF p8^>p7^ THEN sum==+1 FI
IF p9^>p8^ THEN sum==+1 FI
IF p2^>p9^ THEN sum==+1 FI
IF sum=1 THEN
IF step1 THEN
p24=p4 p68=p6
ELSE
p24=p2 p68=p8
FI
IF p2^+p4^+p68^<3 AND p24^+p6^+p8^<3 THEN
change(count)=p1 count==+1
FI
FI
FI
FI
p1==+1 p2==+1 p3==+1 p4==+1 p5==+1
p6==+1 p7==+1 p8==+1 p9==+1
OD
OD
step1=1-step1
FOR i=0 TO count-1
DO
p1=change(i) p1^=0
OD
UNTIL count=0
OD
RETURN
PROC Main()
BYTE ARRAY image1=[
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0
0 1 1 1 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0
0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0
0 1 1 1 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0
0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 1 1 1 0 0 1 1 1 1 0 1 1 1 0 0
0 1 1 1 0 0 0 1 1 1 1 0 1 1 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
BYTE ARRAY image2=[
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
BYTE width1=[32],height1=[10],width2=[59],height2=[18]
BYTE CH=$02FC
Graphics(7+16)
Color=1
SetColor(0,0,$00)
SetColor(4,0,$04)
SetColor(1,0,$0C)
DrawImage(image1,0,0,width1,height1)
Thinning(image1,width1,height1)
DrawImage(image1,width1+10,0,width1,height1)
DrawImage(image2,0,height1+10,width2,height2)
Thinning(image2,width2,height2)
DrawImage(image2,width2+10,height1+10,width2,height2)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Scala | Scala |
object ArchimedeanSpiral extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Archimedean Spiral") {
class ArchimedeanSpiral extends JPanel {
setPreferredSize(new Dimension(640, 640))
setBackground(Color.white)
private def drawGrid(g: Graphics2D): Unit = {
val (angle, margin, numRings) = (toRadians(45), 10, 8)
val w = getWidth
val (center, spacing) = (w / 2, (w - 2 * margin) / (numRings * 2))
g.setColor(new Color(0xEEEEEE))
for (i <- 0 until numRings) {
val pos = margin + i * spacing
val size = w - (2 * margin + i * 2 * spacing)
g.drawOval(pos, pos, size, size)
val ia = i * angle
val x2 = center + (cos(ia) * (w - 2 * margin) / 2).toInt
val y2 = center - (sin(ia) * (w - 2 * margin) / 2).toInt
g.drawLine(center, center, x2, y2)
}
}
private def drawSpiral(g: Graphics2D): Unit = {
val (degrees: Double, center) = (toRadians(0.1), getWidth / 2)
val (a, b, c, end) = (0, 20, 1, 360 * 2 * 10 * degrees)
def plot(g: Graphics2D, x: Int, y: Int): Unit = g.drawOval(x, y, 1, 1)
def iter(theta: Double): Double = {
if (theta < end) {
val r = a + b * pow(theta, 1 / c)
val x = r * cos(theta)
val y = r * sin(theta)
plot(g, (center + x).toInt, (center - y).toInt)
iter(theta + degrees)
} else theta
}
g.setStroke(new BasicStroke(2))
g.setColor(Color.orange)
iter(0)
}
override def paintComponent(gg: Graphics): Unit = {
super.paintComponent(gg)
val g = gg.asInstanceOf[Graphics2D]
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawGrid(g)
drawSpiral(g)
}
}
add(new ArchimedeanSpiral, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
}
)
} |
Subsets and Splits