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/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.
| #C1R | C1R | 100_doors |
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)
| #Euphoria | Euphoria |
--Arrays task for Rosetta Code wiki
--User:Lnettnay
atom dummy
--Arrays are sequences
-- single dimensioned array of 10 elements
sequence xarray = repeat(0,10)
xarray[5] = 5
dummy = xarray[5]
? dummy
--2 dimensional array
--5 sequences of 10 elements each
sequence xyarray = repeat(repeat(0,10),5)
xyarray[3][6] = 12
dummy = xyarray[3][6]
? dummy
--dynamic array use (all sequences can be modified at any time)
sequence dynarray = {}
for x = 1 to 10 do
dynarray = append(dynarray, x * x)
end for
? dynarray
for x = 1 to 10 do
dynarray = prepend(dynarray, x)
end for
? dynarray
|
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.
| #PostScript | PostScript |
%Adding two complex numbers
/addcomp{
/x exch def
/y exch def
/z [0 0] def
z 0 x 0 get y 0 get add put
z 1 x 1 get y 1 get add put
z pstack
}def
%Subtracting one complex number from another
/subcomp{
/x exch def
/y exch def
/z [0 0] def
z 0 x 0 get y 0 get sub put
z 1 x 1 get y 1 get sub put
z pstack
}def
%Multiplying two complex numbers
/mulcomp{
/x exch def
/y exch def
/z [0 0] def
z 0 x 0 get y 0 get mul x 1 get y 1 get mul sub put
z 1 x 1 get y 0 get mul x 0 get y 1 get mul add put
z pstack
}def
%Negating a complex number
/negcomp{
/x exch def
/z [0 0] def
z 0 x 0 get neg put
z 1 x 1 get neg put
z pstack
}def
%Inverting a complex number
/invcomp{
/x exch def
/z [0 0] def
z 0 x 0 get x 0 get 2 exp x 1 get 2 exp add div put
z 0 x 1 get neg x 0 get 2 exp x 1 get 2 exp add div put
z pstack
}def
|
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.
| #PowerShell | PowerShell |
class Complex {
[Double]$x
[Double]$y
Complex() {
$this.x = 0
$this.y = 0
}
Complex([Double]$x, [Double]$y) {
$this.x = $x
$this.y = $y
}
[Double]abs2() {return $this.x*$this.x + $this.y*$this.y}
[Double]abs() {return [math]::sqrt($this.abs2())}
static [Complex]add([Complex]$m,[Complex]$n) {return [Complex]::new($m.x+$n.x, $m.y+$n.y)}
static [Complex]mul([Complex]$m,[Complex]$n) {return [Complex]::new($m.x*$n.x - $m.y*$n.y, $m.x*$n.y + $n.x*$m.y)}
[Complex]mul([Double]$k) {return [Complex]::new($k*$this.x, $k*$this.y)}
[Complex]negate() {return $this.mul(-1)}
[Complex]conjugate() {return [Complex]::new($this.x, -$this.y)}
[Complex]inverse() {return $this.conjugate().mul(1/$this.abs2())}
[String]show() {
if(0 -ge $this.y) {
return "$($this.x)+$($this.y)i"
} else {
return "$($this.x)$($this.y)i"
}
}
static [String]show([Complex]$other) {
return $other.show()
}
}
$m = [complex]::new(3, 4)
$n = [complex]::new(7, 6)
"`$m: $($m.show())"
"`$n: $($n.show())"
"`$m + `$n: $([complex]::show([complex]::add($m,$n)))"
"`$m * `$n: $([complex]::show([complex]::mul($m,$n)))"
"negate `$m: $($m.negate().show())"
"1/`$m: $([complex]::show($m.inverse()))"
"conjugate `$m: $([complex]::show($m.conjugate()))"
|
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
| #Rust | Rust | use std::cmp::Ordering;
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
fn gcd(a: i64, b: i64) -> i64 {
match b {
0 => a,
_ => gcd(b, a % b),
}
}
fn lcm(a: i64, b: i64) -> i64 {
a / gcd(a, b) * b
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord)]
pub struct Rational {
numerator: i64,
denominator: i64,
}
impl Rational {
fn new(numerator: i64, denominator: i64) -> Self {
let divisor = gcd(numerator, denominator);
Rational {
numerator: numerator / divisor,
denominator: denominator / divisor,
}
}
}
impl Add for Rational {
type Output = Self;
fn add(self, other: Self) -> Self {
let multiplier = lcm(self.denominator, other.denominator);
Rational::new(self.numerator * multiplier / self.denominator +
other.numerator * multiplier / other.denominator,
multiplier)
}
}
impl AddAssign for Rational {
fn add_assign(&mut self, other: Self) {
*self = *self + other;
}
}
impl Sub for Rational {
type Output = Self;
fn sub(self, other: Self) -> Self {
self + -other
}
}
impl SubAssign for Rational {
fn sub_assign(&mut self, other: Self) {
*self = *self - other;
}
}
impl Mul for Rational {
type Output = Self;
fn mul(self, other: Self) -> Self {
Rational::new(self.numerator * other.numerator,
self.denominator * other.denominator)
}
}
impl MulAssign for Rational {
fn mul_assign(&mut self, other: Self) {
*self = *self * other;
}
}
impl Div for Rational {
type Output = Self;
fn div(self, other: Self) -> Self {
self *
Rational {
numerator: other.denominator,
denominator: other.numerator,
}
}
}
impl DivAssign for Rational {
fn div_assign(&mut self, other: Self) {
*self = *self / other;
}
}
impl Neg for Rational {
type Output = Self;
fn neg(self) -> Self {
Rational {
numerator: -self.numerator,
denominator: self.denominator,
}
}
}
impl PartialOrd for Rational {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
(self.numerator * other.denominator).partial_cmp(&(self.denominator * other.numerator))
}
}
impl<T: Into<i64>> From<T> for Rational {
fn from(value: T) -> Self {
Rational::new(value.into(), 1)
}
}
fn main() {
let max = 1 << 19;
for candidate in 2..max {
let mut sum = Rational::new(1, candidate);
for factor in 2..(candidate as f64).sqrt().ceil() as i64 {
if candidate % factor == 0 {
sum += Rational::new(1, factor);
sum += Rational::new(1, candidate / factor);
}
}
if sum == 1.into() {
println!("{} is perfect", candidate);
}
}
}
|
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
| #VBScript | VBScript |
Function agm(a,g)
Do Until a = tmp_a
tmp_a = a
a = (a + g)/2
g = Sqr(tmp_a * g)
Loop
agm = a
End Function
WScript.Echo agm(1,1/Sqr(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
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Math
Imports System.Console
Module Module1
Function CalcAGM(ByVal a As Double, ByVal b As Double) As Double
Dim c As Double, d As Double = 0, ld As Double = 1
While ld <> d : c = a : a = (a + b) / 2 : b = Sqrt(c * b)
ld = d : d = a - b : End While : Return b
End Function
Function DecSqRoot(ByVal v As Decimal) As Decimal
Dim r As Decimal = CDec(Sqrt(CDbl(v))), t As Decimal = 0, d As Decimal = 0, ld As Decimal = 1
While ld <> d : t = v / r : r = (r + t) / 2
ld = d : d = t - r : End While : Return t
End Function
Function CalcAGM(ByVal a As Decimal, ByVal b As Decimal) As Decimal
Dim c As Decimal, d As Decimal = 0, ld As Decimal = 1
While ld <> d : c = a : a = (a + b) / 2 : b = DecSqRoot(c * b)
ld = d : d = a - b : End While : Return b
End Function
Sub Main(ByVal args As String())
WriteLine("Double result: {0}", CalcAGM(1.0, DecSqRoot(0.5)))
WriteLine("Decimal result: {0}", CalcAGM(1D, DecSqRoot(0.5D)))
If System.Diagnostics.Debugger.IsAttached Then ReadKey()
End Sub
End Module |
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
| #JavaScript | JavaScript | > Math.pow(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
| #jq | jq | def power(y): y as $y | if $y == 0 then 1 elif . == 0 then 0 else log * $y | exp 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
| #Jsish | Jsish | puts(Math.pow(0,0)); |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #11l | 11l | F yinyang(n = 3)
V radii = [1, 3, 6].map(i -> i * @n)
V ranges = radii.map(r -> Array(-r .. r))
V squares = ranges.map(rnge -> multiloop(rnge, rnge, (x, y) -> (x, y)))
V circles = zip(squares, radii).map((sqrpoints, radius) -> sqrpoints.filter((x, y) -> x*x + y*y <= @radius^2))
V m = Dict(squares.last, (x, y) -> ((x, y), ‘ ’))
L(x, y) circles.last
m[(x, y)] = ‘*’
L(x, y) circles.last
I x > 0
m[(x, y)] = ‘·’
L(x, y) circles[(len)-2]
m[(x, y + 3 * n)] = ‘*’
m[(x, y - 3 * n)] = ‘·’
L(x, y) circles[(len)-3]
m[(x, y + 3 * n)] = ‘·’
m[(x, y - 3 * n)] = ‘*’
R ranges.last.map(y -> reversed(@ranges.last).map(x -> @@m[(x, @y)]).join(‘’)).join("\n")
print(yinyang(2))
print(yinyang(1)) |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program Ycombi64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Structures */
/********************************************/
/* structure function*/
.struct 0
func_fn: // next element
.struct func_fn + 8
func_f_: // next element
.struct func_f_ + 8
func_num:
.struct func_num + 8
func_fin:
/* Initialized data */
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessError: .asciz "\033[31mError Allocation !!!\n"
szFactorielle: .asciz "Function factorielle : \n"
szFibonacci: .asciz "Function Fibonacci : \n"
szCarriageReturn: .asciz "\n"
/* datas message display */
szMessResult: .ascii "Result value : @ \n"
/* UnInitialized data */
.bss
sZoneConv: .skip 100
/* code section */
.text
.global main
main: // program start
ldr x0,qAdrszMessStartPgm // display start message
bl affichageMess
adr x0,facFunc // function factorielle address
bl YFunc // create Ycombinator
mov x19,x0 // save Ycombinator
ldr x0,qAdrszFactorielle // display message
bl affichageMess
mov x20,#1 // loop counter
1: // start loop
mov x0,x20
bl numFunc // create number structure
cmp x0,#-1 // allocation error ?
beq 99f
mov x1,x0 // structure number address
mov x0,x19 // Ycombinator address
bl callFunc // call
ldr x0,[x0,#func_num] // load result
ldr x1,qAdrsZoneConv // and convert ascii string
bl conversion10S // decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message final
add x20,x20,#1 // increment loop counter
cmp x20,#10 // end ?
ble 1b // no -> loop
/*********Fibonacci *************/
adr x0,fibFunc // function fibonacci address
bl YFunc // create Ycombinator
mov x19,x0 // save Ycombinator
ldr x0,qAdrszFibonacci // display message
bl affichageMess
mov x20,#1 // loop counter
2: // start loop
mov x0,x20
bl numFunc // create number structure
cmp x0,#-1 // allocation error ?
beq 99f
mov x1,x0 // structure number address
mov x0,x19 // Ycombinator address
bl callFunc // call
ldr x0,[x0,#func_num] // load result
ldr x1,qAdrsZoneConv // and convert ascii string
bl conversion10S
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess
add x20,x20,#1 // increment loop counter
cmp x20,#10 // end ?
ble 2b // no -> loop
ldr x0,qAdrszMessEndPgm // display end message
bl affichageMess
b 100f
99: // display error message
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszFactorielle: .quad szFactorielle
qAdrszFibonacci: .quad szFibonacci
qAdrszMessError: .quad szMessError
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessResult: .quad szMessResult
qAdrsZoneConv: .quad sZoneConv
/******************************************************************/
/* factorielle function */
/******************************************************************/
/* x0 contains the Y combinator address */
/* x1 contains the number structure */
facFunc:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // save Y combinator address
ldr x0,[x1,#func_num] // load number
cmp x0,#1 // > 1 ?
bgt 1f // yes
mov x0,#1 // create structure number value 1
bl numFunc
b 100f
1:
mov x3,x0 // save number
sub x0,x0,#1 // decrement number
bl numFunc // and create new structure number
cmp x0,#-1 // allocation error ?
beq 100f
mov x1,x0 // new structure number -> param 1
ldr x0,[x2,#func_f_] // load function address to execute
bl callFunc // call
ldr x1,[x0,#func_num] // load new result
mul x0,x1,x3 // and multiply by precedent
bl numFunc // and create new structure number
// and return her address in x0
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* fibonacci function */
/******************************************************************/
/* x0 contains the Y combinator address */
/* x1 contains the number structure */
fibFunc:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x2,x0 // save Y combinator address
ldr x0,[x1,#func_num] // load number
cmp x0,#1 // > 1 ?
bgt 1f // yes
mov x0,#1 // create structure number value 1
bl numFunc
b 100f
1:
mov x3,x0 // save number
sub x0,x0,#1 // decrement number
bl numFunc // and create new structure number
cmp x0,#-1 // allocation error ?
beq 100f
mov x1,x0 // new structure number -> param 1
ldr x0,[x2,#func_f_] // load function address to execute
bl callFunc // call
ldr x4,[x0,#func_num] // load new result
sub x0,x3,#2 // new number - 2
bl numFunc // and create new structure number
cmp x0,#-1 // allocation error ?
beq 100f
mov x1,x0 // new structure number -> param 1
ldr x0,[x2,#func_f_] // load function address to execute
bl callFunc // call
ldr x1,[x0,#func_num] // load new result
add x0,x1,x4 // add two results
bl numFunc // and create new structure number
// and return her address in x0
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* call function */
/******************************************************************/
/* x0 contains the address of the function */
/* x1 contains the address of the function 1 */
callFunc:
stp x2,lr,[sp,-16]! // save registers
ldr x2,[x0,#func_fn] // load function address to execute
blr x2 // and call it
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* create Y combinator function */
/******************************************************************/
/* x0 contains the address of the function */
YFunc:
stp x1,lr,[sp,-16]! // save registers
mov x1,#0
bl newFunc
cmp x0,#-1 // allocation error ?
beq 100f
str x0,[x0,#func_f_] // store function and return in x0
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* create structure number function */
/******************************************************************/
/* x0 contains the number */
numFunc:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // save number
mov x0,#0 // function null
mov x1,#0 // function null
bl newFunc
cmp x0,#-1 // allocation error ?
beq 100f
str x2,[x0,#func_num] // store number in new structure
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* new function */
/******************************************************************/
/* x0 contains the function address */
/* x1 contains the function address 1 */
newFunc:
stp x1,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
stp x5,x8,[sp,-16]! // save registers
mov x4,x0 // save address
mov x5,x1 // save adresse 1
// allocation place on the heap
mov x0,#0 // allocation place heap
mov x8,BRK // call system 'brk'
svc #0
mov x6,x0 // save address heap for output string
add x0,x0,#func_fin // reservation place one element
mov x8,BRK // call system 'brk'
svc #0
cmp x0,#-1 // allocation error
beq 100f
mov x0,x6
str x4,[x0,#func_fn] // store address
str x5,[x0,#func_f_]
str xzr,[x0,#func_num] // store zero to number
100:
ldp x5,x8,[sp],16 // restaur 2 registers
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #AppleScript | AppleScript | set n to 5 -- Size of zig-zag matrix (n^2 cells).
-- Create an empty matrix.
set m to {}
repeat with i from 1 to n
set R to {}
repeat with j from 1 to n
set end of R to 0
end repeat
set end of m to R
end repeat
-- Populate the matrix in a zig-zag manner.
set {x, y, v, d} to {1, 1, 0, 1}
repeat while v < (n ^ 2)
if 1 ≤ x and x ≤ n and 1 ≤ y and y ≤ n then
set {m's item y's item x, x, y, v} to {v, x + d, y - d, v + 1}
else if x > n then
set {x, y, d} to {n, y + 2, -d}
else if y > n then
set {x, y, d} to {x + 2, n, -d}
else if x < 1 then
set {x, y, d} to {1, y, -d}
else if y < 1 then
set {x, y, d} to {x, 1, -d}
end if
end repeat
--> R = {{0, 1, 5, 6, 14}, {2, 4, 7, 13, 15}, {3, 8, 12, 16, 21}, {9, 11, 17, 20, 22}, {10, 18, 19, 23, 24}}
-- Reformat the matrix into a table for viewing.
repeat with i in m
repeat with j in i
set j's contents to (characters -(length of (n ^ 2 as string)) thru -1 of (" " & j)) as string
end repeat
set end of i to return
end repeat
return return & m as string |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Factor | Factor | USING: accessors assocs colors.constants
combinators.short-circuit io kernel math prettyprint sequences
sets ui ui.gadgets ui.gadgets.charts ui.gadgets.charts.lines ;
: yellowstone? ( n hs seq -- ? )
{
[ drop in? not ]
[ nip last gcd nip 1 = ]
[ nip dup length 2 - swap nth gcd nip 1 > ]
} 3&& ;
: next-yellowstone ( hs seq -- n )
[ 4 ] 2dip [ 3dup yellowstone? ] [ [ 1 + ] 2dip ] until
2drop ;
: next ( hs seq -- hs' seq' )
2dup next-yellowstone [ suffix! ] [ pick adjoin ] bi ;
: <yellowstone> ( n -- seq )
[ HS{ 1 2 3 } clone dup V{ } set-like ] dip dup 3 <=
[ head nip ] [ 3 - [ next ] times nip ] if ;
! Show first 30 Yellowstone numbers.
"First 30 Yellowstone numbers:" print
30 <yellowstone> [ pprint bl ] each nl
! Plot first 100 Yellowstone numbers.
chart new { { 0 100 } { 0 175 } } >>axes
line new COLOR: blue >>color
100 <iota> 100 <yellowstone> zip >>data
add-gadget "Yellowstone numbers" open-window |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Forth | Forth | : array create cells allot ;
: th cells + ; \ some helper words
30 constant #yellow \ number of yellowstones
#yellow array y \ create array
( n1 n2 -- n3)
: gcd dup if tuck mod recurse exit then drop ;
: init 3 0 do i 1+ y i th ! loop ; ( --)
: show cr #yellow 0 do y i th ? loop ; ( --)
: gcd-y[] - cells y + @ over gcd ; ( k i n -- k gcd )
: loop1 begin 1+ over 2 gcd-y[] 1 = >r over 1 gcd-y[] 1 > r> or 0= until ;
: loop2 over true swap 0 ?do over y i th @ = if 0= leave then loop ;
: yellow #yellow 3 do i 3 begin loop1 loop2 until y rot th ! loop ;
: main init yellow show ;
main |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #C.23 | C# | using System;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class YahooSearch {
private string query;
private string content;
private int page;
const string yahoo = "http://search.yahoo.com/search?";
public YahooSearch(string query) : this(query, 0) { }
public YahooSearch(string query, int page) {
this.query = query;
this.page = page;
this.content = new WebClient()
.DownloadString(
string.Format(yahoo + "p={0}&b={1}", query, this.page * 10 + 1)
);
}
public YahooResult[] Results {
get {
List<YahooResult> results = new List<YahooResult>();
Func<string, string, string> substringBefore = (str, before) =>
{
int iHref = str.IndexOf(before);
return iHref < 0 ? "" : str.Substring(0, iHref);
};
Func<string, string, string> substringAfter = (str, after) =>
{
int iHref = str.IndexOf(after);
return iHref < 0 ? "" : str.Substring(iHref + after.Length);
};
Converter<string, string> getText = p =>
Regex.Replace(p, "<[^>]*>", x => "");
Regex rx = new Regex(@"
<li>
<div \s class=""res"">
<div>
<h3>
<a \s (?'LinkAttributes'[^>]+)>
(?'LinkText' .*?)
(?></a>)
</h3>
</div>
<div \s class=""abstr"">
(?'Abstract' .*?)
(?></div>)
.*?
(?></div>)
</li>",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.ExplicitCapture
);
foreach (Match e in rx.Matches(this.content)) {
string rurl = getText(substringBefore(substringAfter(
e.Groups["LinkAttributes"].Value, @"href="""), @""""));
string rtitle = getText(e.Groups["LinkText"].Value);
string rcontent = getText(e.Groups["Abstract"].Value);
results.Add(new YahooResult(rurl, rtitle, rcontent));
}
return results.ToArray();
}
}
public YahooSearch NextPage() {
return new YahooSearch(this.query, this.page + 1);
}
public YahooSearch GetPage(int page) {
return new YahooSearch(this.query, page);
}
}
class YahooResult {
public string URL { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public YahooResult(string url, string title, string content) {
this.URL = url;
this.Title = title;
this.Content = content;
}
public override string ToString()
{
return string.Format("\nTitle: {0}\nLink: {1}\nText: {2}",
Title, URL, Content);
}
}
// Usage:
class Prog {
static void Main() {
foreach (int page in new[] { 0, 1 })
{
YahooSearch x = new YahooSearch("test", page);
foreach (YahooResult result in x.Results)
{
Console.WriteLine(result);
}
}
}
}
|
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.
| #Scheme | Scheme |
(import (scheme base)
(scheme char)
(scheme cxr)
(scheme write)
(srfi 1 lists))
;; convert a string into a list of tokens
(define (string->tokens str)
(define (next-token chars)
(cond ((member (car chars) (list #\+ #\- #\* #\/) char=?)
(values (cdr chars)
(cdr (assq (car chars) ; convert char for op into op procedure, using a look up list
(list (cons #\+ +) (cons #\- -) (cons #\* *) (cons #\/ /))))))
((member (car chars) (list #\( #\)) char=?)
(values (cdr chars)
(if (char=? (car chars) #\()
'open
'close)))
(else ; read a multi-digit positive integer
(let loop ((rem chars)
(res 0))
(if (and (not (null? rem))
(char-numeric? (car rem)))
(loop (cdr rem)
(+ (* res 10)
(- (char->integer (car rem))
(char->integer #\0))))
(values rem
res))))))
;
(let loop ((chars (remove char-whitespace? (string->list str)))
(tokens '()))
(if (null? chars)
(reverse tokens)
(let-values (((remaining-chars token) (next-token chars)))
(loop remaining-chars
(cons token tokens))))))
;; turn list of tokens into an AST
;; -- using recursive descent parsing to obey laws of precedence
(define (parse tokens)
(define (parse-factor tokens)
(if (number? (car tokens))
(values (car tokens) (cdr tokens))
(let-values (((expr rem) (parse-expr (cdr tokens))))
(values expr (cdr rem)))))
(define (parse-term tokens)
(let-values (((left-expr rem) (parse-factor tokens)))
(if (and (not (null? rem))
(member (car rem) (list * /)))
(let-values (((right-expr remr) (parse-term (cdr rem))))
(values (list (car rem) left-expr right-expr)
remr))
(values left-expr rem))))
(define (parse-part tokens)
(let-values (((left-expr rem) (parse-term tokens)))
(if (and (not (null? rem))
(member (car rem) (list + -)))
(let-values (((right-expr remr) (parse-part (cdr rem))))
(values (list (car rem) left-expr right-expr)
remr))
(values left-expr rem))))
(define (parse-expr tokens)
(let-values (((expr rem) (parse-part tokens)))
(values expr rem)))
;
(let-values (((expr rem) (parse-expr tokens)))
(if (null? rem)
expr
(error "Misformed expression"))))
;; evaluate the AST, returning a number
(define (eval-expression ast)
(cond ((number? ast)
ast)
((member (car ast) (list + - * /))
((car ast)
(eval-expression (cadr ast))
(eval-expression (caddr ast))))
(else
(error "Misformed expression"))))
;; parse and evaluate the given string
(define (interpret str)
(eval-expression (parse (string->tokens str))))
;; running some examples
(for-each
(lambda (str)
(display
(string-append str
" => "
(number->string (interpret str))))
(newline))
'("1 + 2" "20+4*5" "1/2+5*(6-3)" "(1+3)/4-1" "(1 - 5) * 2 / (20 + 1)"))
|
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Racket | Racket | #lang racket (require math)
(define sqrt5 (sqrt 5))
(define phi (* 0.5 (+ 1 sqrt5)))
;; What is the nth fibonnaci number, shifted by 2 so that
;; F(0) = 1, F(1) = 2, ...?
;;
(define (F n)
(fibonacci (+ n 2)))
;; What is the largest n such that F(n) <= m?
;;
(define (F* m)
(let ([n (- (inexact->exact (round (/ (log (* m sqrt5)) (log phi)))) 2)])
(if (<= (F n) m) n (sub1 n))))
(define (zeck->natural z)
(for/sum ([i (reverse z)]
[j (in-naturals)])
(* i (F j))))
(define (natural->zeck n)
(if (zero? n)
null
(for/list ([i (in-range (F* n) -1 -1)])
(let ([f (F i)])
(cond [(>= n f) (set! n (- n f))
1]
[else 0])))))
; Extend list to the right to a length of len with repeated padding elements
;
(define (pad lst len [padding 0])
(append lst (make-list (- len (length lst)) padding)))
; Strip padding elements from the left of the list
;
(define (unpad lst [padding 0])
(cond [(null? lst) lst]
[(equal? (first lst) padding) (unpad (rest lst) padding)]
[else lst]))
;; Run a filter function across a window in a list from left to right
;;
(define (left->right width fn)
(λ (lst)
(let F ([a lst])
(if (< (length a) width)
a
(let ([f (fn (take a width))])
(cons (first f) (F (append (rest f) (drop a width)))))))))
;; Run a function fn across a window in a list from right to left
;;
(define (right->left width fn)
(λ (lst)
(let F ([a lst])
(if (< (length a) width)
a
(let ([f (fn (take-right a width))])
(append (F (append (drop-right a width) (drop-right f 1)))
(list (last f))))))))
;; (a0 a1 a2 ... an) -> (a0 a1 a2 ... (fn ... an))
;;
(define (replace-tail width fn)
(λ (lst)
(append (drop-right lst width) (fn (take-right lst width)))))
(define (rule-a lst)
(match lst
[(list 0 2 0 x) (list 1 0 0 (add1 x))]
[(list 0 3 0 x) (list 1 1 0 (add1 x))]
[(list 0 2 1 x) (list 1 1 0 x)]
[(list 0 1 2 x) (list 1 0 1 x)]
[else lst]))
(define (rule-a-tail lst)
(match lst
[(list x 0 3 0) (list x 1 1 1)]
[(list x 0 2 0) (list x 1 0 1)]
[(list 0 1 2 0) (list 1 0 1 0)]
[(list x y 0 3) (list x y 1 1)]
[(list x y 0 2) (list x y 1 0)]
[(list x 0 1 2) (list x 1 0 0)]
[else lst]))
(define (rule-b lst)
(match lst
[(list 0 1 1) (list 1 0 0)]
[else lst]))
(define (rule-c lst)
(match lst
[(list 1 0 0) (list 0 1 1)]
[(list 1 -1 0) (list 0 0 1)]
[(list 1 -1 1) (list 0 0 2)]
[(list 1 0 -1) (list 0 1 0)]
[(list 2 0 0) (list 1 1 1)]
[(list 2 -1 0) (list 1 0 1)]
[(list 2 -1 1) (list 1 0 2)]
[(list 2 0 -1) (list 1 1 0)]
[else lst]))
(define (zeck-combine op y z [f identity])
(let* ([bits (max (add1 (length y)) (add1 (length z)) 4)]
[f0 (λ (x) (pad (reverse x) bits))]
[f1 (left->right 4 rule-a)]
[f2 (replace-tail 4 rule-a-tail)]
[f3 (right->left 3 rule-b)]
[f4 (left->right 3 rule-b)])
((compose1 unpad f4 f3 f2 f1 f reverse) (map op (f0 y) (f0 z)))))
(define (zeck+ y z)
(zeck-combine + y z))
(define (zeck- y z)
(when (zeck< y z) (error (format "~a" `(zeck-: cannot subtract since ,y < ,z))))
(zeck-combine - y z (left->right 3 rule-c)))
(define (zeck* y z)
(define (M ry Zn Zn_1 [acc null])
(if (null? ry)
acc
(M (rest ry) (zeck+ Zn Zn_1) Zn
(if (zero? (first ry)) acc (zeck+ acc Zn)))))
(cond [(zeck< z y) (zeck* z y)]
[(null? y) null] ; 0 * z -> 0
[else (M (reverse y) z z)]))
(define (zeck-quotient/remainder y z)
(define (M Zn acc)
(if (zeck< y Zn)
(drop-right acc 1)
(M (zeck+ Zn (first acc)) (cons Zn acc))))
(define (D x m [acc null])
(if (null? m)
(values (reverse acc) x)
(let* ([v (first m)]
[smaller (zeck< v x)]
[bit (if smaller 1 0)]
[x_ (if smaller (zeck- x v) x)])
(D x_ (rest m) (cons bit acc)))))
(D y (M z (list z))))
(define (zeck-quotient y z)
(let-values ([(quotient _) (zeck-quotient/remainder y z)])
quotient))
(define (zeck-remainder y z)
(let-values ([(_ remainder) (zeck-quotient/remainder y z)])
remainder))
(define (zeck-add1 z)
(zeck+ z '(1)))
(define (zeck= y z)
(equal? (unpad y) (unpad z)))
(define (zeck< y z)
; Compare equal-length unpadded zecks
(define (LT a b)
(if (null? a)
#f
(let ([a0 (first a)] [b0 (first b)])
(if (= a0 b0)
(LT (rest a) (rest b))
(= a0 0)))))
(let* ([a (unpad y)] [len-a (length a)]
[b (unpad z)] [len-b (length b)])
(cond [(< len-a len-b) #t]
[(> len-a len-b) #f]
[else (LT a b)])))
(define (zeck> y z)
(not (or (zeck= y z) (zeck< y z))))
;; Examples
;;
(define (example op-name op a b)
(let* ([y (natural->zeck a)]
[z (natural->zeck b)]
[x (op y z)]
[c (zeck->natural x)])
(printf "~a ~a ~a = ~a ~a ~a = ~a = ~a\n"
a op-name b y op-name z x c)))
(example '+ zeck+ 888 111)
(example '- zeck- 888 111)
(example '* zeck* 8 111)
(example '/ zeck-quotient 9876 1000)
(example '% zeck-remainder 9876 1000)
|
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Raku | Raku | addition: +z
subtraction: -z
multiplication: *z
division: /z (more of a divmod really)
post increment: ++z
post decrement: --z
|
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Phix | Phix | function isPartSum(sequence f, integer l, t)
if t=0 then return true end if
if l=0 then return false end if
integer last = f[l]
return (t>=last and isPartSum(f, l-1, t-last))
or isPartSum(f, l-1, t)
end function
function isZumkeller(integer n)
sequence f = factors(n,1)
integer t = sum(f)
-- an odd sum cannot be split into two equal sums
if remainder(t,2)=1 then return false end if
-- if n is odd use 'abundant odd number' optimization
if remainder(n,2)=1 then
integer abundance := t - 2*n
return abundance>0 and remainder(abundance,2)=0
end if
-- if n and t both even check for any partition of t/2
return isPartSum(f, length(f), t/2)
end function
sequence tests = {{220,1,0,20,"%3d "},
{40,2,0,10,"%5d "},
{40,2,5,8,"%7d "}}
integer lim, step, rem, cr; string fmt
for t=1 to length(tests) do
{lim, step, rem, cr, fmt} = tests[t]
string odd = iff(step=1?"":"odd "),
wch = iff(rem=0?"":"which don't end in 5 ")
printf(1,"The first %d %sZumkeller numbers %sare:\n",{lim,odd,wch})
integer i = step+1, count = 0
while count<lim do
if (rem=0 or remainder(i,10)!=rem)
and isZumkeller(i) then
printf(1,fmt,i)
count += 1
if remainder(count,cr)=0 then puts(1,"\n") end if
end if
i += step
end while
printf(1,"\n")
end for
|
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Erlang | Erlang |
-module(arbitrary).
-compile([export_all]).
pow(B,E) when E > 0 ->
pow(B,E,1).
pow(_,0,_) -> 0;
pow(B,1,Acc) -> Acc * B;
pow(B,P,Acc) when P rem 2 == 0 ->
pow(B*B,P div 2, Acc);
pow(B,P,Acc) ->
pow(B,P-1,Acc*B).
test() ->
I = pow(5,pow(4,pow(3,2))),
S = integer_to_list(I),
L = length(S),
Prefix = lists:sublist(S,20),
Suffix = lists:sublist(S,L-19,20),
io:format("Length: ~b~nPrefix:~s~nSuffix:~s~n",[L,Prefix,Suffix]).
|
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
| #Phix | Phix | with javascript_semantics
constant n = {{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0}};
function AB(sequence text, integer y, x, step)
integer wtb = 0, bn = 0
integer prev = '#', next
string p2468 = ""
for i=1 to length(n) do
next = text[y+n[i][1]][x+n[i][2]]
wtb += (prev='.' and next<='#')
bn += (i>1 and next<='#')
if and_bits(i,1)=0 then p2468 = append(p2468,prev) end if
prev = next
end for
if step=2 then -- make it p6842
p2468 = p2468[3..4]&p2468[1..2]
end if
return {wtb,bn,p2468}
end function
procedure Zhang_Suen(sequence text)
integer wtb, bn, changed, changes
string p2468 -- (p6842 for step 2)
text = split(text,'\n')
while 1 do
changed = 0
for step=1 to 2 do
changes = 0
for y=2 to length(text)-1 do
for x=2 to length(text[y])-1 do
if text[y][x]='#' then
{wtb,bn,p2468} = AB(text,y,x,step)
if wtb=1
and bn>=2 and bn<=6
and find('.',p2468[1..3])
and find('.',p2468[2..4])then
changes = 1
text[y][x] = '!' -- (logically still black)
end if
end if
end for
end for
if changes then
for y=2 to length(text)-1 do
text[y] = substitute(text[y],"!",".")
end for
changed = 1
end if
end for
if not changed then exit end if
end while
puts(1,join(text,"\n"))
end procedure
string small_rc = """
................................
.#########.......########.......
.###...####.....####..####......
.###....###.....###....###......
.###...####.....###.............
.#########......###.............
.###.####.......###....###......
.###..####..###.####..####.###..
.###...####.###..########..###..
................................"""
Zhang_Suen(small_rc)
|
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
| #FreeBASIC | FreeBASIC | ' version 17-10-2016
' compile with: fbc -s console
#Define max 92 ' max for Fibonacci number
Dim Shared As ULongInt fib(max)
fib(0) = 1
fib(1) = 1
For x As Integer = 2 To max
fib(x) = fib(x-1) + fib(x-2)
Next
Function num2zeck(n As Integer) As String
If n < 0 Then
Print "Error: no negative numbers allowed"
Beep : Sleep 5000,1 : End
End If
If n < 2 Then Return Str(n)
Dim As String zeckendorf
For x As Integer = max To 1 Step -1
If fib(x) <= n Then
zeckendorf = zeckendorf + "1"
n = n - fib(x)
Else
zeckendorf = zeckendorf + "0"
End If
Next
return LTrim(zeckendorf, "0") ' get rid of leading zeroes
End Function
' ------=< MAIN >=------
Dim As Integer x, e
Dim As String zeckendorf
Print "number zeckendorf"
For x = 0 To 200000
zeckendorf = num2zeck(x)
If x <= 20 Then Print x, zeckendorf
' check for two consecutive Fibonacci numbers
If InStr(zeckendorf, "11") <> 0 Then
Print " Error: two consecutive Fibonacci numbers "; x, zeckendorf
e = e +1
End If
Next
Print
If e = 0 Then
Print " No Zeckendorf numbers with two consecutive Fibonacci numbers found"
Else
Print e; " error(s) found"
End If
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
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.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript |
for i=1:1:100 {
set doors(i) = 0
}
for i=1:1:100 {
for door=i:i:100 {
Set doors(door)='doors(door)
}
}
for i = 1:1:100
{
if doors(i)=1 write i_": 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)
| #Explore | Explore | > Array.create 6 'A';;
val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
> Array.init 8 (fun i -> i * 10) ;;
val it : int [] = [|0; 10; 20; 30; 40; 50; 60; 70|]
> let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;;
val arr : int [] = [|0; 1; 2; 3; 4; 5; 6|]
> arr.[4];;
val it : int = 4
> arr.[4] <- 65 ;;
val it : unit = ()
> arr;;
val it : int [] = [|0; 1; 2; 3; 65; 5; 6|] |
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.
| #PureBasic | PureBasic | Structure Complex
real.d
imag.d
EndStructure
Procedure Add_Complex(*A.Complex, *B.Complex)
Protected *R.Complex=AllocateMemory(SizeOf(Complex))
If *R
*R\real=*A\real+*B\real
*R\imag=*A\imag+*B\imag
EndIf
ProcedureReturn *R
EndProcedure
Procedure Inv_Complex(*A.Complex)
Protected *R.Complex=AllocateMemory(SizeOf(Complex)), denom.d
If *R
denom = *A\real * *A\real + *A\imag * *A\imag
*R\real= *A\real / denom
*R\imag=-*A\imag / denom
EndIf
ProcedureReturn *R
EndProcedure
Procedure Mul_Complex(*A.Complex, *B.Complex)
Protected *R.Complex=AllocateMemory(SizeOf(Complex))
If *R
*R\real=*A\real * *B\real - *A\imag * *B\imag
*R\imag=*A\real * *B\imag + *A\imag * *B\real
EndIf
ProcedureReturn *R
EndProcedure
Procedure Neg_Complex(*A.Complex)
Protected *R.Complex=AllocateMemory(SizeOf(Complex))
If *R
*R\real=-*A\real
*R\imag=-*A\imag
EndIf
ProcedureReturn *R
EndProcedure
Procedure ShowAndFree(Header$, *Complex.Complex)
If *Complex
Protected.d i=*Complex\imag, r=*Complex\real
Print(LSet(Header$,7))
Print("= "+StrD(r,3))
If i>=0: Print(" + ")
Else: Print(" - ")
EndIf
PrintN(StrD(Abs(i),3)+"i")
FreeMemory(*Complex)
EndIf
EndProcedure
If OpenConsole()
Define.Complex a, b, *c
a\real=1.0: a\imag=1.0
b\real=#PI: b\imag=1.2
*c=Add_Complex(a,b): ShowAndFree("a+b", *c)
*c=Mul_Complex(a,b): ShowAndFree("a*b", *c)
*c=Inv_Complex(a): ShowAndFree("Inv(a)", *c)
*c=Neg_Complex(a): ShowAndFree("-a", *c)
Print(#CRLF$+"Press ENTER to exit"):Input()
EndIf |
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
| #Scala | Scala | class Rational(n: Long, d:Long) extends Ordered[Rational]
{
require(d!=0)
private val g:Long = gcd(n, d)
val numerator:Long = n/g
val denominator:Long = d/g
def this(n:Long)=this(n,1)
def +(that:Rational):Rational=new Rational(
numerator*that.denominator + that.numerator*denominator,
denominator*that.denominator)
def -(that:Rational):Rational=new Rational(
numerator*that.denominator - that.numerator*denominator,
denominator*that.denominator)
def *(that:Rational):Rational=
new Rational(numerator*that.numerator, denominator*that.denominator)
def /(that:Rational):Rational=
new Rational(numerator*that.denominator, that.numerator*denominator)
def unary_~ :Rational=new Rational(denominator, numerator)
def unary_- :Rational=new Rational(-numerator, denominator)
def abs :Rational=new Rational(Math.abs(numerator), Math.abs(denominator))
override def compare(that:Rational):Int=
(this.numerator*that.denominator-that.numerator*this.denominator).toInt
override def toString()=numerator+"/"+denominator
private def gcd(x:Long, y:Long):Long=
if(y==0) x else gcd(y, x%y)
}
object Rational
{
def apply(n: Long, d:Long)=new Rational(n,d)
def apply(n:Long)=new Rational(n)
implicit def longToRational(i:Long)=new Rational(i)
} |
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
| #Vlang | Vlang | import math
const ep = 1e-14
fn agm(aa f64, gg f64) f64 {
mut a, mut g := aa, gg
for math.abs(a-g) > math.abs(a)*ep {
t := a
a, g = (a+g)*.5, math.sqrt(t*g)
}
return a
}
fn main() {
println(agm(1.0, 1.0/math.sqrt2))
} |
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
| #Wren | Wren | var eps = 1e-14
var agm = Fn.new { |a, g|
while ((a-g).abs > a.abs * eps) {
var t = a
a = (a+g)/2
g = (t*g).sqrt
}
return a
}
System.print(agm.call(1, 1/2.sqrt)) |
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
| #Julia | Julia | using Printf
const types = (Complex, Float64, Rational, Int, Bool)
for Tb in types, Te in types
zb, ze = zero(Tb), zero(Te)
r = zb ^ ze
@printf("%10s ^ %-10s = %7s ^ %-7s = %-12s (%s)\n", Tb, Te, zb, ze, r, typeof(r))
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
| #K | K |
0^0
1.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
| #Klingphix | Klingphix | :mypower
dup not (
[ drop sign dup 0 equal [ drop 1 ] if ]
[ power ]
) if
;
0 0 mypower print nl
"End " input |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #68000_Assembly | 68000 Assembly | pushall: MOVEM.L D0-D7/A0-A6,-(SP)
popall: MOVEM.L (SP)+,D0-D7/A0-A6
pushWord: MOVE.W <argument>,-(SP)
popWord: MOVE.W (SP)+,<argument>
|
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
INCLUDE "D2:CIRCLE.ACT" ;from the Action! Tool Kit
PROC YinYang(INT x BYTE y BYTE r)
INT i,a,b,rr,r2,rr2,r5,rr5,y1,y2
REAL tmp1,tmp2
Circle(x,y,r,1)
rr=r*r
r2=r/2 rr2=rr/4
Color=1
FOR i=0 TO r
DO
a=rr-i*i
IntToReal(a,tmp1)
Sqrt(tmp1,tmp2)
a=RealToInt(tmp2)
b=rr2-(i-r2)*(i-r2)
IntToReal(b,tmp1)
Sqrt(tmp1,tmp2)
b=RealToInt(tmp2)
Plot(x+b,y-i) DrawTo(x+a,y-i)
Plot(x-b,y+i) DrawTo(x+a,y+i)
OD
r5=r/5
rr5=rr/25
y1=y-r2 y2=y+r2
FOR i=0 TO r5
DO
a=rr5-i*i
IntToReal(a,tmp1)
Sqrt(tmp1,tmp2)
a=RealToInt(tmp2)
Color=1
Plot(x-a,y1-i) DrawTo(x+a,y1-i)
Plot(x-a,y1+i) DrawTo(x+a,y1+i)
Color=0
Plot(x-a,y2-i) DrawTo(x+a,y2-i)
Plot(x-a,y2+i) DrawTo(x+a,y2+i)
OD
RETURN
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
Graphics(8+16)
MathInit()
COLOR1=$00
COLOR2=$0F
YinYang(180,120,60)
YinYang(100,40,30)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #ALGOL_68 | ALGOL 68 | BEGIN
MODE F = PROC(INT)INT;
MODE Y = PROC(Y)F;
# compare python Y = lambda f: (lambda x: x(x)) (lambda y: f( lambda *args: y(y)(*args)))#
PROC y = (PROC(F)F f)F: ( (Y x)F: x(x)) ( (Y z)F: f((INT arg )INT: z(z)( arg )));
PROC fib = (F f)F: (INT n)INT: CASE n IN n,n OUT f(n-1) + f(n-2) ESAC;
FOR i TO 10 DO print(y(fib)(i)) OD
END |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #Applesoft_BASIC | Applesoft BASIC | 100 S = 5
110 S2 = S ^ 2 : REM SQUARED
120 H = S2 / 2 : REM HALFWAY
130 S2 = S2 - 1
140 DX = 1 : REM INITIAL
150 DY = 0 : REM DIRECTION
160 N = S - 1
170 DIM A%(N, N)
200 FOR I = 0 TO H
210 A%(X, Y) = I
220 A%(N - X, N - Y) = S2 - I
230 X = X + DX
240 Y = Y + DY
250 IF Y = 0 THEN DY = DY + 1 : IF DY THEN DX = -DX
260 IF X = 0 THEN DX = DX + 1 : IF DX THEN DY = -DY
270 NEXT I
300 FOR Y = 0 TO N
310 FOR X = 0 TO N
320 IF X THEN PRINT TAB(X * (LEN(STR$(S2)) + 1) + 1);
330 PRINT A%(X, Y);
340 NEXT X
350 PRINT
360 NEXT Y |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #FreeBASIC | FreeBASIC | function gcd(a as uinteger, b as uinteger) as uinteger
if b = 0 then return a
return gcd( b, a mod b )
end function
dim as uinteger i, j, k, Y(1 to 100)
Y(1) = 1 : Y(2) = 2: Y(3) = 3
for i = 4 to 100
k = 3
print i
do
k += 1
if gcd( k, Y(i-2) ) = 1 orelse gcd( k, Y(i-1) ) > 1 then continue do
for j = 1 to i-1
if Y(j)=k then continue do
next j
Y(i) = k
exit do
loop
next i
for i = 1 to 30
print str(Y(i))+" ";
next i
print
screen 13
for i = 1 to 100
pset (i, 200-Y(i)), 31
next i
while inkey=""
wend
end |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Go | Go | package main
import (
"fmt"
"log"
"os/exec"
)
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
func yellowstone(n int) []int {
m := make(map[int]bool)
a := make([]int, n+1)
for i := 1; i < 4; i++ {
a[i] = i
m[i] = true
}
min := 4
for c := 4; c <= n; c++ {
for i := min; ; i++ {
if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
a[c] = i
m[i] = true
if i == min {
min++
}
break
}
}
}
return a[1:]
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
x := make([]int, 100)
for i := 0; i < 100; i++ {
x[i] = i + 1
}
y := yellowstone(100)
fmt.Println("The first 30 Yellowstone numbers are:")
fmt.Println(y[:30])
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
check(err)
check(g.Start())
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %d\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
} |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #D | D | import std.stdio, std.exception, std.regex, std.algorithm, std.string,
std.net.curl;
struct YahooResult {
string url, title, content;
string toString() const {
return "\nTitle: %s\nLink: %s\nText: %s"
.format(title, url, content);
}
}
struct YahooSearch {
private string query, content;
private uint page;
this(in string query_, in uint page_ = 0) {
this.query = query_;
this.page = page_;
this.content = "http://search.yahoo.com/search?p=%s&b=%d"
.format(query, page * 10 + 1).get.assumeUnique;
}
@property results() const {
immutable re = `<li>
<div \s class="res">
<div>
<h3>
<a \s (?P<linkAttributes> [^>]+)>
(?P<linkText> .*?)
</a>
</h3>
</div>
<div \s class="abstr">
(?P<abstract> .*?)
</div>
.*?
</div>
</li>`;
const clean = (string s) => s.replace("<[^>]*>".regex("g"),"");
return content.match(re.regex("gx")).map!(m => YahooResult(
clean(m.captures["linkAttributes"]
.findSplitAfter(`href="`)[1]
.findSplitBefore(`"`)[0]),
clean(m.captures["linkText"]),
clean(m.captures["abstract"])
));
}
YahooSearch nextPage() const {
return YahooSearch(query, page + 1);
}
}
void main() {
writefln("%(%s\n%)", "test".YahooSearch.results);
} |
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.
| #Sidef | Sidef | func evalArithmeticExp(s) {
func evalExp(s) {
func operate(s, op) {
s.split(op).map{|c| Number(c) }.reduce(op)
}
func add(s) {
operate(s.sub(/^\+/,'').sub(/\++/,'+'), '+')
}
func subtract(s) {
s.gsub!(/(\+-|-\+)/,'-')
if (s ~~ /--/) {
return(add(s.sub(/--/,'+')))
}
var b = s.split('-')
b.len == 3 ? (-1*Number(b[1]) - Number(b[2]))
: operate(s, '-')
}
s.gsub!(/[()]/,'').gsub!(/-\+/, '-')
var reM = /\*/
var reMD = %r"(\d+\.?\d*\s*[*/]\s*[+-]?\d+\.?\d*)"
var reA = /\d\+/
var reAS = /(-?\d+\.?\d*\s*[+-]\s*[+-]?\d+\.?\d*)/
while (var match = reMD.match(s)) {
match[0] ~~ reM
? s.sub!(reMD, operate(match[0], '*').to_s)
: s.sub!(reMD, operate(match[0], '/').to_s)
}
while (var match = reAS.match(s)) {
match[0] ~~ reA
? s.sub!(reAS, add(match[0]).to_s)
: s.sub!(reAS, subtract(match[0]).to_s)
}
return s
}
var rePara = /(\([^\(\)]*\))/
s.split!.join!('').sub!(/^\+/,'')
while (var match = s.match(rePara)) {
s.sub!(rePara, evalExp(match[0]))
}
return Number(evalExp(s))
} |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Scala | Scala |
import scala.collection.mutable.ListBuffer
object ZeckendorfArithmetic extends App {
val elapsed: (=> Unit) => Long = f => {
val s = System.currentTimeMillis
f
(System.currentTimeMillis - s) / 1000
}
val add: (Z, Z) => Z = (z1, z2) => z1 + z2
val subtract: (Z, Z) => Z = (z1, z2) => z1 - z2
val multiply: (Z, Z) => Z = (z1, z2) => z1 * z2
val divide: (Z, Z) => Option[Z] = (z1, z2) => z1 / z2
val modulo: (Z, Z) => Option[Z] = (z1, z2) => z1 % z2
val ops = Map(("+", add), ("-", subtract), ("*", multiply), ("/", divide), ("%", modulo))
val calcs = List(
(Z("101"), "+", Z("10100"))
, (Z("101"), "-", Z("10100"))
, (Z("101"), "*", Z("10100"))
, (Z("101"), "/", Z("10100"))
, (Z("-1010101"), "+", Z("10100"))
, (Z("-1010101"), "-", Z("10100"))
, (Z("-1010101"), "*", Z("10100"))
, (Z("-1010101"), "/", Z("10100"))
, (Z("1000101010"), "+", Z("10101010"))
, (Z("1000101010"), "-", Z("10101010"))
, (Z("1000101010"), "*", Z("10101010"))
, (Z("1000101010"), "/", Z("10101010"))
, (Z("10100"), "+", Z("1010"))
, (Z("100101"), "-", Z("100"))
, (Z("1010101010101010101"), "+", Z("-1010101010101"))
, (Z("1010101010101010101"), "-", Z("-1010101010101"))
, (Z("1010101010101010101"), "*", Z("-1010101010101"))
, (Z("1010101010101010101"), "/", Z("-1010101010101"))
, (Z("1010101010101010101"), "%", Z("-1010101010101"))
, (Z("1010101010101010101"), "+", Z("101010101010101"))
, (Z("1010101010101010101"), "-", Z("101010101010101"))
, (Z("1010101010101010101"), "*", Z("101010101010101"))
, (Z("1010101010101010101"), "/", Z("101010101010101"))
, (Z("1010101010101010101"), "%", Z("101010101010101"))
, (Z("10101010101010101010"), "+", Z("1010101010101010"))
, (Z("10101010101010101010"), "-", Z("1010101010101010"))
, (Z("10101010101010101010"), "*", Z("1010101010101010"))
, (Z("10101010101010101010"), "/", Z("1010101010101010"))
, (Z("10101010101010101010"), "%", Z("1010101010101010"))
, (Z("1010"), "%", Z("10"))
, (Z("1010"), "%", Z("-10"))
, (Z("-1010"), "%", Z("10"))
, (Z("-1010"), "%", Z("-10"))
, (Z("100"), "/", Z("0"))
, (Z("100"), "%", Z("0"))
)
val iadd: (BigInt, BigInt) => BigInt = (a, b) => a + b
val isub: (BigInt, BigInt) => BigInt = (a, b) => a - b
// just for result checking:
import Z._
val imul: (BigInt, BigInt) => BigInt = (a, b) => a * b
val idiv: (BigInt, BigInt) => Option[BigInt] = (a, b) => if (b == 0) None else Some(a / b)
val imod: (BigInt, BigInt) => Option[BigInt] = (a, b) => if (b == 0) None else Some(a % b)
val iops = Map(("+", iadd), ("-", isub), ("*", imul), ("/", idiv), ("%", imod))
case class Z(var zs: String) {
import Z._
require((zs.toSet -- Set('-', '0', '1') == Set()) && (!zs.contains("11")))
//--- fa(summand1.z,summand2.z) --------------------------
val fa: (BigInt, BigInt) => BigInt = (z1, z2) => {
val v = z1.toString.toCharArray.map(_.asDigit).reverse.padTo(5, 0).zipAll(z2.toString.toCharArray.map(_.asDigit).reverse, 0, 0)
val arr1 = (v.map(p => p._1 + p._2) :+ 0).reverse
(0 to arr1.length - 4) foreach { i => //stage1
val a = arr1.slice(i, i + 4).toList
val b = a.foldRight("")("" + _ + _) dropRight 1
val a1 = b match {
case "020" => List(1, 0, 0, a(3) + 1)
case "030" => List(1, 1, 0, a(3) + 1)
case "021" => List(1, 1, 0, a(3))
case "012" => List(1, 0, 1, a(3))
case _ => a
}
0 to 3 foreach { j => arr1(j + i) = a1(j) }
}
val arr2 = arr1.foldRight("")("" + _ + _)
.replace("0120", "1010").replace("030", "111").replace("003", "100").replace("020", "101")
.replace("003", "100").replace("012", "101").replace("021", "110")
.replace("02", "10").replace("03", "11")
.reverse.toArray
(0 to arr2.length - 3) foreach { i => //stage2, step1
val a = arr2.slice(i, i + 3).toList
val b = a.foldRight("")("" + _ + _)
val a1 = b match {
case "110" => List('0', '0', '1')
case _ => a
}
0 to 2 foreach { j => arr2(j + i) = a1(j) }
}
val arr3 = arr2.foldRight("")("" + _ + _).concat("0").reverse.toArray
(0 to arr3.length - 3) foreach { i => //stage2, step2
val a = arr3.slice(i, i + 3).toList
val b = a.foldRight("")("" + _ + _)
val a1 = b match {
case "011" => List('1', '0', '0')
case _ => a
}
0 to 2 foreach { j => arr3(j + i) = a1(j) }
}
BigInt(arr3.foldRight("")("" + _ + _))
}
//--- fs(minuend.z,subtrahend.z) -------------------------
val fs: (BigInt, BigInt) => BigInt = (min, sub) => {
val zmvr = min.toString.toCharArray.map(_.asDigit).reverse
val zsvr = sub.toString.toCharArray.map(_.asDigit).reverse.padTo(zmvr.length, 0)
val v = zmvr.zipAll(zsvr, 0, 0).reverse
val last = v.length - 1
val zma = zmvr.reverse.toArray
val zsa = zsvr.reverse.toArray
for (i <- (0 to last).reverse) {
val e = zma(i) - zsa(i)
if (e < 0) {
zma(i - 1) = zma(i - 1) - 1
zma(i) = 0
val part = Z(((i to last).map(zma(_))).foldRight("")("" + _ + _))
val carry = Z("1".padTo(last - i, "0").foldRight("")("" + _ + _))
val sum = part + carry
val sums = sum.z.toString
(1 to sum.size) foreach { j => zma(last - sum.size + j) = sums(j - 1).asDigit }
if (zma(i - 1) < 0) {
for (j <- (0 until i).reverse) {
if (zma(j) < 0) {
zma(j - 1) = zma(j - 1) - 1
zma(j) = 0
val part = Z(((j to last).map(zma(_))).foldRight("")("" + _ + _))
val carry = Z("1".padTo(last - j, "0").foldRight("")("" + _ + _))
val sum = part + carry
val sums = sum.z.toString
(1 to sum.size) foreach { k => zma(last - sum.size + k) = sums(k - 1).asDigit }
}
}
}
}
else zma(i) = e
zsa(i) = 0
}
BigInt(zma.foldRight("")("" + _ + _))
}
//--- fm(multiplicand.z,multplier.z) ---------------------
val fm: (BigInt, BigInt) => BigInt = (mc, mp) => {
val mct = mt(Z(mc.toString))
val mpxi = mp.toString.reverse.toCharArray.map(_.asDigit).zipWithIndex.filter(_._1 != 0).map(_._2)
mpxi.foldRight(Z("0"))((fi, sum) => sum + mct(fi)).z
}
//--- fd(dividend.z,divisor.z) ---------------------------
val fd: (BigInt, BigInt) => BigInt = (dd, ds) => {
val dst = dt(Z(dd.toString), Z(ds.toString)).reverse
var diff = Z(dd.toString)
val zd = ListBuffer[String]()
0 until dst.length foreach { i =>
if (dst(i) > diff) zd += "0" else {
diff = diff - dst(i)
zd += "1"
}
}
BigInt(zd.mkString)
}
val fasig: (Z, Z) => Int = (z1, z2) => if (z1.z.abs > z2.z.abs) z1.z.signum else z2.z.signum
val fssig: (Z, Z) => Int = (z1, z2) =>
if ((z1.z.abs > z2.z.abs && z1.z.signum > 0) || (z1.z.abs < z2.z.abs && z1.z.signum < 0)) 1 else -1
var z: BigInt = BigInt(zs)
override def toString: String = "" + z + "Z(i:" + z2i(this) + ")"
def size: Int = z.abs.toString.length
def ++ : Z = {
val za = this + Z("1")
this.zs = za.zs
this.z = za.z
this
}
def +(that: Z): Z =
if (this == Z("0")) that
else if (that == Z("0")) this
else if (this.z.signum == that.z.signum) Z((fa(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * this.z.signum).toString)
else if (this.z.abs == that.z.abs) Z("0")
else Z((fs(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * fasig(this, that)).toString)
def -- : Z = {
val zs = this - Z("1")
this.zs = zs.zs
this.z = zs.z
this
}
def -(that: Z): Z =
if (this == Z("0")) Z((that.z * (-1)).toString)
else if (that == Z("0")) this
else if (this.z.signum != that.z.signum) Z((fa(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * this.z.signum).toString)
else if (this.z.abs == that.z.abs) Z("0")
else Z((fs(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * fssig(this, that)).toString)
def %(that: Z): Option[Z] =
if (that == Z("0")) None
else if (this == Z("0")) Some(Z("0"))
else if (that == Z("1")) Some(Z("0"))
else if (this.z.abs < that.z.abs) Some(this)
else if (this.z == that.z) Some(Z("0"))
else this / that match {
case None => None
case Some(z) => Some(this - z * that)
}
def *(that: Z): Z =
if (this == Z("0") || that == Z("0")) Z("0")
else if (this == Z("1")) that
else if (that == Z("1")) this
else Z((fm(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * this.z.signum * that.z.signum).toString)
def /(that: Z): Option[Z] =
if (that == Z("0")) None
else if (this == Z("0")) Some(Z("0"))
else if (that == Z("1")) Some(Z("1"))
else if (this.z.abs < that.z.abs) Some(Z("0"))
else if (this.z == that.z) Some(Z("1"))
else Some(Z((fd(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * this.z.signum * that.z.signum).toString))
def <(that: Z): Boolean = this.z < that.z
def <=(that: Z): Boolean = this.z <= that.z
def >(that: Z): Boolean = this.z > that.z
def >=(that: Z): Boolean = this.z >= that.z
}
object Z {
// only for comfort and result checking:
val fibs: LazyList[BigInt] = {
def series(i: BigInt, j: BigInt): LazyList[BigInt] = i #:: series(j, i + j)
series(1, 0).tail.tail.tail
}
val z2i: Z => BigInt = z => z.z.abs.toString.toCharArray.map(_.asDigit).reverse.zipWithIndex.map { case (v, i) => v * fibs(i) }.foldRight(BigInt(0))(_ + _) * z.z.signum
var fmts: Map[Z, List[Z]] = Map(Z("0") -> List[Z](Z("0"))) //map of Fibonacci multiples table of divisors
// get division table (division weight vector)
def dt(dd: Z, ds: Z): List[Z] = {
val wv = new ListBuffer[Z]
wv ++= mt(ds)
var zs = ds.z.abs.toString
val upper = dd.z.abs.toString
while ((zs.length < upper.length)) {
wv += (wv.toList.last + wv.toList.reverse.tail.head)
zs = "1" + zs
}
wv.toList
}
// get multiply table from fmts
def mt(z: Z): List[Z] = {
fmts.getOrElse(z, Nil) match {
case Nil =>
val e = mwv(z)
fmts = fmts + (z -> e)
e
case l => l
}
}
// multiply weight vector
def mwv(z: Z): List[Z] = {
val wv = new ListBuffer[Z]
wv += z
wv += (z + z)
var zs = "11"
val upper = z.z.abs.toString
while ((zs.length < upper.length)) {
wv += (wv.toList.last + wv.toList.reverse.tail.head)
zs = "1" + zs
}
wv.toList
}
}
println("elapsed time: " + elapsed {
calcs foreach { case (op1, op, op2) => println("" + op1 + " " + op + " " + op2 + " = "
+ {
(ops(op)) (op1, op2) match {
case None => None
case Some(z) => z
case z => z
}
}
.ensuring { x =>
(iops(op)) (z2i(op1), z2i(op2)) match {
case None => None == x
case Some(i) => i == z2i(x.asInstanceOf[Z])
case i => i == z2i(x.asInstanceOf[Z])
}
})
}
} + " sec"
)
}
|
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #PicoLisp | PicoLisp | (de propdiv (N)
(make
(for I N
(and (=0 (% N I)) (link I)) ) ) )
(de sum? (G L)
(cond
((=0 G) T)
((= (car L) G) T)
((cdr L)
(if (> (car L) G)
(sum? G (cdr L))
(or
(sum? (- G (car L)) (cdr L))
(sum? G (cdr L)) ) ) ) ) )
(de zum? (N)
(let (L (propdiv N) S (sum prog L))
(and
(not (bit? 1 S))
(if (bit? 1 N)
(let A (- S (* 2 N))
(and (gt0 A) (not (bit? 1 A)))
)
(sum?
(- (/ S 2) (car L))
(cdr L) ) ) ) ) )
(zero C)
(for (I 2 (> 220 C) (inc I))
(when (zum? I)
(prin (align 3 I) " ")
(inc 'C)
(and
(=0 (% C 20))
(prinl) ) ) )
(prinl)
(zero C)
(for (I 1 (> 40 C) (inc 'I 2))
(when (zum? I)
(prin (align 9 I) " ")
(inc 'C)
(and
(=0 (% C 8))
(prinl) ) ) )
(prinl)
(zero C)
# cheater
(for (I 81079 (> 40 C) (inc 'I 2))
(when (and (<> 5 (% I 10)) (zum? I))
(prin (align 9 I) " ")
(inc 'C)
(and
(=0 (% C 8))
(prinl) ) ) ) |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Python | Python | from sympy import divisors
from sympy.combinatorics.subsets import Subset
def isZumkeller(n):
d = divisors(n)
s = sum(d)
if not s % 2 and max(d) <= s/2:
for x in range(1, 2**len(d)):
if sum(Subset.unrank_binary(x, d).subset) == s/2:
return True
return False
def printZumkellers(N, oddonly=False):
nprinted = 0
for n in range(1, 10**5):
if (oddonly == False or n % 2) and isZumkeller(n):
print(f'{n:>8}', end='')
nprinted += 1
if nprinted % 10 == 0:
print()
if nprinted >= N:
return
print("220 Zumkeller numbers:")
printZumkellers(220)
print("\n\n40 odd Zumkeller numbers:")
printZumkellers(40, True)
|
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #F.23 | F# | let () =
let answer = 5I **(int (4I ** (int (3I ** 2))))
let sans = answer.ToString()
printfn "Length = %d, digits %s ... %s" sans.Length (sans.Substring(0,20)) (sans.Substring(sans.Length-20))
;;
Length = 183231, digits 62060698786608744707 ... 92256259918212890625 |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Factor | Factor | USING: formatting kernel math.functions math.parser sequences ;
IN: rosettacode.bignums
: test-bignums ( -- )
5 4 3 2 ^ ^ ^ number>string
[ 20 head ] [ 20 tail* ] [ length ] tri
"5^4^3^2 is %s...%s and has %d digits\n" printf ; |
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
| #PL.2FI | PL/I | zhang: procedure options (main); /* 8 July 2014 */
declare pic(10) bit(32) initial (
'00000000000000000000000000000000'b,
'01111111110000000111111110000000'b,
'01110001111000001111001111000000'b,
'01110000111000001110000111000000'b,
'01110001111000001110000000000000'b,
'01111111110000001110000000000000'b,
'01110111100000001110000111000000'b,
'01110011110011101111001111011100'b,
'01110001111011100111111110011100'b,
'00000000000000000000000000000000'b );
declare image (10,32) bit(1) defined pic;
declare status (10,32) fixed decimal (1);
declare changes bit(1);
declare (i, j, k, m, n) fixed binary;
m = hbound(image,1); n = hbound(image,2);
call display;
/* Pixel labelling for pixels surrounding P1, co-ordinates (i,j). */
/* P9 P2 P3 */
/* P8 P1 P4 */
/* P7 P6 P5 */
do k = 1 to 10 until (^changes);
changes = '0'b;
/* Set conditions as follows: */
/* (0) The pixel is black and has eight neighbours */
/* (1) 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 */
status = -1;
do i = 2 to m-1;
do j = 2 to n-1;
if image(i,j) then
if B(i,j) >= 2 & B(i,j) <= 6 then
if A(i,j) = 1 then
if ^image(i-1,j) | ^image(i,j+1) | ^image(i+1,j) then
if ^image(i,j+1) | ^image(i+1,j) | ^image(i,j-1) then
status(i,j) = 4;
end;
end;
/* Having determined a status for every bit in the image, */
/* change those bits to white. */
do i = 2 to m-1;
do j = 2 to n-1;
if status(i,j) ^= -1 then do; image(i,j) = '0'b; changes = '1'b; end;
end;
end;
/* Set conditions as follows: */
/* (0) The pixel is black and has eight neighbours */
/* (1) 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 */
status = -1;
do i = 2 to m-1;
do j = 2 to n-1;
if image(i,j) then
if B(i,j) >= 2 & B(i,j) <= 6 then
if A(i,j) = 1 then
if ^image(i-1,j) | ^image(i,j+1) | ^image(i,j-1) then
if ^image(i-1,j) | ^image(i+1,j) | ^image(i,j-1) then
status(i,j) = 4;
end;
end;
/* Having determined a status for every bit in the image, */
/* change those bits to white. */
do i = 2 to m-1;
do j = 2 to n-1;
if status(i,j) ^= -1 then do; image(i,j) = '0'b; changes = '1'b; end;
end;
end;
end; /* of the "until" loop */
put skip list ('Final image after ' || trim(k) || ' iterations:');
call display;
display: procedure;
declare (i, j) fixed binary;
declare c character (1);
do i = 1 to m;
put skip edit ('row:', i) (A, F(3));
do j = 1 to n;
if image(i,j) then c = '.'; else c = ' ';
put edit (c) (A);
end;
end;
put skip;
end;
/* Returns the number of transitions from white to black from P2 through P9 and P2. */
A: procedure (i,j) returns (fixed binary);
declare (i,j) fixed binary nonassignable;
declare n(2:10) bit(1);
n(2) = image(i-1,j); n(3) = image(i-1,j+1);
n(4) = image(i, j+1); n(5) = image(i+1,j+1);
n(6) = image(i+1,j); n(7) = image(i+1,j-1);
n(8) = image(i,j-1); n(9) = image(i-1,j-1);
n(10) = image(i-1,j);
return ( tally(string(n), '01'b) );
end A;
/* Count the pixel neighbors of P1 that are black */
B: procedure (i, j) returns (fixed binary);
declare (i,j) fixed binary nonassignable;
declare s fixed binary;
s = image(i-1,j-1) + image(i-1,j) + image(i-1,j+1);
s = s + image(i,j-1) + image(i,j+1);
return ( s + image(i+1,j-1) + image(i+1,j) + image(i+1,j+1) );
end B;
end zhang; |
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
| #Python | Python | # -*- coding: utf-8 -*-
# Example from [http://nayefreza.wordpress.com/2013/05/11/zhang-suen-thinning-algorithm-java-implementation/ this blog post].
beforeTxt = '''\
1100111
1100111
1100111
1100111
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1111110
0000000\
'''
# Thanks to [http://www.network-science.de/ascii/ this site] and vim for these next two examples
smallrc01 = '''\
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000\
'''
rc01 = '''\
00000000000000000000000000000000000000000000000000000000000
01111111111111111100000000000000000001111111111111000000000
01111111111111111110000000000000001111111111111111000000000
01111111111111111111000000000000111111111111111111000000000
01111111100000111111100000000001111111111111111111000000000
00011111100000111111100000000011111110000000111111000000000
00011111100000111111100000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111111111111110000000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000011111110000000111111000000000
01111111100000111111100000000001111111111111111111000000000
01111111100000111111101111110000111111111111111111011111100
01111111100000111111101111110000001111111111111111011111100
01111111100000111111101111110000000001111111111111011111100
00000000000000000000000000000000000000000000000000000000000\
'''
def intarray(binstring):
'''Change a 2D matrix of 01 chars into a list of lists of ints'''
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
'''Change a 2d list of lists of 1/0 ints into lines of 1/0 chars'''
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
'''Change a 2d list of lists of 1/0 ints into lines of '#' and '.' chars'''
return '\n'.join(''.join(('#' if p else '.') for p in row) for row in intmatrix)
def neighbours(x, y, image):
'''Return 8-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
#print ((x,y))
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1], # P2,P3,P4,P5
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]] # P6,P7,P8,P9
def transitions(neighbours):
n = neighbours + neighbours[0:1] # P2, ... P9, P2
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
# Step 1
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and # (Condition 0)
P4 * P6 * P8 == 0 and # Condition 4
P2 * P4 * P6 == 0 and # Condition 3
transitions(n) == 1 and # Condition 2
2 <= sum(n) <= 6): # Condition 1
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
# Step 2
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and # (Condition 0)
P2 * P6 * P8 == 0 and # Condition 4
P2 * P4 * P8 == 0 and # Condition 3
transitions(n) == 1 and # Condition 2
2 <= sum(n) <= 6): # Condition 1
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
#print changing1
#print changing2
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s' % toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s' % toTxt(after)) |
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
| #Go | Go | package main
import "fmt"
func main() {
for i := 0; i <= 20; i++ {
fmt.Printf("%2d %7b\n", i, zeckendorf(i))
}
}
func zeckendorf(n int) int {
// initial arguments of fib0 = 1 and fib1 = 1 will produce
// the Fibonacci sequence {1, 2, 3,..} on the stack as successive
// values of fib1.
_, set := zr(1, 1, n, 0)
return set
}
func zr(fib0, fib1, n int, bit uint) (remaining, set int) {
if fib1 > n {
return n, 0
}
// recurse.
// construct sequence on the way in, construct ZR on the way out.
remaining, set = zr(fib1, fib0+fib1, n, bit+1)
if fib1 <= remaining {
set |= 1 << bit
remaining -= fib1
}
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.
| #Ceylon | Ceylon | shared void run() {
print("Open doors (naive): ``naive()``
Open doors (optimized): ``optimized()``");
}
shared {Integer*} naive(Integer count = 100) {
variable value doors = [ for (_ in 1..count) closed ];
for (step in 1..count) {
doors = [for (i->door in doors.indexed) let (index = i+1) if (step == 1 || step.divides(index)) then door.toggle() else door ];
}
return doors.indexesWhere((door) => door == opened).map(1.plusInteger);
}
shared {Integer*} optimized(Integer count = 100) =>
{ for (i in 1..count) i*i }.takeWhile(count.notSmallerThan);
shared abstract class Door(shared actual String string) of opened | closed {
shared formal Door toggle();
}
object opened extends Door("opened") { toggle() => closed; }
object closed extends Door("closed") { toggle() => opened; } |
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)
| #F.23 | F# | > Array.create 6 'A';;
val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
> Array.init 8 (fun i -> i * 10) ;;
val it : int [] = [|0; 10; 20; 30; 40; 50; 60; 70|]
> let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;;
val arr : int [] = [|0; 1; 2; 3; 4; 5; 6|]
> arr.[4];;
val it : int = 4
> arr.[4] <- 65 ;;
val it : unit = ()
> arr;;
val it : int [] = [|0; 1; 2; 3; 65; 5; 6|] |
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.
| #Python | Python | >>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
(3+4.5j)
>>> z1 - z2
1.5j
>>> z1 * z2
(-2.25+6.75j)
>>> z1 / z2
(1.5+0.5j)
>>> - z1
(-1.5-3j)
>>> z1.conjugate()
(1.5-3j)
>>> abs(z1)
3.3541019662496847
>>> z1 ** z2
(-1.1024829553277784-0.38306415117199333j)
>>> z1.real
1.5
>>> z1.imag
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
| #Scheme | Scheme | ; simply prints all the perfect numbers
(do ((candidate 2 (+ candidate 1))) ((>= candidate (expt 2 19)))
(let ((sum (/ 1 candidate)))
(do ((factor 2 (+ factor 1))) ((>= factor (sqrt candidate)))
(if (= 0 (modulo candidate factor))
(set! sum (+ sum (/ 1 factor) (/ factor candidate)))))
(if (= 1 (denominator sum))
(begin (display candidate) (newline))))) |
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
| #XPL0 | XPL0 | include c:\cxpl\codesi;
real A, A1, G;
[Format(0, 16);
A:= 1.0; G:= 1.0/sqrt(2.0);
repeat A1:= (A+G)/2.0;
G:= sqrt(A*G);
A:= A1;
RlOut(0, A); RlOut(0, G); RlOut(0, A-G); CrLf(0);
until A=G;
] |
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
| #zkl | zkl | a:=1.0; g:=1.0/(2.0).sqrt();
while(not a.closeTo(g,1.0e-15)){
a1:=(a+g)/2.0; g=(a*g).sqrt(); a=a1;
println(a," ",g," ",a-g);
} |
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
| #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
println("0 ^ 0 = ${Math.pow(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
| #Lambdatalk | Lambdatalk |
{pow 0 0}
-> 1
{exp 0 0}
-> 1
|
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives in the red house.
The Swede has a dog.
The Dane drinks tea.
The green house is immediately to the left of the white house.
They drink coffee in the green house.
The man who smokes Pall Mall has birds.
In the yellow house they smoke Dunhill.
In the middle house they drink milk.
The Norwegian lives in the first house.
The man who smokes Blend lives in the house next to the house with cats.
In a house next to the house where they have a horse, they smoke Dunhill.
The man who smokes Blue Master drinks beer.
The German smokes Prince.
The Norwegian lives next to the blue house.
They drink water in a house next to the house where they smoke Blend.
The question is, who owns the zebra?
Additionally, list the solution for all the houses.
Optionally, show the solution is unique.
Related tasks
Dinesman's multiple-dwelling problem
Twelve statements
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Zebra is
type Content is (Beer, Coffee, Milk, Tea, Water,
Danish, English, German, Norwegian, Swedish,
Blue, Green, Red, White, Yellow,
Blend, BlueMaster, Dunhill, PallMall, Prince,
Bird, Cat, Dog, Horse, Zebra);
type Test is (Drink, Person, Color, Smoke, Pet);
type House is (One, Two, Three, Four, Five);
type Street is array (Test'Range, House'Range) of Content;
type Alley is access all Street;
procedure Print (mat : Alley) is begin
for H in House'Range loop
Put(H'Img&": ");
for T in Test'Range loop
Put(T'Img&"="&mat(T,H)'Img&" ");
end loop; New_Line; end loop;
end Print;
function FinalChecks (mat : Alley) return Boolean is
function Diff (A, B : Content; CA , CB : Test) return Integer is begin
for H1 in House'Range loop for H2 in House'Range loop
if mat(CA,H1) = A and mat(CB,H2) = B then
return House'Pos(H1) - House'Pos(H2);
end if;
end loop; end loop;
end Diff;
begin
if abs(Diff(Norwegian, Blue, Person, Color)) = 1
and Diff(Green, White, Color, Color) = -1
and abs(Diff(Horse, Dunhill, Pet, Smoke)) = 1
and abs(Diff(Water, Blend, Drink, Smoke)) = 1
and abs(Diff(Blend, Cat, Smoke, Pet)) = 1
then return True;
end if;
return False;
end FinalChecks;
function Constrained (mat : Alley; atest : Natural) return Boolean is begin
-- Tests seperated into levels for speed, not strictly necessary
-- As such, the program finishes in around ~0.02s
case Test'Val (atest) is
when Drink => -- Drink
if mat (Drink, Three) /= Milk then return False; end if;
return True;
when Person => -- Drink+Person
for H in House'Range loop
if (mat(Person,H) = Norwegian and H /= One)
or (mat(Person,H) = Danish and mat(Drink,H) /= Tea)
then return False; end if;
end loop;
return True;
when Color => -- Drink+People+Color
for H in House'Range loop
if (mat(Person,H) = English and mat(Color,H) /= Red)
or (mat(Drink,H) = Coffee and mat(Color,H) /= Green)
then return False; end if;
end loop;
return True;
when Smoke => -- Drink+People+Color+Smoke
for H in House'Range loop
if (mat(Color,H) = Yellow and mat(Smoke,H) /= Dunhill)
or (mat(Smoke,H) = BlueMaster and mat(Drink,H) /= Beer)
or (mat(Person,H) = German and mat(Smoke,H) /= Prince)
then return False; end if;
end loop;
return True;
when Pet => -- Drink+People+Color+Smoke+Pet
for H in House'Range loop
if (mat(Person,H) = Swedish and mat(Pet,H) /= Dog)
or (mat(Smoke,H) = PallMall and mat(Pet,H) /= Bird)
then return False; end if;
end loop;
return FinalChecks(mat); -- Do the next-to checks
end case;
end Constrained;
procedure Solve (mat : Alley; t, n : Natural) is
procedure Swap (I, J : Natural) is
temp : constant Content := mat (Test'Val (t), House'Val (J));
begin
mat (Test'Val (t), House'Val (J)) := mat (Test'Val (t), House'Val (I));
mat (Test'Val (t), House'Val (I)) := temp;
end Swap;
begin
if n = 1 and Constrained (mat, t) then -- test t passed
if t < 4 then Solve (mat, t + 1, 5); -- Onto next test
else Print (mat); return; -- Passed and t=4 means a solution
end if;
end if;
for i in 0 .. n - 1 loop -- The permutations part
Solve (mat, t, n - 1);
if n mod 2 = 1 then Swap (0, n - 1);
else Swap (i, n - 1); end if;
end loop;
end Solve;
myStreet : aliased Street;
myAlley : constant Alley := myStreet'Access;
begin
for i in Test'Range loop for j in House'Range loop -- Init Matrix
myStreet (i,j) := Content'Val(Test'Pos(i)*5 + House'Pos(j));
end loop; end loop;
Solve (myAlley, 0, 5); -- start at test 0 with 5 options
end Zebra; |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name="food">
<item upc="485672034" stock="653">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc="132957764" stock="44">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program xpathXml64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBMAXELEMENTS, 100
/*******************************************/
/* Structures */
/********************************************/
/* structure xmlNode*/
.struct 0
xmlNode_private: // application data
.struct xmlNode_private + 8
xmlNode_type: // type number, must be second !
.struct xmlNode_type + 8
xmlNode_name: // the name of the node, or the entity
.struct xmlNode_name + 8
xmlNode_children: // parent->childs link
.struct xmlNode_children + 8
xmlNode_last: // last child link
.struct xmlNode_last + 8
xmlNode_parent: // child->parent link
.struct xmlNode_parent + 8
xmlNode_next: // next sibling link
.struct xmlNode_next + 8
xmlNode_prev: // previous sibling link
.struct xmlNode_prev + 8
xmlNode_doc: // the containing document
.struct xmlNode_doc + 8
xmlNode_ns: // pointer to the associated namespace
.struct xmlNode_ns + 8
xmlNode_content: // the content
.struct xmlNode_content + 8
xmlNode_properties: // properties list
.struct xmlNode_properties + 8
xmlNode_nsDef: // namespace definitions on this node
.struct xmlNode_nsDef + 8
xmlNode_psvi: // for type/PSVI informations
.struct xmlNode_psvi + 8
xmlNode_line: // line number
.struct xmlNode_line + 4
xmlNode_extra: // extra data for XPath/XSLT
.struct xmlNode_extra + 4
xmlNode_fin:
/********************************************/
/* structure xmlNodeSet*/
.struct 0
xmlNodeSet_nodeNr: // number of nodes in the set
.struct xmlNodeSet_nodeNr + 4
xmlNodeSet_nodeMax: // size of the array as allocated
.struct xmlNodeSet_nodeMax + 4
xmlNodeSet_nodeTab: // array of nodes in no particular order
.struct xmlNodeSet_nodeTab + 8
xmlNodeSet_fin:
/********************************************/
/* structure xmlXPathObject*/
.struct 0
xmlPathObj_type: //
.struct xmlPathObj_type + 8
xmlPathObj_nodesetval: //
.struct xmlPathObj_nodesetval + 8
xmlPathObj_boolval: //
.struct xmlPathObj_boolval + 8
xmlPathObj_floatval: //
.struct xmlPathObj_floatval + 8
xmlPathObj_stringval: //
.struct xmlPathObj_stringval + 8
xmlPathObj_user: //
.struct xmlPathObj_user + 8
xmlPathObj_index: //
.struct xmlPathObj_index + 8
xmlPathObj_usex2: //
.struct xmlPathObj_usex2 + 8
xmlPathObj_index2: //
.struct xmlPathObj_index2 + 8
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndpgm: .asciz "\nNormal end of program.\n"
szMessDisVal: .asciz "\nDisplay set values.\n"
szMessDisArea: .asciz "\nDisplay area values.\n"
szFileName: .asciz "testXml.xml"
szMessError: .asciz "Error detected !!!!. \n"
szLibName: .asciz "name"
szLibPrice: .asciz "//price"
szLibExtName: .asciz "//name"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
tbExtract: .skip 8 * NBMAXELEMENTS // result extract area
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszFileName
bl xmlParseFile // create doc
cbz x0,99f // error ?
mov x19,x0 // doc address
mov x0,x19 // doc
bl xmlDocGetRootElement // get root
bl xmlFirstElementChild // get first section
bl xmlFirstElementChild // get first item
bl xmlFirstElementChild // get first name
bl xmlNodeGetContent // extract content
bl affichageMess // for display
ldr x0,qAdrszCarriageReturn
bl affichageMess
ldr x0,qAdrszMessDisVal
bl affichageMess
mov x0,x19
ldr x1,qAdrszLibPrice // extract prices
bl extractValue
mov x0,x19
ldr x1,qAdrszLibExtName // extract names
bl extractValue
ldr x0,qAdrszMessDisArea
bl affichageMess
mov x4,#0 // display string result area
ldr x5,qAdrtbExtract
1:
ldr x0,[x5,x4,lsl #3]
cbz x0,2f
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x4,x4,1
b 1b
2:
mov x0,x19
bl xmlFreeDoc
bl xmlCleanupParser
ldr x0,qAdrszMessEndpgm
bl affichageMess
b 100f
99: // error
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessError: .quad szMessError
qAdrszMessEndpgm: .quad szMessEndpgm
qAdrszLibName: .quad szLibName
qAdrszLibPrice: .quad szLibPrice
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszFileName: .quad szFileName
qAdrszLibExtName: .quad szLibExtName
qAdrtbExtract: .quad tbExtract
qAdrszMessDisVal: .quad szMessDisVal
qAdrszMessDisArea: .quad szMessDisArea
/******************************************************************/
/* extract value of set */
/******************************************************************/
/* x0 contains the doc address
/* x1 contains the address of the libel to extract */
extractValue:
stp x19,lr,[sp,-16]! // save registers
stp x20,x21,[sp,-16]! // save registers
stp x22,x23,[sp,-16]! // save registers
mov x20,x1 // save address libel
mov x19,x0 // save doc
bl xmlXPathNewContext // create context
mov x23,x0 // save context
mov x1,x0
mov x0,x20
bl xmlXPathEvalExpression
mov x21,x0
mov x0,x23
bl xmlXPathFreeContext // free context
cmp x21,#0
beq 100f
ldr x14,[x21,#xmlPathObj_nodesetval] // values set
ldr w23,[x14,#xmlNodeSet_nodeNr] // set size
mov x22,#0 // index
ldr x20,[x14,#xmlNodeSet_nodeTab] // area of nodes
ldr x21,qAdrtbExtract
1: // start loop
ldr x3,[x20,x22,lsl #3] // load node
mov x0,x19
ldr x1,[x3,#xmlNode_children] // load string value
mov x2,#1
bl xmlNodeListGetString
str x0,[x21,x22,lsl #3] // store string pointer in area
bl affichageMess // and display string result
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x22,x22,1
cmp x22,x23
blt 1b
100:
ldp x22,x23,[sp],16 // restaur 2 registers
ldp x20,x21,[sp],16 // restaur 2 registers
ldp x19,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #Ada | Ada | with Glib; use Glib;
with Cairo; use Cairo;
with Cairo.Png; use Cairo.Png;
with Cairo.Image_Surface; use Cairo.Image_Surface;
procedure YinYang is
subtype Dub is Glib.Gdouble;
procedure Draw (C : Cairo_Context; x : Dub; y : Dub; r : Dub) is begin
Arc (C, x, y, r + 1.0, 1.571, 7.854);
Set_Source_Rgb (C, 0.0, 0.0, 0.0); Fill (C);
Arc_Negative (C, x, y - r / 2.0, r / 2.0, 1.571, 4.712);
Arc (C, x, y + r / 2.0, r / 2.0, 1.571, 4.712);
Arc_Negative (C, x, y, r, 4.712, 1.571);
Set_Source_Rgb (C, 1.0, 1.0, 1.0); Fill (C);
Arc (C, x, y - r / 2.0, r / 5.0, 1.571, 7.854);
Set_Source_Rgb (C, 0.0, 0.0, 0.0); Fill (C);
Arc (C, x, y + r / 2.0, r / 5.0, 1.571, 7.854);
Set_Source_Rgb (C, 1.0, 1.0, 1.0); Fill (C);
end Draw;
Surface : Cairo_Surface;
Context : Cairo_Context;
Status : Cairo_Status;
begin
Surface := Create (Cairo_Format_ARGB32, 200, 200);
Context := Create (Surface);
Draw (Context, 120.0, 120.0, 75.0);
Draw (Context, 35.0, 35.0, 30.0);
Status := Write_To_Png (Surface, "YinYangAda.png");
pragma Assert (Status = Cairo_Status_Success);
end YinYang; |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #AppleScript | AppleScript | -- Y COMBINATOR ---------------------------------------------------------------
on |Y|(f)
script
on |λ|(y)
script
on |λ|(x)
y's |λ|(y)'s |λ|(x)
end |λ|
end script
f's |λ|(result)
end |λ|
end script
result's |λ|(result)
end |Y|
-- TEST -----------------------------------------------------------------------
on run
-- Factorial
script fact
on |λ|(f)
script
on |λ|(n)
if n = 0 then return 1
n * (f's |λ|(n - 1))
end |λ|
end script
end |λ|
end script
-- Fibonacci
script fib
on |λ|(f)
script
on |λ|(n)
if n = 0 then return 0
if n = 1 then return 1
(f's |λ|(n - 2)) + (f's |λ|(n - 1))
end |λ|
end script
end |λ|
end script
{facts:map(|Y|(fact), enumFromTo(0, 11)), fibs:map(|Y|(fib), enumFromTo(0, 20))}
--> {facts:{1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800},
--> fibs:{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987,
-- 1597, 2584, 4181, 6765}}
end run
-- GENERIC FUNCTIONS FOR TEST -------------------------------------------------
-- 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
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m 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
-- 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 |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #Arturo | Arturo | zigzag: function [n][
result: map 1..n 'x -> map 1..n => 0
x: 1, y: 1, v: 0, d: 1
while [v < n^2][
if? all? @[1 =< x x =< n 1 =< y y =< n][
set get result (y-1) (x-1) v
x: x + d, y: y - d, v: v + 1
]
else[if? x > n [x: n, y: y + 2, d: neg d]
else[if? y > n [x: x + 2, y: n, d: neg d]
else[if? x < 1 [x: 1, d: neg d]
else[if y < 1 [y: 1, d: neg d]
]
]
]
]
]
result
]
zz: zigzag 5
loop zz 'row -> print map row 'col [pad to :string col 3] |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Haskell | Haskell | import Data.List (unfoldr)
yellowstone :: [Integer]
yellowstone = 1 : 2 : 3 : unfoldr (Just . f) (2, 3, [4 ..])
where
f ::
(Integer, Integer, [Integer]) ->
(Integer, (Integer, Integer, [Integer]))
f (p2, p1, rest) = (next, (p1, next, rest_))
where
(next, rest_) = select rest
select :: [Integer] -> (Integer, [Integer])
select (x : xs)
| gcd x p1 == 1 && gcd x p2 /= 1 = (x, xs)
| otherwise = (y, x : ys)
where
(y, ys) = select xs
main :: IO ()
main = print $ take 30 yellowstone |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Gambas | Gambas | Public Sub Form_Open()
Dim hWebView As WebView
Me.Arrangement = Arrange.Fill
Me.Maximized = True
Me.Title = "Yahoo! search interface"
hWebView = New WebView(Me)
hWebView.Expand = True
hWebView.URL = "https://www.yahoo.com"
End |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Go | Go | package main
import (
"fmt"
"golang.org/x/net/html"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
var (
expr = `<h3 class="title"><a class=.*?href="(.*?)".*?>(.*?)</a></h3>` +
`.*?<div class="compText aAbs" ><p class=.*?>(.*?)</p></div>`
rx = regexp.MustCompile(expr)
)
type YahooResult struct {
title, url, content string
}
func (yr YahooResult) String() string {
return fmt.Sprintf("Title : %s\nUrl : %s\nContent: %s\n", yr.title, yr.url, yr.content)
}
type YahooSearch struct {
query string
page int
}
func (ys YahooSearch) results() []YahooResult {
search := fmt.Sprintf("http://search.yahoo.com/search?p=%s&b=%d", ys.query, ys.page*10+1)
resp, _ := http.Get(search)
body, _ := ioutil.ReadAll(resp.Body)
s := string(body)
defer resp.Body.Close()
var results []YahooResult
for _, f := range rx.FindAllStringSubmatch(s, -1) {
yr := YahooResult{}
yr.title = html.UnescapeString(strings.ReplaceAll(strings.ReplaceAll(f[2], "<b>", ""), "</b>", ""))
yr.url = f[1]
yr.content = html.UnescapeString(strings.ReplaceAll(strings.ReplaceAll(f[3], "<b>", ""), "</b>", ""))
results = append(results, yr)
}
return results
}
func (ys YahooSearch) nextPage() YahooSearch {
return YahooSearch{ys.query, ys.page + 1}
}
func main() {
ys := YahooSearch{"rosettacode", 0}
// Limit output to first 5 entries, say, from pages 1 and 2.
fmt.Println("PAGE 1 =>\n")
for _, res := range ys.results()[0:5] {
fmt.Println(res)
}
fmt.Println("PAGE 2 =>\n")
for _, res := range ys.nextPage().results()[0:5] {
fmt.Println(res)
}
} |
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.
| #Standard_ML | Standard ML | (* AST *)
datatype expression =
Con of int (* constant *)
| Add of expression * expression (* addition *)
| Mul of expression * expression (* multiplication *)
| Sub of expression * expression (* subtraction *)
| Div of expression * expression (* division *)
(* Evaluator *)
fun eval (Con x) = x
| eval (Add (x, y)) = (eval x) + (eval y)
| eval (Mul (x, y)) = (eval x) * (eval y)
| eval (Sub (x, y)) = (eval x) - (eval y)
| eval (Div (x, y)) = (eval x) div (eval y)
(* Lexer *)
datatype token =
CON of int
| ADD
| MUL
| SUB
| DIV
| LPAR
| RPAR
fun lex nil = nil
| lex (#"+" :: cs) = ADD :: lex cs
| lex (#"*" :: cs) = MUL :: lex cs
| lex (#"-" :: cs) = SUB :: lex cs
| lex (#"/" :: cs) = DIV :: lex cs
| lex (#"(" :: cs) = LPAR :: lex cs
| lex (#")" :: cs) = RPAR :: lex cs
| lex (#"~" :: cs) = if null cs orelse not (Char.isDigit (hd cs)) then raise Domain
else lexDigit (0, cs, ~1)
| lex (c :: cs) = if Char.isDigit c then lexDigit (0, c :: cs, 1)
else raise Domain
and lexDigit (a, cs, s) = if null cs orelse not (Char.isDigit (hd cs)) then CON (a*s) :: lex cs
else lexDigit (a * 10 + (ord (hd cs))- (ord #"0") , tl cs, s)
(* Parser *)
exception Error of string
fun match (a,ts) t = if null ts orelse hd ts <> t
then raise Error "match"
else (a, tl ts)
fun extend (a,ts) p f = let val (a',tr) = p ts in (f(a,a'), tr) end
fun parseE ts = parseE' (parseM ts)
and parseE' (e, ADD :: ts) = parseE' (extend (e, ts) parseM Add)
| parseE' (e, SUB :: ts) = parseE' (extend (e, ts) parseM Sub)
| parseE' s = s
and parseM ts = parseM' (parseP ts)
and parseM' (e, MUL :: ts) = parseM' (extend (e, ts) parseP Mul)
| parseM' (e, DIV :: ts) = parseM' (extend (e, ts) parseP Div)
| parseM' s = s
and parseP (CON c :: ts) = (Con c, ts)
| parseP (LPAR :: ts) = match (parseE ts) RPAR
| parseP _ = raise Error "parseP"
(* Test *)
fun lex_parse_eval (str:string) =
case parseE (lex (explode str)) of
(exp, nil) => eval exp
| _ => raise Error "not parseable stuff at the end" |
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.
| #Tailspin | Tailspin |
def ops: ['+','-','*','/'];
data binaryExpression <{left: <node>, op: <?($ops <[<=$::raw>]>)>, right: <node>}>
data node <binaryExpression|"1">
composer parseArithmetic
(<WS>?) <addition|multiplication|term> (<WS>?)
rule addition: {left:<addition|multiplication|term> (<WS>?) op:<'[+-]'> (<WS>?) right:<multiplication|term>}
rule multiplication: {left:<multiplication|term> (<WS>?) op:<'[*/]'> (<WS>?) right:<term>}
rule term: <INT"1"|parentheses>
rule parentheses: (<'\('> <WS>?) <addition|multiplication|term> (<WS>? <'\)'>)
end parseArithmetic
templates evaluateArithmetic
<{op: <='+'>}> ($.left -> evaluateArithmetic) + ($.right -> evaluateArithmetic) !
<{op: <='-'>}> ($.left -> evaluateArithmetic) - ($.right -> evaluateArithmetic) !
<{op: <='*'>}> ($.left -> evaluateArithmetic) * ($.right -> evaluateArithmetic) !
<{op: <='/'>}> ($.left -> evaluateArithmetic) ~/ ($.right -> evaluateArithmetic) !
otherwise $ !
end evaluateArithmetic
def ast: '(100 - 5 * (2+3*4) + 2) / 2' -> parseArithmetic;
'$ast;
' -> !OUT::write
'$ast -> evaluateArithmetic;
' -> !OUT::write
|
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Tcl | Tcl | namespace eval zeckendorf {
# Want to use alternate symbols? Change these
variable zero "0"
variable one "1"
# Base operations: increment and decrement
proc zincr var {
upvar 1 $var a
namespace upvar [namespace current] zero 0 one 1
if {![regsub "$0$" $a $1$0 a]} {append a $1}
while {[regsub "$0$1$1" $a "$1$0$0" a]
|| [regsub "^$1$1" $a "$1$0$0" a]} {}
regsub ".$" $a "" a
return $a
}
proc zdecr var {
upvar 1 $var a
namespace upvar [namespace current] zero 0 one 1
regsub "^$0+(.+)$" [subst [regsub "${1}($0*)$" $a "$0\[
string repeat {$1$0} \[regsub -all .. {\\1} {} x]]\[
string repeat {$1} \[expr {\$x ne {}}]]"]
] {\1} a
return $a
}
# Exported operations
proc eq {a b} {
expr {$a eq $b}
}
proc add {a b} {
variable zero
while {![eq $b $zero]} {
zincr a
zdecr b
}
return $a
}
proc sub {a b} {
variable zero
while {![eq $b $zero]} {
zdecr a
zdecr b
}
return $a
}
proc mul {a b} {
variable zero
variable one
if {[eq $a $zero] || [eq $b $zero]} {return $zero}
if {[eq $a $one]} {return $b}
if {[eq $b $one]} {return $a}
set c $a
while {![eq [zdecr b] $zero]} {
set c [add $c $a]
}
return $c
}
proc div {a b} {
variable zero
variable one
if {[eq $b $zero]} {error "div zero"}
if {[eq $a $zero] || [eq $b $one]} {return $a}
set r $zero
while {![eq $a $zero]} {
if {![eq $a [add [set a [sub $a $b]] $b]]} break
zincr r
}
return $r
}
# Note that there aren't any ordering operations in this version
# Assemble into a coherent API
namespace export \[a-y\]*
namespace ensemble create
} |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Racket | Racket | #lang racket
(require math/number-theory)
(define (zum? n)
(let* ((set (divisors n))
(sum (apply + set)))
(cond
[(odd? sum) #f]
[(odd? n) ; if n is odd use 'abundant odd number' optimization
(let ((abundance (- sum (* n 2)))) (and (positive? abundance) (even? abundance)))]
[else
(let ((sum/2 (quotient sum 2)))
(let loop ((acc (car set)) (set (cdr set)))
(cond [(= acc sum/2) #t]
[(> acc sum/2) #f]
[(null? set) #f]
[else (or (loop (+ (car set) acc) (cdr set))
(loop acc (cdr set)))])))])))
(define (first-n-matching-naturals count pred)
(for/list ((i count) (j (stream-filter pred (in-naturals 1)))) j))
(define (tabulate title ns (row-width 132))
(displayln title)
(let* ((cell-width (+ 2 (order-of-magnitude (apply max ns))))
(cells/row (quotient row-width cell-width)))
(let loop ((ns ns) (col cells/row))
(cond [(null? ns) (unless (= col cells/row) (newline))]
[(zero? col) (newline) (loop ns cells/row)]
[else (display (~a #:width cell-width #:align 'right (car ns)))
(loop (cdr ns) (sub1 col))]))))
(tabulate "First 220 Zumkeller numbers:" (first-n-matching-naturals 220 zum?))
(newline)
(tabulate "First 40 odd Zumkeller numbers:"
(first-n-matching-naturals 40 (λ (n) (and (odd? n) (zum? n)))))
(newline)
(tabulate "First 40 odd Zumkeller numbers not ending in 5:"
(first-n-matching-naturals 40 (λ (n) (and (odd? n) (not (= 5 (modulo n 10))) (zum? n))))) |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Raku | Raku | use ntheory:from<Perl5> <factor is_prime>;
sub zumkeller ($range) {
$range.grep: -> $maybe {
next if $maybe < 3 or $maybe.&is_prime;
my @divisors = $maybe.&factor.combinations».reduce( &[×] ).unique.reverse;
next unless [and] @divisors > 2, @divisors %% 2, (my $sum = @divisors.sum) %% 2, ($sum /= 2) ≥ $maybe;
my $zumkeller = False;
if $maybe % 2 {
$zumkeller = True
} else {
TEST: for 1 ..^ @divisors/2 -> $c {
@divisors.combinations($c).map: -> $d {
next if $d.sum != $sum;
$zumkeller = True and last TEST
}
}
}
$zumkeller
}
}
say "First 220 Zumkeller numbers:\n" ~
zumkeller(^Inf)[^220].rotor(20)».fmt('%3d').join: "\n";
put "\nFirst 40 odd Zumkeller numbers:\n" ~
zumkeller((^Inf).map: * × 2 + 1)[^40].rotor(10)».fmt('%7d').join: "\n";
# Stretch. Slow to calculate. (minutes)
put "\nFirst 40 odd Zumkeller numbers not divisible by 5:\n" ~
zumkeller(flat (^Inf).map: {my \p = 10 * $_; p+1, p+3, p+7, p+9} )[^40].rotor(10)».fmt('%7d').join: "\n"; |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Forth | Forth | 388c388
< CREATE big_string 256 CHARS ALLOT
---
> CREATE big_string 500000 CHARS ALLOT
394c394
< big_string 256 CHARS + bighld ! ; \ Haydon p 67
---
> big_string 500000 CHARS + bighld ! ; \ Haydon p 67
403c403
< big_string 256 CHARS + \ One past end of string
---
> big_string 500000 CHARS + \ One past end of string
|
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Fortran | Fortran | program bignum
use fmzm
implicit none
type(im) :: a
integer :: n
call fm_set(50)
a = to_im(5)**(to_im(4)**(to_im(3)**to_im(2)))
n = to_int(floor(log10(to_fm(a))))
call im_print(a / to_im(10)**(n - 19))
call im_print(mod(a, to_im(10)**20))
end program |
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
| #Racket | Racket | #lang racket
(define (img-01string->vector str)
(define lines (regexp-split "\n" str))
(define h (length lines))
(define w (if (zero? h) 0 (string-length (car lines))))
(define v (for*/vector #:length (* w h)
((l (in-list lines)) (p (in-string l)))
(match p (#\0 0) (#\1 1) (#\# 1) (#\. 0))))
(values v h w))
; Task (2) asks for "or an ASCII-art image of space/non-space characters."
; Spaces don't really impress where the borders are, so we'll use a dot.
(define cell->display-char (match-lambda (0 ".") (1 "#") (else "?")))
(define (display-img v w)
(for ((p (in-vector v)) (col (in-naturals)))
(printf "~a" (cell->display-char p))
(when (= (modulo col w) (sub1 w)) (newline))))
; returns vector of ([P1's idx] P1 P2 ... P9)
(define (Pns v w r c)
(define i (+ c (* r w)))
(define-syntax-rule (vi+ x) (vector-ref v (+ i x)))
(define-syntax-rule (vi- x) (vector-ref v (- i x)))
(vector i (vi+ 0) (vi- w) (vi+ (- 1 w))
(vi+ 1) (vi+ (+ w 1)) (vi+ w)
(vi+ (- w 1)) (vi- 1) (vi- (+ w 1))))
; Second argument to in-vector is the start offset;
; We skip offset 0 (idx) and 1 (P1)
(define (B Ps) (for/sum ((Pn (in-vector Ps 2))) Pn))
(define (A Ps)
(define P2 (vector-ref Ps 2))
(define-values (rv _)
(for/fold ((acc 0) (Pn-1 P2))
((Pn (in-sequences (in-vector Ps 3) (in-value P2))))
(values (+ acc (if (and (= 0 Pn-1) (= 1 Pn)) 1 0)) Pn)))
rv)
(define-syntax-rule (not-all-black? Pa Pb Pc) (zero? (* Pa Pb Pc)))
(define (z-s-thin v h w)
; return idx when thin necessary, #f otherwise
(define (thin? Ps n/bour-check-1 n/bour-check-2)
(match-define (vector idx P1 P2 _ P4 _ P6 _ P8 _) Ps)
(and (= P1 1) (<= 2 (B Ps) 6) (= (A Ps) 1)
(n/bour-check-1 P2 P4 P6 P8)
(n/bour-check-2 P2 P4 P6 P8)
idx))
(define (has-white?-246 P2 P4 P6 P8) (not-all-black? P2 P4 P6))
(define (has-white?-468 P2 P4 P6 P8) (not-all-black? P4 P6 P8))
(define (has-white?-248 P2 P4 P6 P8) (not-all-black? P2 P4 P8))
(define (has-white?-268 P2 P4 P6 P8) (not-all-black? P2 P6 P8))
(define (step-n even-Pn-check-1 even-Pn-check-2)
(for*/list ((r (in-range 1 (- h 1)))
(c (in-range 1 (- w 1)))
(idx (in-value (thin? (Pns v w r c)
even-Pn-check-1
even-Pn-check-2)))
#:when idx) idx))
(define (step-1) (step-n has-white?-246 has-white?-468))
(define (step-2) (step-n has-white?-248 has-white?-268))
(define (inner-z-s-thin)
(define changed-list-1 (step-1))
(for ((idx (in-list changed-list-1))) (vector-set! v idx 0))
(define changed-list-2 (step-2))
(for ((idx (in-list changed-list-2))) (vector-set! v idx 0))
(unless (and (null? changed-list-1) (null? changed-list-2)) (inner-z-s-thin)))
(inner-z-s-thin))
(define (read-display-thin-display-image img-str)
(define-values (v h w) (img-01string->vector img-str))
(printf "Original image:~%") (display-img v w)
(z-s-thin v h w)
(printf "Thinned image:~%") (display-img v w))
(define e.g.-image #<<EOS
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
EOS
)
(define e.g.-image/2 #<<EOS
##..###
##..###
##..###
##..###
##..##.
##..##.
##..##.
##..##.
##..##.
##..##.
##..##.
##..##.
######.
.......
EOS
)
(module+ main
; (read-display-thin-display-image e.g.-image/2)
; (newline)
(read-display-thin-display-image e.g.-image)) |
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
| #Raku | Raku | my $source = qq:to/EOD/;
................................
.#########.......########.......
.###...####.....####..####......
.###....###.....###....###......
.###...####.....###.............
.#########......###.............
.###.####.......###....###......
.###..####..###.####..####.###..
.###...####.###..########..###..
................................
EOD
my @lines = ([.ords X+& 1] for $source.split("\n")); # The low bits Just Work.
my \v = +@lines;
my \h = +@lines[0];
my @black = flat @lines.map: *.values; # Flatten to 1-dimensional.
my \p8 = [-h-1, -h+0, -h+1, # Flatland distances to 8 neighbors.
0-1, 0+1,
h-1, h+0, h+1].[1,2,4,7,6,5,3,0]; # (in cycle order)
# Candidates have 8 neighbors and are known black
my @cand = grep { @black[$_] }, do
for 1..v-2 X 1..h-2 -> (\y,\x) { y*h + x }
repeat while my @goners1 or my @goners2 {
sub seewhite (\w1,\w2) {
sub cycles (@neighbors) { [+] @neighbors Z< @neighbors[].rotate }
sub blacks (@neighbors) { [+] @neighbors }
my @prior = @cand; @cand = ();
gather for @prior -> \p {
my \n = @black[p8 X+ p];
if cycles(n) == 1 and 2 <= blacks(n) <= 6 and n[w1].any == 0 and n[w2].any == 0
{ take p }
else { @cand.push: p }
}
}
@goners1 = seewhite (0,2,4), (2,4,6);
@black[@goners1] = 0 xx *;
say "Ping: {[+] @black} remaining after removing ", @goners1;
@goners2 = seewhite (0,2,6), (0,4,6);
@black[@goners2] = 0 xx *;
say "Pong: {[+] @black} remaining after removing ", @goners2;
}
say @black.splice(0,h).join.trans('01' => '.#') while @black; |
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
| #Haskell | Haskell | import Data.Bits
import Numeric
zeckendorf = map b $ filter ones [0..] where
ones :: Int -> Bool
ones x = 0 == x .&. (x `shiftR` 1)
b x = showIntAtBase 2 ("01"!!) x ""
main = mapM_ putStrLn $ take 21 zeckendorf |
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.
| #Clarion | Clarion |
program
map
end
MAX_DOOR_NUMBER equate(100)
CRLF equate('<13,10>')
Doors byte,dim(MAX_DOOR_NUMBER)
Pass byte
DoorNumber byte
DisplayString cstring(2000)
ResultWindow window('Result'),at(,,133,291),center,double,auto
prompt('Door states:'),at(8,4),use(?PromptTitle)
text,at(8,16,116,266),use(DisplayString),boxed,vscroll,font('Courier New',,,,CHARSET:ANSI),readonly
end
code
Doors :=: false
loop Pass = 1 to MAX_DOOR_NUMBER
loop DoorNumber = Pass to MAX_DOOR_NUMBER by Pass
Doors[DoorNumber] = choose(Doors[DoorNumber], false, true)
end
end
clear(DisplayString)
loop DoorNumber = 1 to MAX_DOOR_NUMBER
DisplayString = DisplayString & format(DoorNumber, @n3) & ' is ' & choose(Doors[DoorNumber], 'opened', 'closed') & CRLF
end
open(ResultWindow)
accept
end
close(ResultWindow)
return
|
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)
| #Factor | Factor | { 1 2 3 }
{
[ "The initial array: " write . ]
[ [ 42 1 ] dip set-nth ]
[ "Modified array: " write . ]
[ "The element we modified: " write [ 1 ] dip nth . ]
} cleave |
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.
| #R | R | z1 <- 1.5 + 3i
z2 <- 1.5 + 1.5i
print(z1 + z2) # 3+4.5i
print(z1 - z2) # 0+1.5i
print(z1 * z2) # -2.25+6.75i
print(z1 / z2) # 1.5+0.5i
print(-z1) # -1.5-3i
print(Conj(z1)) # 1.5-3i
print(abs(z1)) # 3.354102
print(z1^z2) # -1.102483-0.383064i
print(exp(z1)) # -4.436839+0.632456i
print(Re(z1)) # 1.5
print(Im(z1)) # 3 |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "rational.s7i";
const func boolean: isPerfect (in integer: candidate) is func
result
var boolean: isPerfect is FALSE;
local
var integer: divisor is 0;
var rational: sum is rational.value;
begin
sum := 1 / candidate;
for divisor range 2 to sqrt(candidate) do
if candidate mod divisor = 0 then
sum +:= 1 / divisor + 1 / (candidate div divisor);
end if;
end for;
isPerfect := sum = rat(1);
end func;
const proc: main is func
local
var integer: candidate is 0;
begin
for candidate range 2 to 2 ** 19 - 1 do
if isPerfect(candidate) then
writeln(candidate <& " is perfect");
end if;
end for;
end func; |
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
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET a=1: LET g=1/SQR 2
20 LET ta=a
30 LET a=(a+g)/2
40 LET g=SQR (ta*g)
50 IF a<ta THEN GO TO 20
60 PRINT a
|
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
| #Liberty_BASIC | Liberty 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
| #Locomotive_Basic | Locomotive Basic | print 0🠅0 |
http://rosettacode.org/wiki/Zebra_puzzle | Zebra puzzle | Zebra puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
The Zebra puzzle, a.k.a. Einstein's Riddle,
is a logic puzzle which is to be solved programmatically.
It has several variants, one of them this:
There are five houses.
The English man lives in the red house.
The Swede has a dog.
The Dane drinks tea.
The green house is immediately to the left of the white house.
They drink coffee in the green house.
The man who smokes Pall Mall has birds.
In the yellow house they smoke Dunhill.
In the middle house they drink milk.
The Norwegian lives in the first house.
The man who smokes Blend lives in the house next to the house with cats.
In a house next to the house where they have a horse, they smoke Dunhill.
The man who smokes Blue Master drinks beer.
The German smokes Prince.
The Norwegian lives next to the blue house.
They drink water in a house next to the house where they smoke Blend.
The question is, who owns the zebra?
Additionally, list the solution for all the houses.
Optionally, show the solution is unique.
Related tasks
Dinesman's multiple-dwelling problem
Twelve statements
| #ALGOL_68 | ALGOL 68 | BEGIN
# attempt to solve Einstein's Riddle - the Zebra puzzle #
INT unknown = 0, same = -1;
INT english = 1, swede = 2, dane = 3, norwegian = 4, german = 5;
INT dog = 1, birds = 2, cats = 3, horse = 4, zebra = 5;
INT red = 1, green = 2, white = 3, yellow = 4, blue = 5;
INT tea = 1, coffee = 2, milk = 3, beer = 4, water = 5;
INT pall mall = 1, dunhill = 2, blend = 3, blue master = 4, prince = 5;
[]STRING nationality = ( "unknown", "english", "swede", "dane", "norwegian", "german" );
[]STRING animal = ( "unknown", "dog", "birds", "cats", "horse", "ZEBRA" );
[]STRING colour = ( "unknown", "red", "green", "white", "yellow", "blue" );
[]STRING drink = ( "unknown", "tea", "coffee", "milk", "beer", "water" );
[]STRING smoke = ( "unknown", "pall mall", "dunhill", "blend", "blue master", "prince" );
MODE HOUSE = STRUCT( INT nationality, animal, colour, drink, smoke );
# returns TRUE if a field in a house could be set to value, FALSE otherwise #
PROC can set = ( INT field, INT value )BOOL: field = unknown OR value = same;
# returns TRUE if the fields of house h could be set to those of #
# suggestion s, FALSE otherwise #
OP XOR = ( HOUSE h, HOUSE s )BOOL:
( can set( nationality OF h, nationality OF s ) AND can set( animal OF h, animal OF s )
AND can set( colour OF h, colour OF s ) AND can set( drink OF h, drink OF s )
AND can set( smoke OF h, smoke OF s )
) # XOR # ;
# sets a field in a house to value if it is unknown #
PROC set = ( REF INT field, INT value )VOID: IF field = unknown AND value /= same THEN field := value FI;
# sets the unknown fields in house h to the non-same fields of suggestion s #
OP +:= = ( REF HOUSE h, HOUSE s )VOID:
( set( nationality OF h, nationality OF s ); set( animal OF h, animal OF s )
; set( colour OF h, colour OF s ); set( drink OF h, drink OF s )
; set( smoke OF h, smoke OF s )
) # +:= # ;
# sets a field in a house to unknown if the value is not same #
PROC reset = ( REF INT field, INT value )VOID: IF value /= same THEN field := unknown FI;
# sets fields in house h to unknown if the suggestion s is not same #
OP -:= = ( REF HOUSE h, HOUSE s )VOID:
( reset( nationality OF h, nationality OF s ); reset( animal OF h, animal OF s )
; reset( colour OF h, colour OF s ); reset( drink OF h, drink OF s )
; reset( smoke OF h, smoke OF s )
) # -:= # ;
# attempts a partial solution for the house at pos #
PROC try = ( INT pos, HOUSE suggestion, PROC VOID continue )VOID:
IF pos >= LWB house AND pos <= UPB house THEN
IF house[ pos ] XOR suggestion THEN
house[ pos ] +:= suggestion; continue; house[ pos ] -:= suggestion
FI
FI # try # ;
# attempts a partial solution for the neighbours of a house #
PROC left or right = ( INT pos, BOOL left, BOOL right, HOUSE neighbour suggestion
, PROC VOID continue )VOID:
( IF left THEN try( pos - 1, neighbour suggestion, continue ) FI
; IF right THEN try( pos + 1, neighbour suggestion, continue ) FI
) # left or right # ;
# attempts a partial solution for all houses and possibly their neighbours #
PROC any2 = ( REF INT number, HOUSE suggestion
, BOOL left, BOOL right, HOUSE neighbour suggestion
, PROC VOID continue )VOID:
FOR pos TO UPB house DO
IF house[ pos ] XOR suggestion THEN
number := pos;
house[ number ] +:= suggestion;
IF NOT left AND NOT right THEN # neighbours not involved #
continue
ELSE # try one or both neighbours #
left or right( pos, left, right, neighbour suggestion, continue )
FI;
house[ number ] -:= suggestion
FI
OD # any2 # ;
# attempts a partial solution for all houses #
PROC any = ( HOUSE suggestion, PROC VOID continue )VOID:
any2( LOC INT, suggestion, FALSE, FALSE, SKIP, continue );
# find solution(s) #
INT blend pos;
INT solutions := 0;
# There are five houses. #
[ 1 : 5 ]HOUSE house;
FOR h TO UPB house DO house[ h ] := ( unknown, unknown, unknown, unknown, unknown ) OD;
# In the middle house they drink milk. #
drink OF house[ 3 ] := milk;
# The Norwegian lives in the first house. #
nationality OF house[ 1 ] := norwegian;
# The Norwegian lives next to the blue house. #
colour OF house[ 2 ] := blue;
# They drink coffee in the green house. #
# The green house is immediately to the left of the white house. #
any2( LOC INT, ( same, same, green, coffee, same )
, FALSE, TRUE, ( same, same, white, same, same ), VOID:
# In a house next to the house where they have a horse, #
# they smoke Dunhill. #
# In the yellow house they smoke Dunhill. #
any2( LOC INT, ( same, horse, same, same, same )
, TRUE, TRUE, ( same, same, yellow, same, dunhill ), VOID:
# The English man lives in the red house. #
any( ( english, same, red, same, same ), VOID:
# The man who smokes Blend lives in the house next to the #
# house with cats. #
any2( blend pos, ( same, same, same, same, blend )
, TRUE, TRUE, ( same, cats, same, same, same ), VOID:
# They drink water in a house next to the house where #
# they smoke Blend. #
left or right( blend pos, TRUE, TRUE, ( same, same, same, water, same ), VOID:
# The Dane drinks tea. #
any( ( dane, same, same, tea, same ), VOID:
# The man who smokes Blue Master drinks beer. #
any( ( same, same, same, beer, blue master ), VOID:
# The Swede has a dog. #
any( ( swede, dog, same, same, same ), VOID:
# The German smokes Prince. #
any( ( german, same, same, same, prince ), VOID:
# The man who smokes Pall Mall has birds. #
any( ( same, birds, same, same, pall mall ), VOID:
# if we can place the zebra, we have a solution #
any( ( same, zebra, same, same, same ), VOID:
( solutions +:= 1;
FOR h TO UPB house DO
print( ( whole( h, 0 )
, " ", nationality[ 1 + nationality OF house[ h ] ]
, ", ", animal [ 1 + animal OF house[ h ] ]
, ", ", colour [ 1 + colour OF house[ h ] ]
, ", ", drink [ 1 + drink OF house[ h ] ]
, ", ", smoke [ 1 + smoke OF house[ h ] ]
, newline
)
)
OD;
print( ( newline ) )
)
) # zebra #
) # pall mall #
) # german #
) # swede #
) # beer #
) # dane #
) # blend L/R #
) # blend #
) # red #
) # horse #
) # green # ;
print( ( "solutions: ", whole( solutions, 0 ), newline ) )
END
|
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name="food">
<item upc="485672034" stock="653">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc="132957764" stock="44">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>
| #AppleScript | AppleScript | set theXMLdata to "<inventory title=\"OmniCorp Store #45x10^3\">
<section name=\"health\">
<item upc=\"123456789\" stock=\"12\">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc=\"445322344\" stock=\"18\">
<name>Levitation Salve</name>
<price>23.99</price>
<description>Levitate yourself for up to 3 hours per application</description>
</item>
</section>
<section name=\"food\">
<item upc=\"485672034\" stock=\"653\">
<name>Blork and Freen Instameal</name>
<price>4.95</price>
<description>A tasty meal in a tablet; just add water</description>
</item>
<item upc=\"132957764\" stock=\"44\">
<name>Grob winglets</name>
<price>3.56</price>
<description>Tender winglets of Grob. Just add water</description>
</item>
</section>
</inventory>"
on getElementValuesByName(theXML, theNameToFind)
set R to {}
tell application "System Events"
repeat with i in theXML
set {theName, theElements} to {i's name, i's XML elements}
if (count of theElements) > 0 then set R to R & my getElementValuesByName(theElements, theNameToFind)
if theName = theNameToFind then set R to R & i's value
end repeat
end tell
return R
end getElementValuesByName
on getBlock(theXML, theItem, theInstance)
set text item delimiters to ""
repeat with i from 1 to theInstance
set {R, blockStart, blockEnd} to {{}, "<" & theItem & space, "</" & theItem & ">"}
set x to offset of blockStart in theXML
if x = 0 then exit repeat
set y to offset of blockEnd in (characters x thru -1 of theXML as string)
if y = 0 then exit repeat
set R to characters x thru (x + y + (length of blockEnd) - 2) of theXML as string
set theXML to characters (y + (length of blockEnd)) thru -1 of theXML as string
end repeat
return R
end getBlock
tell application "System Events"
set xmlData to make new XML data with properties {name:"xmldata", text:theXMLdata}
return my getBlock(xmlData's text, "item", 1) -- Solution to part 1 of problem.
return my getElementValuesByName(xmlData's contents, "name") -- Solution to part 2 of problem.
return my getElementValuesByName(xmlData's contents, "price") -- Solution to part 3 of problem.
end tell |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #ALGOL_68 | ALGOL 68 | INT scale x=2, scale y=1;
CHAR black="#", white=".", clear=" ";
PROC print yin yang = (REAL radius)VOID:(
PROC in circle = (REAL centre x, centre y, radius, x, y)BOOL:
(x-centre x)**2+(y-centre y)**2 <= radius**2;
PROC (REAL, REAL)BOOL
in big circle = in circle(0, 0, radius, , ),
in white semi circle = in circle(0, +radius/2, radius/2, , ),
in small black circle = in circle(0, +radius/2, radius/6, , ),
in black semi circle = in circle(0, -radius/2, radius/2, , ),
in small white circle = in circle(0, -radius/2, radius/6, , );
FOR sy FROM +ROUND(radius * scale y) BY -1 TO -ROUND(radius * scale y) DO
FOR sx FROM -ROUND(radius * scale x) TO +ROUND(radius * scale x) DO
REAL x=sx/scale x, y=sy/scale y;
print(
IF in big circle(x, y) THEN
IF in white semi circle(x, y) THEN
IF in small black circle(x, y) THEN black ELSE white FI
ELIF in black semi circle(x, y) THEN
IF in small white circle(x, y) THEN white ELSE black FI
ELIF x < 0 THEN white ELSE black FI
ELSE
clear
FI
)
OD;
print(new line)
OD
);
main:(
print yin yang(17);
print yin yang(8)
) |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program Ycombi.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*******************************************/
/* Structures */
/********************************************/
/* structure function*/
.struct 0
func_fn: @ next element
.struct func_fn + 4
func_f_: @ next element
.struct func_f_ + 4
func_num:
.struct func_num + 4
func_fin:
/* Initialized data */
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessError: .asciz "\033[31mError Allocation !!!\n"
szFactorielle: .asciz "Function factorielle : \n"
szFibonacci: .asciz "Function Fibonacci : \n"
szCarriageReturn: .asciz "\n"
/* datas message display */
szMessResult: .ascii "Result value :"
sValue: .space 12,' '
.asciz "\n"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main: @ program start
ldr r0,iAdrszMessStartPgm @ display start message
bl affichageMess
adr r0,facFunc @ function factorielle address
bl YFunc @ create Ycombinator
mov r5,r0 @ save Ycombinator
ldr r0,iAdrszFactorielle @ display message
bl affichageMess
mov r4,#1 @ loop counter
1: @ start loop
mov r0,r4
bl numFunc @ create number structure
cmp r0,#-1 @ allocation error ?
beq 99f
mov r1,r0 @ structure number address
mov r0,r5 @ Ycombinator address
bl callFunc @ call
ldr r0,[r0,#func_num] @ load result
ldr r1,iAdrsValue @ and convert ascii string
bl conversion10
ldr r0,iAdrszMessResult @ display result message
bl affichageMess
add r4,#1 @ increment loop counter
cmp r4,#10 @ end ?
ble 1b @ no -> loop
/*********Fibonacci *************/
adr r0,fibFunc @ function factorielle address
bl YFunc @ create Ycombinator
mov r5,r0 @ save Ycombinator
ldr r0,iAdrszFibonacci @ display message
bl affichageMess
mov r4,#1 @ loop counter
2: @ start loop
mov r0,r4
bl numFunc @ create number structure
cmp r0,#-1 @ allocation error ?
beq 99f
mov r1,r0 @ structure number address
mov r0,r5 @ Ycombinator address
bl callFunc @ call
ldr r0,[r0,#func_num] @ load result
ldr r1,iAdrsValue @ and convert ascii string
bl conversion10
ldr r0,iAdrszMessResult @ display result message
bl affichageMess
add r4,#1 @ increment loop counter
cmp r4,#10 @ end ?
ble 2b @ no -> loop
ldr r0,iAdrszMessEndPgm @ display end message
bl affichageMess
b 100f
99: @ display error message
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessStartPgm: .int szMessStartPgm
iAdrszMessEndPgm: .int szMessEndPgm
iAdrszFactorielle: .int szFactorielle
iAdrszFibonacci: .int szFibonacci
iAdrszMessError: .int szMessError
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessResult: .int szMessResult
iAdrsValue: .int sValue
/******************************************************************/
/* factorielle function */
/******************************************************************/
/* r0 contains the Y combinator address */
/* r1 contains the number structure */
facFunc:
push {r1-r3,lr} @ save registers
mov r2,r0 @ save Y combinator address
ldr r0,[r1,#func_num] @ load number
cmp r0,#1 @ > 1 ?
bgt 1f @ yes
mov r0,#1 @ create structure number value 1
bl numFunc
b 100f
1:
mov r3,r0 @ save number
sub r0,#1 @ decrement number
bl numFunc @ and create new structure number
cmp r0,#-1 @ allocation error ?
beq 100f
mov r1,r0 @ new structure number -> param 1
ldr r0,[r2,#func_f_] @ load function address to execute
bl callFunc @ call
ldr r1,[r0,#func_num] @ load new result
mul r0,r1,r3 @ and multiply by precedent
bl numFunc @ and create new structure number
@ and return her address in r0
100:
pop {r1-r3,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* fibonacci function */
/******************************************************************/
/* r0 contains the Y combinator address */
/* r1 contains the number structure */
fibFunc:
push {r1-r4,lr} @ save registers
mov r2,r0 @ save Y combinator address
ldr r0,[r1,#func_num] @ load number
cmp r0,#1 @ > 1 ?
bgt 1f @ yes
mov r0,#1 @ create structure number value 1
bl numFunc
b 100f
1:
mov r3,r0 @ save number
sub r0,#1 @ decrement number
bl numFunc @ and create new structure number
cmp r0,#-1 @ allocation error ?
beq 100f
mov r1,r0 @ new structure number -> param 1
ldr r0,[r2,#func_f_] @ load function address to execute
bl callFunc @ call
ldr r4,[r0,#func_num] @ load new result
sub r0,r3,#2 @ new number - 2
bl numFunc @ and create new structure number
cmp r0,#-1 @ allocation error ?
beq 100f
mov r1,r0 @ new structure number -> param 1
ldr r0,[r2,#func_f_] @ load function address to execute
bl callFunc @ call
ldr r1,[r0,#func_num] @ load new result
add r0,r1,r4 @ add two results
bl numFunc @ and create new structure number
@ and return her address in r0
100:
pop {r1-r4,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* call function */
/******************************************************************/
/* r0 contains the address of the function */
/* r1 contains the address of the function 1 */
callFunc:
push {r2,lr} @ save registers
ldr r2,[r0,#func_fn] @ load function address to execute
blx r2 @ and call it
pop {r2,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* create Y combinator function */
/******************************************************************/
/* r0 contains the address of the function */
YFunc:
push {r1,lr} @ save registers
mov r1,#0
bl newFunc
cmp r0,#-1 @ allocation error ?
strne r0,[r0,#func_f_] @ store function and return in r0
pop {r1,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* create structure number function */
/******************************************************************/
/* r0 contains the number */
numFunc:
push {r1,r2,lr} @ save registers
mov r2,r0 @ save number
mov r0,#0 @ function null
mov r1,#0 @ function null
bl newFunc
cmp r0,#-1 @ allocation error ?
strne r2,[r0,#func_num] @ store number in new structure
pop {r1,r2,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* new function */
/******************************************************************/
/* r0 contains the function address */
/* r1 contains the function address 1 */
newFunc:
push {r2-r7,lr} @ save registers
mov r4,r0 @ save address
mov r5,r1 @ save adresse 1
@ allocation place on the heap
mov r0,#0 @ allocation place heap
mov r7,#0x2D @ call system 'brk'
svc #0
mov r3,r0 @ save address heap for output string
add r0,#func_fin @ reservation place one element
mov r7,#0x2D @ call system 'brk'
svc #0
cmp r0,#-1 @ allocation error
beq 100f
mov r0,r3
str r4,[r0,#func_fn] @ store address
str r5,[r0,#func_f_]
mov r2,#0
str r2,[r0,#func_num] @ store zero to number
100:
pop {r2-r7,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
//
(* ****** ****** *)
//
extern
fun
Zig_zag_matrix(n: int): void
//
(* ****** ****** *)
fun max(a: int, b: int): int =
if a > b then a else b
fun movex(n: int, x: int, y: int): int =
if y < n-1 then max(0, x-1) else x+1
fun movey(n: int, x: int, y: int): int =
if y < n-1 then y+1 else y
fun zigzag(n: int, i: int, row: int, x: int, y: int): void =
if i = n*n then ()
else
let
val () = (if x = row then begin print i; print ','; end else ())
//val () = (begin print x; print ' '; print y; print ' '; print i; print ' '; end)
val nextX: int = if ((x+y) % 2) = 0 then movex(n, x, y) else movey(n, y, x)
val nextY: int = if ((x+y) % 2) = 0 then movey(n, x, y) else movex(n, y, x)
in
zigzag(n, i+1, row, nextX, nextY)
end
implement
Zig_zag_matrix(n) =
let
fun loop(row: int): void =
if row = n then () else
let
val () = zigzag(n, 0, row, 0, 0)
val () = println!(" ")
in
loop(row + 1)
end
in
loop(0)
end
(* ****** ****** *)
implement
main0() = () where
{
val () = Zig_zag_matrix(5)
} (* end of [main0] *)
(* ****** ****** *)
|
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #J | J |
Until=: 2 :'u^:(0-:v)^:_'
assert 44 -: >:Until(>&43) 32 NB. increment until exceeding 43
gcd=: +.
coprime=: 1 = gcd
prepare=:1 2 3"_ NB. start with the vector 1 2 3
condition=: 0 1 -: (coprime _2&{.) NB. trial coprime most recent 2, nay and yay
append=: , NB. concatenate
novel=: -.@e. NB. x is not a member of y
term=: >:@:]Until((condition *. novel)~) 4:
ys=: (append term)@]^:(0 >. _3+[) prepare
assert (ys 30) -: 1 2 3 4 9 8 15 14 5 6 25 12 35 16 7 10 21 20 27 22 39 11 13 33 26 45 28 51 32 17
|
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Java | Java |
import java.util.ArrayList;
import java.util.List;
public class YellowstoneSequence {
public static void main(String[] args) {
System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30));
}
private static List<Integer> yellowstoneSequence(int sequenceCount) {
List<Integer> yellowstoneList = new ArrayList<Integer>();
yellowstoneList.add(1);
yellowstoneList.add(2);
yellowstoneList.add(3);
int num = 4;
List<Integer> notYellowstoneList = new ArrayList<Integer>();
int yellowSize = 3;
while ( yellowSize < sequenceCount ) {
int found = -1;
for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {
int test = notYellowstoneList.get(index);
if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {
found = index;
break;
}
}
if ( found >= 0 ) {
yellowstoneList.add(notYellowstoneList.remove(found));
yellowSize++;
}
else {
while ( true ) {
if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {
yellowstoneList.add(num);
yellowSize++;
num++;
break;
}
notYellowstoneList.add(num);
num++;
}
}
}
return yellowstoneList;
}
private static final int gcd(int a, int b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
}
|
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #GUISS | GUISS | Start,Programs,Applications,Mozilla Firefox,Inputbox:address bar>www.yahoo.co.uk,
Button:Go,Area:browser window,Inputbox:searchbox>elephants,Button:Search |
http://rosettacode.org/wiki/Yahoo!_search_interface | Yahoo! search interface | Create a class for searching Yahoo! results.
It must implement a Next Page method, and read URL, Title and Content from results.
| #Haskell | Haskell | import Network.HTTP
import Text.Parsec
data YahooSearchItem = YahooSearchItem {
itemUrl, itemTitle, itemContent :: String }
data YahooSearch = YahooSearch {
searchQuery :: String,
searchPage :: Int,
searchItems :: [YahooSearchItem] }
-- URL for Yahoo! searches, without giving a page number
yahooUrl = "http://search.yahoo.com/search?p="
-- make an HTTP request and return a YahooSearch
yahoo :: String -> IO YahooSearch
yahoo q = simpleHTTP (getRequest $ yahooUrl ++ q) >>=
getResponseBody >>= return . YahooSearch q 1 . items
-- get some results and return the next page of results
next :: YahooSearch -> IO YahooSearch
next (YahooSearch q p _) =
simpleHTTP (getRequest $
-- add the page number to the search
yahooUrl ++ q ++ "&b=" ++ show (p + 1)) >>=
getResponseBody >>= return . YahooSearch q (p + 1) . items
printResults :: YahooSearch -> IO ()
printResults (YahooSearch q p items) = do
putStrLn $ "Showing Yahoo! search results for query: " ++ q
putStrLn $ "Page: " ++ show p
putChar '\n'
mapM_ printOne items
where
printOne (YahooSearchItem itemUrl itemTitle itemContent) = do
putStrLn $ "URL : " ++ itemUrl
putStrLn $ "Title : " ++ itemTitle
putStrLn $ "Abstr : " ++ itemContent
putChar '\n'
urlTag, titleTag, contentTag1, contentTag2, ignoreTag,
ignoreText :: Parsec String () String
-- parse a tag containing the URL of a search result
urlTag = do { string "<a id=\"link-";
many digit; string "\" class=\"yschttl spt\" href=\"";
url <- manyTill anyChar (char '"'); manyTill anyChar (char '>');
return url }
-- the title comes after the URL tag, so parse it first, discard it
-- and get the title text
titleTag = do { urlTag; manyTill anyChar (try (string "</a>")) }
-- parse a tag containing the description of the search result
-- the tag can be named "sm-abs" or "abstr"
contentTag1 = do { string "<div class=\"sm-abs\">";
manyTill anyChar (try (string "</div>")) }
contentTag2 = do { string "<div class=\"abstr\">";
manyTill anyChar (try (string "</div>")) }
-- parse a tag and discard it
ignoreTag = do { char ('<'); manyTill anyChar (char '>');
return "" }
-- parse some text and discard it
ignoreText = do { many1 (noneOf "<"); return "" }
-- return only non-empty strings
nonempty :: [String] -> Parsec String () [String]
nonempty xs = return [ x | x <- xs, not (null x) ]
-- a template to parse a whole source file looking for items of the
-- same class
parseCategory x = do
res <- many x
eof
nonempty res
urls, titles, contents :: Parsec String () [String]
-- parse HTML source looking for URL tags of the search results
urls = parseCategory url where
url = (try urlTag) <|> ignoreTag <|> ignoreText
-- parse HTML source looking for titles of the search results
titles = parseCategory title where
title = (try titleTag) <|> ignoreTag <|> ignoreText
-- parse HTML source looking for descriptions of the search results
contents = parseCategory content where
content = (try contentTag1) <|> (try contentTag2) <|>
ignoreTag <|> ignoreText
-- parse the HTML source three times looking for URL, title and
-- description of all search results and return them as a list of
-- YahooSearchItem
items :: String -> [YahooSearchItem]
items q =
let ignoreOrKeep = either (const []) id
us = ignoreOrKeep $ parse urls "" q
ts = ignoreOrKeep $ parse titles "" q
cs = ignoreOrKeep $ parse contents "" q
in [ YahooSearchItem { itemUrl = u, itemTitle = t, itemContent = c } |
(u, t, c) <- zip3 us ts cs ]
|
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.
| #Tcl | Tcl | namespace import tcl::mathop::*
proc ast str {
# produce abstract syntax tree for an expression
regsub -all {[-+*/()]} $str { & } str ;# "tokenizer"
s $str
}
proc s {args} {
# parse "(a + b) * c + d" to "+ [* [+ a b] c] d"
if {[llength $args] == 1} {set args [lindex $args 0]}
if [regexp {[()]} $args] {
eval s [string map {( "\[s " ) \]} $args]
} elseif {"*" in $args} {
s [s_group $args *]
} elseif {"/" in $args} {
s [s_group $args /]
} elseif {"+" in $args} {
s [s_group $args +]
} elseif {"-" in $args} {
s [s_group $args -]
} else {
string map {\{ \[ \} \]} [join $args]
}
}
proc s_group {list op} {
# turn ".. a op b .." to ".. {op a b} .."
set pos [lsearch -exact $list $op]
set p_1 [- $pos 1]
set p1 [+ $pos 1]
lreplace $list $p_1 $p1 \
[list $op [lindex $list $p_1] [lindex $list $p1]]
}
#-- Test suite
foreach test [split {
ast 2-2
ast 1-2-3
ast (1-2)-3
ast 1-(2-3)
ast (1+2)*3
ast (1+2)/3-4*5
ast ((1+2)/3-4)*5
} \n] {
puts "$test ..... [eval $test] ..... [eval [eval $test]]"
} |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Class Zeckendorf
Implements IComparable(Of Zeckendorf)
Private Shared ReadOnly dig As String() = {"00", "01", "10"}
Private Shared ReadOnly dig1 As String() = {"", "1", "10"}
Private dVal As Integer = 0
Private dLen As Integer = 0
Public Sub New(Optional x As String = "0")
Dim q = 1
Dim i = x.Length - 1
dLen = i \ 2
Dim z = Asc("0")
While i >= 0
Dim a = Asc(x(i))
dVal += (a - z) * q
q *= 2
i -= 1
End While
End Sub
Private Sub A(n As Integer)
Dim i = n
While True
If dLen < i Then
dLen = i
End If
Dim j = (dVal >> (i * 2)) And 3
If j = 0 OrElse j = 1 Then
Return
ElseIf j = 2 Then
If ((dVal >> ((i + 1) * 2)) And 1) <> 1 Then
Return
End If
dVal += 1 << (i * 2 + 1)
Return
ElseIf j = 3 Then
Dim temp = 3 << (i * 2)
temp = temp Xor -1
dVal = dVal And temp
B((i + 1) * 2)
End If
i += 1
End While
End Sub
Private Sub B(pos As Integer)
If pos = 0 Then
Inc()
Return
End If
If ((dVal >> pos) And 1) = 0 Then
dVal += 1 << pos
A(pos \ 2)
If pos > 1 Then
A(pos \ 2 - 1)
End If
Else
Dim temp = 1 << pos
temp = temp Xor -1
dVal = dVal And temp
B(pos + 1)
B(pos - If(pos > 1, 2, 1))
End If
End Sub
Private Sub C(pos As Integer)
If ((dVal >> pos) And 1) = 1 Then
Dim temp = 1 << pos
temp = temp Xor -1
dVal = dVal And temp
Return
End If
C(pos + 1)
If pos > 0 Then
B(pos - 1)
Else
Inc()
End If
End Sub
Public Function Inc() As Zeckendorf
dVal += 1
A(0)
Return Me
End Function
Public Function Copy() As Zeckendorf
Dim z As New Zeckendorf With {
.dVal = dVal,
.dLen = dLen
}
Return z
End Function
Public Sub PlusAssign(other As Zeckendorf)
Dim gn = 0
While gn < (other.dLen + 1) * 2
If ((other.dVal >> gn) And 1) = 1 Then
B(gn)
End If
gn += 1
End While
End Sub
Public Sub MinusAssign(other As Zeckendorf)
Dim gn = 0
While gn < (other.dLen + 1) * 2
If ((other.dVal >> gn) And 1) = 1 Then
C(gn)
End If
gn += 1
End While
While (((dVal >> dLen * 2) And 3) = 0) OrElse dLen = 0
dLen -= 1
End While
End Sub
Public Sub TimesAssign(other As Zeckendorf)
Dim na = other.Copy
Dim nb = other.Copy
Dim nt As Zeckendorf
Dim nr As New Zeckendorf
Dim i = 0
While i < (dLen + 1) * 2
If ((dVal >> i) And 1) > 0 Then
nr.PlusAssign(nb)
End If
nt = nb.Copy
nb.PlusAssign(na)
na = nt.Copy
i += 1
End While
dVal = nr.dVal
dLen = nr.dLen
End Sub
Public Function CompareTo(other As Zeckendorf) As Integer Implements IComparable(Of Zeckendorf).CompareTo
Return dVal.CompareTo(other.dVal)
End Function
Public Overrides Function ToString() As String
If dVal = 0 Then
Return "0"
End If
Dim idx = (dVal >> (dLen * 2)) And 3
Dim sb As New StringBuilder(dig1(idx))
Dim i = dLen - 1
While i >= 0
idx = (dVal >> (i * 2)) And 3
sb.Append(dig(idx))
i -= 1
End While
Return sb.ToString
End Function
End Class
Sub Main()
Console.WriteLine("Addition:")
Dim g As New Zeckendorf("10")
g.PlusAssign(New Zeckendorf("10"))
Console.WriteLine(g)
g.PlusAssign(New Zeckendorf("10"))
Console.WriteLine(g)
g.PlusAssign(New Zeckendorf("1001"))
Console.WriteLine(g)
g.PlusAssign(New Zeckendorf("1000"))
Console.WriteLine(g)
g.PlusAssign(New Zeckendorf("10101"))
Console.WriteLine(g)
Console.WriteLine()
Console.WriteLine("Subtraction:")
g = New Zeckendorf("1000")
g.MinusAssign(New Zeckendorf("101"))
Console.WriteLine(g)
g = New Zeckendorf("10101010")
g.MinusAssign(New Zeckendorf("1010101"))
Console.WriteLine(g)
Console.WriteLine()
Console.WriteLine("Multiplication:")
g = New Zeckendorf("1001")
g.TimesAssign(New Zeckendorf("101"))
Console.WriteLine(g)
g = New Zeckendorf("101010")
g.PlusAssign(New Zeckendorf("101"))
Console.WriteLine(g)
End Sub
End Module |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #REXX | REXX | /*REXX pgm finds & shows Zumkeller numbers: 1st N; 1st odd M; 1st odd V not ending in 5.*/
parse arg n m v . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 220 /*Not specified? Then use the default.*/
if m=='' | m=="," then m= 40 /* " " " " " " */
if v=='' | v=="," then v= 40 /* " " " " " " */
@zum= ' Zumkeller numbers are: ' /*literal used for displaying messages.*/
sw= linesize() - 1 /*obtain the usable screen width. */
say
if n>0 then say center(' The first ' n @zum, sw, "═")
#= 0 /*the count of Zumkeller numbers so far*/
$= /*initialize the $ list (to a null).*/
do j=1 until #==n /*traipse through integers 'til done. */
if \Zum(j) then iterate /*if not a Zumkeller number, then skip.*/
#= # + 1; call add$ /*bump Zumkeller count; add to $ list.*/
end /*j*/
if $\=='' then say $ /*Are there any residuals? Then display*/
say
if m>0 then say center(' The first odd ' m @zum, sw, "═")
#= 0 /*the count of Zumkeller numbers so far*/
$= /*initialize the $ list (to a null).*/
do j=1 by 2 until #==m /*traipse through integers 'til done. */
if \Zum(j) then iterate /*if not a Zumkeller number, then skip.*/
#= # + 1; call add$ /*bump Zumkeller count; add to $ list.*/
end /*j*/
if $\=='' then say $ /*Are there any residuals? Then display*/
say
if v>0 then say center(' The first odd ' v " (not ending in 5) " @zum, sw, '═')
#= 0 /*the count of Zumkeller numbers so far*/
$= /*initialize the $ list (to a null).*/
do j=1 by 2 until #==v /*traipse through integers 'til done. */
if right(j,1)==5 then iterate /*skip if odd number ends in digit "5".*/
if \Zum(j) then iterate /*if not a Zumkeller number, then skip.*/
#= # + 1; call add$ /*bump Zumkeller count; add to $ list.*/
end /*j*/
if $\=='' then say $ /*Are there any residuals? Then display*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
add$: _= strip($ j, 'L'); if length(_)<sw then do; $= _; return; end /*add to $*/
say strip($, 'L'); $= j; return /*say, add*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt: procedure; parse arg x; r= 0; q= 1; do while q<=x; q=q*4; end
do while q>1; q= q%4; _= x-r-q; r= r%2; if _>=0 then do; x= _; r= r+q; end; end
return r /*R is the integer square root of X. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
PDaS: procedure; parse arg x 1 b; odd= x//2 /*obtain X and B (the 1st argument).*/
if x==1 then return 1 1 /*handle special case for unity. */
r= iSqrt(x) /*calculate integer square root of X. */
a= 1 /* [↓] use all, or only odd numbers. */
sig= a + b /*initialize the sigma (so far) ___ */
do j=2+odd by 1+odd to r - (r*r==x) /*divide by some integers up to √ X */
if x//j==0 then do; a=a j; b= x%j b /*if ÷, add both divisors to α & ß. */
sig= sig +j +x%j /*bump the sigma (the sum of divisors).*/
end
end /*j*/ /* [↑] % is the REXX integer division*/
/* [↓] adjust for a square. ___*/
if j*j==x then return sig+j a j b /*Was X a square? If so, add √ X */
return sig a b /*return the divisors (both lists). */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Zum: procedure; parse arg x . /*obtain a # to be tested for Zumkeller*/
if x<6 then return 0 /*test if X is too low " " */
if x<945 then if x//2==1 then return 0 /* " " " " " " for odd " */
parse value PDaS(x) with sigma pdivs /*obtain sigma and the proper divisors.*/
if sigma//2 then return 0 /*Is the sigma odd? Not Zumkeller.*/
#= words(pdivs) /*count the number of divisors for X. */
if #<3 then return 0 /*Not enough divisors? " " */
if x//2 then do; _= sigma - x - x /*use abundant optimization for odd #'s*/
return _>0 & _//2==0 /*Abundant is > 0 and even? It's a Zum*/
end
if #>23 then return 1 /*# divisors is 24 or more? It's a Zum*/
do i=1 for #; @.i= word(pdivs, i) /*assign proper divisors to the @ array*/
end /*i*/
c=0; u= 2**#; !.= .
do p=1 for u-2; b= x2b(d2x(p)) /*convert P──►binary with leading zeros*/
b= right(strip(b, 'L', 0), #, 0) /*ensure enough leading zeros for B. */
r= reverse(b); if !.r\==. then iterate /*is this binary# a palindrome of prev?*/
c= c + 1; yy.c= b; !.b= /*store this particular combination. */
end /*p*/
do part=1 for c; p1= 0; p2= 0 /*test of two partitions add to same #.*/
_= yy.part /*obtain one method of partitioning. */
do cp=1 for # /*obtain the sums of the two partitions*/
if substr(_, cp, 1) then p1= p1 + @.cp /*if a one, then add it to P1.*/
else p2= p2 + @.cp /* " " zero, " " " " P2.*/
end /*cp*/
if p1==p2 then return 1 /*Partition sums equal? Then X is Zum.*/
end /*part*/
return 0 /*no partition sum passed. X isn't Zum*/ |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #FreeBASIC | FreeBASIC | #Include once "gmp.bi"
Dim Shared As Zstring * 100000000 outtext
Function Power(number As String,n As Uinteger) As String'automate precision
#define dp 3321921
Dim As __mpf_struct _number,FloatAnswer
Dim As Ulongint ln=Len(number)*(n)*4
If ln>dp Then ln=dp
mpf_init2(@FloatAnswer,ln)
mpf_init2(@_number,ln)
mpf_set_str(@_number,number,10)
mpf_pow_ui(@Floatanswer,@_number,n)
gmp_sprintf( @outtext,"%." & Str(n) & "Ff",@FloatAnswer )
Var outtxt=Trim(outtext)
If Instr(outtxt,".") Then outtxt= Rtrim(outtxt,"0"):outtxt=Rtrim(outtxt,".")
Return Trim(outtxt)
End Function
Extern gmp_version Alias "__gmp_version" As Zstring Ptr
Print "GMP version ";*gmp_version
Print
var ans=power("5",(4^(3^2)))
Print Left(ans,20) + " ... "+Right(ans,20)
Print "Number of digits ";Len(ans)
Sleep |
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
| #REXX | REXX | /*REXX program thins a NxM character grid using the Zhang-Suen thinning algorithm.*/
parse arg iFID .; if iFID=='' then iFID='ZHANG_SUEN.DAT'
white=' '; @.=white /* [↓] read the input character grid. */
do row=1 while lines(iFID)\==0; _=linein(iFID)
_=translate(_,,.0); cols.row=length(_)
do col=1 for cols.row; @.row.col=substr(_,col,1)
end /*col*/ /* [↑] assign whole row of characters.*/
end /*row*/
rows=row-1 /*adjust ROWS because of the DO loop. */
call show@ 'input file ' iFID " contents:" /*display show the input character grid*/
do until changed==0; changed=0 /*keep slimming until we're finished. */
do step=1 for 2 /*keep track of step one or step two.*/
do r=1 for rows /*process all the rows and columns. */
do c=1 for cols.r; [email protected] /*assign an alternate grid. */
if r==1|r==rows|c==1|c==cols.r then iterate /*is this an edge?*/
if @.r.c==white then iterate /*Is the character white? Then skip it*/
call Ps; b=b() /*define Ps and also "b". */
if b<2 | b>6 then iterate /*is B within the range ? */
if a()\==1 then iterate /*count the number of transitions. */ /* ╔══╦══╦══╗ */
if step==1 then if (p2 & p4 & p6) | p4 & p6 & p8 then iterate /* ║p9║p2║p3║ */
if step==2 then if (p2 & p4 & p8) | p2 & p6 & p8 then iterate /* ╠══╬══╬══╣ */
!.r.c=white /*set a grid character to white. */ /* ║p8║p1║p4║ */
changed=1 /*indicate a character was changed. */ /* ╠══╬══╬══╣ */
end /*c*/ /* ║p7║p6║p5║ */
end /*r*/ /* ╚══╩══╩══╝ */
call copy! /*copy the alternate to working grid. */
end /*step*/
end /*until changed==0*/
call show@ 'slimmed output:' /*display the slimmed character grid. */
exit /*stick a fork in it, we're all done. */
/*─────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
a: return (\p2==p3&p3)+(\p3==p4&p4)+(\p4==p5&p5)+(\p5==p6&p6)+(\p6==p7&p7)+(\p7==p8&p8)+(\p8==p9&p9)+(\p9==p2&p2)
b: return p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
copy!: do r=1 for rows; do c=1 for cols.r; @.r.c=!.r.c; end; end; return
show@: say; say arg(1); say; do r=1 for rows; _=; do c=1 for cols.r; _=_ || @.r.c; end; say _; end; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
Ps: rm=r-1; rp=r+1; cm=c-1; cp=c+1 /*calculate some shortcuts.*/
[email protected]\==white; [email protected]\==white; [email protected]\==white; [email protected]\==white
[email protected]\==white; [email protected]\==white; [email protected]\==white; [email protected]\==white; return |
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
| #J | J |
fib=: 3 : 0 " 0
mp=. +/ .*
{.{: mp/ mp~^:(I.|.#:y) 2 2$0 1 1 1x
)
phi=: -:1+%:5
fi =: 3 : 'n - y<fib n=. 0>.(1=y)-~>.(phi^.%:5)+phi^.y'
fsum=: 3 : 0
z=. 0$r=. y
while. 3<r do.
m=. fib fi r
z=. z,m
r=. r-m
end.
z,r$~(*r)+.0=y
)
Filter=: (#~`)(`:6)
' '&~:Filter@:":@:#:@:#.@:((|. fib 2+i.8) e. fsum)&.>i.3 7
┌──────┬──────┬──────┬──────┬──────┬──────┬──────┐
│0 │1 │10 │100 │101 │1000 │1001 │
├──────┼──────┼──────┼──────┼──────┼──────┼──────┤
│1010 │10000 │10001 │10010 │10100 │10101 │100000│
├──────┼──────┼──────┼──────┼──────┼──────┼──────┤
│100001│100010│100100│100101│101000│101001│101010│
└──────┴──────┴──────┴──────┴──────┴──────┴──────┘
|
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.
| #Clio | Clio | fn visit-doors doors step:
if step > 100: doors
else:
[1:100]
-> * fn index:
if index % step: doors[(index - 1)]
else: not doors[(index - 1)]
-> visit-doors (step + 1)
[1:100] -> * n: false -> visit-doors 1 => doors
[1:100] -> * (@eager) fn i:
doors[(i - 1)]
-> if = true: #open
else: #closed
-> print #Door i #is @ |
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)
| #FBSL | FBSL | create MyArray 1 , 2 , 3 , 4 , 5 , 5 cells allot
here constant MyArrayEnd
30 MyArray 7 cells + !
MyArray 7 cells + @ . \ 30
: .array MyArrayEnd MyArray do I @ . cell +loop ; |
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.
| #Racket | Racket |
#lang racket
(define a 3+4i)
(define b 8+0i)
(+ a b) ; addition
(- a b) ; subtraction
(/ a b) ; division
(* a b) ; multiplication
(- a) ; negation
(/ 1 a) ; reciprocal
(conjugate a) ; conjugation
|
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.
| #Raku | Raku | my $a = 1 + i;
my $b = pi + 1.25i;
.say for $a + $b, $a * $b, -$a, 1 / $a, $a.conj;
.say for $a.abs, $a.sqrt, $a.re, $a.im; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.