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/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
| #C.23 | C# | using System;
static class YCombinator<T, TResult>
{
// RecursiveFunc is not needed to call Fix() and so can be private.
private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);
public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =
f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));
}
static class Program
{
static void Main()
{
var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));
var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));
Console.WriteLine(fac(10));
Console.WriteLine(fib(10));
}
}
|
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
| #Beads | Beads | beads 1 program 'Zig-zag Matrix'
calc main_init
var test : array^2 of num = create_array(5)
printMatrix(test)
calc create_array(
dimension:num
):array^2 of num
var
result : array^2 of num
lastValue = dimension^2 - 1
loopFrom
loopTo
row
col
currDiag = 0
currNum = 0
loop
if (currDiag < dimension) // if doing the upper-left triangular half
loopFrom = 1
loopTo = currDiag + 1
else // doing the bottom-right triangular half
loopFrom = currDiag - dimension + 2
loopTo = dimension
loop count:c from:loopFrom to:loopTo
var i = loopFrom + c - 1
if (rem(currDiag, 2) == 0) // want to fill upwards
row = loopTo - i + loopFrom
col = i
else // want to fill downwards
row = i
col = loopTo - i + loopFrom
result[row][col] = currNum
inc currNum
inc currDiag
if (currNum > lastValue)
exit
return result
calc printMatrix(
matrix:array^2 of num
)
var dimension = tree_count(matrix)
var maxDigits = 1 + lg((dimension^2-1), base:10)
loop across:matrix ptr:rowp index:row
var tempstr : str
loop across:rowp index:col
tempstr = tempstr & " " & to_str(matrix[row][col], min:maxDigits)
log(tempstr) |
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
| #Befunge | Befunge | >> 5 >>00p0010p:1:>20p030pv >0g-:0`*:*-:00g:*1-55+/>\55+/:v v:,*84<
v:++!\**2p01:+1g01:g02$$_>>#^4#00#+p#1:#+1#g0#0g#3<^/+ 55\_$:>55+/\|
>55+,20g!00g10g`>#^_$$$@^!`g03g00!g04++**2p03:+1g03!\*+1*2g01:g04.$< |
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].
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | state = {1, 2, 3};
MakeNext[state_List] := Module[{i = First[state], done = False, out},
While[! done,
If[FreeQ[state, i],
If[GCD[Last[state], i] == 1,
If[GCD[state[[-2]], i] > 1,
out = Append[state, i];
done = True;
]
]
];
i++;
];
out
]
Nest[MakeNext, state, 30 - 3]
ListPlot[%] |
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].
| #Nim | Nim | import math
proc yellowstone(n: int): seq[int] =
assert n >= 3
result = @[1, 2, 3]
var present = {1, 2, 3}
var start = 4
while result.len < n:
var candidate = start
while true:
if candidate notin present and gcd(candidate, result[^1]) == 1 and gcd(candidate, result[^2]) != 1:
result.add candidate
present.incl candidate
while start in present: inc start
break
inc candidate
echo yellowstone(30) |
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].
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::Util qw(first);
use GD::Graph::bars;
use constant Inf => 1e5;
sub gcd {
my ($u, $v) = @_;
while ($v) {
($u, $v) = ($v, $u % $v);
}
return abs($u);
}
sub yellowstone {
my($terms) = @_;
my @s = (1, 2, 3);
my @used = (1) x 4;
my $min = 3;
while (1) {
my $index = first { not defined $used[$_] and gcd($_,$s[-2]) != 1 and gcd($_,$s[-1]) == 1 } $min .. Inf;
$used[$index] = 1;
$min = (first { not defined $used[$_] } 0..@used-1) || @used-1;
push @s, $index;
last if @s == $terms;
}
@s;
}
say "The first 30 terms in the Yellowstone sequence:\n" . join ' ', yellowstone(30);
my @data = ( [1..500], [yellowstone(500)]);
my $graph = GD::Graph::bars->new(800, 600);
$graph->set(
title => 'Yellowstone sequence',
y_max_value => 1400,
x_tick_number => 5,
r_margin => 10,
dclrs => [ 'blue' ],
) or die $graph->error;
my $gd = $graph->plot(\@data) or die $graph->error;
open my $fh, '>', 'yellowstone-sequence.png';
binmode $fh;
print $fh $gd->png();
close $fh; |
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.
| #Oz | Oz | declare
[HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']}
[StringX] = {Module.link ['x-oz://system/String.ozf']}
[Regex] = {Module.link ['x-oz://contrib/regex']}
%% Displays page 1 and 3 of the search results.
%% The user can request and display more with context menu->Actions->Make Needed.
proc {ExampleUsage}
Pages = {YahooSearch "Rosetta code"}
in
{Inspector.configure widgetShowStrings true}
{ForAll {Nth Pages 1} Value.makeNeeded}
{ForAll {Nth Pages 3} Value.makeNeeded}
%% Display the infinite list of search result pages.
{Inspect Pages}
end
%% Returns a lazy list of pages.
%% A page is a lazy list of entries like this: result(url:U title:T content:C).
fun {YahooSearch Query}
FetchURL = {CreateURLFetcher}
fun {Page Nr}
StartResult = (Nr-1)*10+1
%% only retrieve it when really needed
Doc = {Value.byNeed fun {$}
{FetchURL "http://search.yahoo.com/search"
["p"#Query "b"#{Int.toString StartResult}]}
end}
RE = "<a class=\"yschttl spt\" href="
in
%% Lazily returns results.
%% In this way it is possible to build the pages list structure
%% without creating the single elements
%% (e.g. retrieve page 1 and 3 but not 2).
for Match in {Regex.allMatches RE Doc} yield:Yield do
Xs = {List.drop Doc Match.0.2}
in
{Yield {ParseEntry Xs}}
end
end
in
for PageNr in 1;PageNr+1 yield:Yield do
{Yield {Page PageNr}}
end
end
fun {CreateURLFetcher}
Client = {New HTTPClient.cgiGET
init(inPrms(toFile:false toStrm:true)
httpReqPrms
)}
%% close when no longer used
{Finalize.register Client proc {$ C} {C closeAll(true)} end}
fun {FetchURL Url Params}
OutParams
in
{Client getService(Url Params ?OutParams ?_)}
OutParams.sOut
end
in
FetchURL
end
%% Xs: String containing HtmL
%% Result: "result(url:U title:T content:C)" or "parseError"
fun {ParseEntry Xs}
proc {Parse Root}
R1 R2 R3 R4 R4 R5 R6 R7
Url = {Fix {QuotedString Xs R1}}
{Const ">" R1 R2}
Title = {Fix {Until "</a>" R2 R3}}
{Const "</h3></div>" R3 R4}
choice
%% "enchanted" result?
{Const "<div class=\"sm-bd sm-nophoto\" id=\"sm-bd-4-1\">" R4 R5}
{Until "</div>" R5 R6 _}
[] %% result with links into document
{Const "<div class=\"sm-bd sm-r\" id=\"sm-bd-8-1\">" R4 R5}
{Until "</ul></div>" R5 R6 _}
[] %% PDF file
{Const "<div class=\"format\">" R4 R5}
{Until "</a></div>" R5 R6 _}
[] %% With Review
{Const "<div class=\"sm-bd sm-r\" id=\"sm-bd-9-1\">" R4 R5}
R6 = nil %% no nice abstract when a review is there
[] %% normal result
R6 = R4
end
Abstract =
choice
{Const "<div class=\"abstr\">" R6 R7}
{Fix {Until "</div>" R7 _}}
[] {Const "<div class=\"sm-abs\">" R6 R7}
{Fix {Until "</div>" R7 _}}
[] ""
end
in
Root = result(url:Url title:Title content:Abstract)
end
in
{CondSelect {SearchOne Parse} 1 parseError}
end
%% Result: contents of Xs until M is found.
%% Xs = {Append M Yr}
fun {Until M Xs ?Yr}
L R
in
{List.takeDrop Xs {Length M} L R}
if L == M then Yr = R nil
elsecase Xs of X|Xr then X|{Until M Xr Yr}
[] nil then Yr = nil nil
end
end
%% Asserts that Xs starts with C. Returns the remainder in Ys.
proc {Const C Xs ?Ys}
{List.takeDrop Xs {Length C} C Ys}
end
%% Assert that a quoted string follows.
%% Returns the unquoted string and binds Ys to the remainder of Xs.
fun {QuotedString &"|Xs ?Ys}
fun {Loop Xs Ys}
case Xs of &\\|&"|Xr then &\\|&"|{Loop Xr Ys}
[] &"|Xr then Ys = Xr nil
[] X|Xr then X|{Loop Xr Ys}
end
end
in
{Loop Xs Ys}
end
%% Remove formatting tags.
fun {Fix Xs}
{Until "</a></h3>"
{FoldL ["<b>" "</b>" "<wbr />" "<wbr>" "<b>...</b>"]
fun {$ Ys Z}
{StringX.replace Ys Z ""}
end
Xs}
_}
end
in
{ExampleUsage} |
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 | #Vlang | Vlang | fn get_divisors(n int) []int {
mut divs := [1, n]
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs << i
if i != j {
divs << j
}
}
}
return divs
}
fn sum(divs []int) int {
mut sum := 0
for div in divs {
sum += div
}
return sum
}
fn is_part_sum(d []int, sum int) bool {
mut divs := d.clone()
if sum == 0 {
return true
}
le := divs.len
if le == 0 {
return false
}
last := divs[le-1]
divs = divs[0 .. le-1]
if last > sum {
return is_part_sum(divs, sum)
}
return is_part_sum(divs, sum) || is_part_sum(divs, sum-last)
}
fn is_zumkeller(n int) bool {
divs := get_divisors(n)
s := sum(divs)
// if sum is odd can't be split into two partitions with equal sums
if s%2 == 1 {
return false
}
// if n is odd use 'abundant odd number' optimization
if n%2 == 1 {
abundance := s - 2*n
return abundance > 0 && abundance%2 == 0
}
// if n and sum are both even check if there's a partition which totals sum / 2
return is_part_sum(divs, s/2)
}
fn main() {
println("The first 220 Zumkeller numbers are:")
for i, count := 2, 0; count < 220; i++ {
if is_zumkeller(i) {
print("${i:3} ")
count++
if count%20 == 0 {
println('')
}
}
}
println("\nThe first 40 odd Zumkeller numbers are:")
for i, count := 3, 0; count < 40; i += 2 {
if is_zumkeller(i) {
print("${i:5} ")
count++
if count%10 == 0 {
println('')
}
}
}
println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
for i, count := 3, 0; count < 40; i += 2 {
if (i % 10 != 5) && is_zumkeller(i) {
print("${i:7} ")
count++
if count%8 == 0 {
println('')
}
}
}
println('')
} |
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 | #Wren | Wren | import "/math" for Int, Nums
import "/fmt" for Fmt
import "io" for Stdout
var isPartSum // recursive
isPartSum = Fn.new { |divs, sum|
if (sum == 0) return true
if (divs.count == 0) return false
var last = divs[-1]
divs = divs[0...-1]
if (last > sum) return isPartSum.call(divs, sum)
return isPartSum.call(divs, sum-last) || isPartSum.call(divs, sum)
}
var isZumkeller = Fn.new { |n|
var divs = Int.divisors(n)
var sum = Nums.sum(divs)
// if sum is odd can't be split into two partitions with equal sums
if (sum % 2 == 1) return false
// if n is odd use 'abundant odd number' optimization
if (n % 2 == 1) {
var abundance = sum - 2 * n
return abundance > 0 && abundance % 2 == 0
}
// if n and sum are both even check if there's a partition which totals sum / 2
return isPartSum.call(divs, sum / 2)
}
System.print("The first 220 Zumkeller numbers are:")
var count = 0
var i = 2
while (count < 220) {
if (isZumkeller.call(i)) {
Fmt.write("$3d ", i)
Stdout.flush()
count = count + 1
if (count % 20 == 0) System.print()
}
i = i + 1
}
System.print("\nThe first 40 odd Zumkeller numbers are:")
count = 0
i = 3
while (count < 40) {
if (isZumkeller.call(i)) {
Fmt.write("$5d ", i)
Stdout.flush()
count = count + 1
if (count % 10 == 0) System.print()
}
i = i + 2
}
System.print("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
count = 0
i = 3
while (count < 40) {
if ((i % 10 != 5) && isZumkeller.call(i)) {
Fmt.write("$7d ", i)
Stdout.flush()
count = count + 1
if (count % 8 == 0) System.print()
}
i = i + 2
}
System.print() |
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
| #J | J | Pow5432=: 5^4^3^2x
Pow5432=: ^/ 5 4 3 2x NB. alternate J solution
# ": Pow5432 NB. number of digits
183231
20 ({. , '...' , -@[ {. ]) ": Pow5432 NB. 20 first & 20 last 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
| #Java | Java | import java.math.BigInteger;
class IntegerPower {
public static void main(String[] args) {
BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());
String str = power.toString();
int len = str.length();
System.out.printf("5**4**3**2 = %s...%s and has %d digits%n",
str.substring(0, 20), str.substring(len - 20), len);
}
} |
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
| #VBA | VBA | Public n As Variant
Private Sub init()
n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]
End Sub
Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant
Dim wtb As Integer
Dim bn As Integer
Dim prev As String: prev = "#"
Dim next_ As String
Dim p2468 As String
For i = 1 To UBound(n)
next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)
wtb = wtb - (prev = "." And next_ <= "#")
bn = bn - (i > 1 And next_ <= "#")
If (i And 1) = 0 Then p2468 = p2468 & prev
prev = next_
Next i
If step = 2 Then '-- make it p6842
p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)
'p2468 = p2468(3..4)&p2468(1..2)
End If
Dim ret(2) As Variant
ret(0) = wtb
ret(1) = bn
ret(2) = p2468
AB = ret
End Function
Private Sub Zhang_Suen(text As Variant)
Dim wtb As Integer
Dim bn As Integer
Dim changed As Boolean, changes As Boolean
Dim p2468 As String '-- (p6842 for step 2)
Dim x As Integer, y As Integer, step As Integer
Do While True
changed = False
For step = 1 To 2
changes = False
For y = 1 To UBound(text) - 1
For x = 2 To Len(text(y)) - 1
If Mid(text(y), x, 1) = "#" Then
ret = AB(text, y, x, step)
wtb = ret(0)
bn = ret(1)
p2468 = ret(2)
If wtb = 1 _
And bn >= 2 And bn <= 6 _
And InStr(1, Mid(p2468, 1, 3), ".") _
And InStr(1, Mid(p2468, 2, 3), ".") Then
changes = True
text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x)
End If
End If
Next x
Next y
If changes Then
For y = 1 To UBound(text) - 1
text(y) = Replace(text(y), "!", ".")
Next y
changed = True
End If
Next step
If Not changed Then Exit Do
Loop
Debug.Print Join(text, vbCrLf)
End Sub
Public Sub main()
init
Dim Small_rc(9) As String
Small_rc(0) = "................................"
Small_rc(1) = ".#########.......########......."
Small_rc(2) = ".###...####.....####..####......"
Small_rc(3) = ".###....###.....###....###......"
Small_rc(4) = ".###...####.....###............."
Small_rc(5) = ".#########......###............."
Small_rc(6) = ".###.####.......###....###......"
Small_rc(7) = ".###..####..###.####..####.###.."
Small_rc(8) = ".###...####.###..########..###.."
Small_rc(9) = "................................"
Zhang_Suen (Small_rc)
End Sub |
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
| #Liberty_BASIC | Liberty BASIC | samples = 20
call zecklist samples
print "Decimal","Zeckendorf"
for n = 0 to samples
print n, zecklist$(n)
next n
Sub zecklist inDEC
dim zecklist$(inDEC)
do
bin$ = dec2bin$(count)
if instr(bin$,"11") = 0 then
zecklist$(found) = bin$
found = found + 1
end if
count = count+1
loop until found = inDEC + 1
End sub
function dec2bin$(inDEC)
do
bin$ = str$(inDEC mod 2) + bin$
inDEC = int(inDEC/2)
loop until inDEC = 0
dec2bin$ = bin$
end function |
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.
| #Coco | Coco | doors = [false] * 100
for pass til doors.length
for i from pass til doors.length by pass + 1
! = doors[i]
for i til doors.length
console.log 'Door %d is %s.', i + 1, if doors[i] then 'open' else 'closed' |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Futhark | Futhark |
[1, 2, 3]
|
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.
| #Scheme | Scheme | (define a 1+i)
(define b 3.14159+1.25i)
(define c (+ a b))
(define c (* a b))
(define c (/ 1 a))
(define c (- a)) |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "complex.s7i";
const proc: main is func
local
var complex: a is complex(1.0, 1.0);
var complex: b is complex(3.14159, 1.2);
begin
writeln("a=" <& a digits 5);
writeln("b=" <& b digits 5);
# addition
writeln("a+b=" <& a + b digits 5);
# multiplication
writeln("a*b=" <& a * b digits 5);
# inversion
writeln("1/a=" <& complex(1.0) / a digits 5);
# negation
writeln("-a=" <& -a digits 5);
end func; |
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
| #TI-89_BASIC | TI-89 BASIC | import "/math" for Int
import "/rat" for Rat
System.print("The following numbers (less than 2^19) are perfect:")
for (i in 2...(1<<19)) {
var sum = Rat.new(1, i)
for (j in Int.properDivisors(i)[1..-1]) sum = sum + Rat.new(1, j)
if (sum == Rat.one) System.print(" %(i)")
} |
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
| #NetRexx | NetRexx | x=0
Say '0**0='||x**x |
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
| #NewLISP | NewLISP | (pow 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
| #C.2B.2B | C++ |
#include <stdio.h>
#include <string.h>
#define defenum(name, val0, val1, val2, val3, val4) \
enum name { val0, val1, val2, val3, val4 }; \
const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 }
defenum( Attrib, Color, Man, Drink, Animal, Smoke );
defenum( Colors, Red, Green, White, Yellow, Blue );
defenum( Mans, English, Swede, Dane, German, Norwegian );
defenum( Drinks, Tea, Coffee, Milk, Beer, Water );
defenum( Animals, Dog, Birds, Cats, Horse, Zebra );
defenum( Smokes, PallMall, Dunhill, Blend, BlueMaster, Prince );
void printHouses(int ha[5][5]) {
const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str};
printf("%-10s", "House");
for (const char *name : Attrib_str) printf("%-10s", name);
printf("\n");
for (int i = 0; i < 5; i++) {
printf("%-10d", i);
for (int j = 0; j < 5; j++) printf("%-10s", attr_names[j][ha[i][j]]);
printf("\n");
}
}
struct HouseNoRule {
int houseno;
Attrib a; int v;
} housenos[] = {
{2, Drink, Milk}, // Cond 9: In the middle house they drink milk.
{0, Man, Norwegian} // Cond 10: The Norwegian lives in the first house.
};
struct AttrPairRule {
Attrib a1; int v1;
Attrib a2; int v2;
bool invalid(int ha[5][5], int i) {
return (ha[i][a1] >= 0 && ha[i][a2] >= 0) &&
((ha[i][a1] == v1 && ha[i][a2] != v2) ||
(ha[i][a1] != v1 && ha[i][a2] == v2));
}
} pairs[] = {
{Man, English, Color, Red}, // Cond 2: The English man lives in the red house.
{Man, Swede, Animal, Dog}, // Cond 3: The Swede has a dog.
{Man, Dane, Drink, Tea}, // Cond 4: The Dane drinks tea.
{Color, Green, Drink, Coffee}, // Cond 6: drink coffee in the green house.
{Smoke, PallMall, Animal, Birds}, // Cond 7: The man who smokes Pall Mall has birds.
{Smoke, Dunhill, Color, Yellow}, // Cond 8: In the yellow house they smoke Dunhill.
{Smoke, BlueMaster, Drink, Beer}, // Cond 13: The man who smokes Blue Master drinks beer.
{Man, German, Smoke, Prince} // Cond 14: The German smokes Prince
};
struct NextToRule {
Attrib a1; int v1;
Attrib a2; int v2;
bool invalid(int ha[5][5], int i) {
return (ha[i][a1] == v1) &&
((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) ||
(i == 4 && ha[i - 1][a2] != v2) ||
(ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2));
}
} nexttos[] = {
{Smoke, Blend, Animal, Cats}, // Cond 11: The man who smokes Blend lives in the house next to the house with cats.
{Smoke, Dunhill, Animal, Horse}, // Cond 12: In a house next to the house where they have a horse, they smoke Dunhill.
{Man, Norwegian, Color, Blue}, // Cond 15: The Norwegian lives next to the blue house.
{Smoke, Blend, Drink, Water} // Cond 16: They drink water in a house next to the house where they smoke Blend.
};
struct LeftOfRule {
Attrib a1; int v1;
Attrib a2; int v2;
bool invalid(int ha[5][5]) {
return (ha[0][a2] == v2) || (ha[4][a1] == v1);
}
bool invalid(int ha[5][5], int i) {
return ((i > 0 && ha[i][a1] >= 0) &&
((ha[i - 1][a1] == v1 && ha[i][a2] != v2) ||
(ha[i - 1][a1] != v1 && ha[i][a2] == v2)));
}
} leftofs[] = {
{Color, Green, Color, White} // Cond 5: The green house is immediately to the left of the white house.
};
bool invalid(int ha[5][5]) {
for (auto &rule : leftofs) if (rule.invalid(ha)) return true;
for (int i = 0; i < 5; i++) {
#define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true;
eval_rules(pairs);
eval_rules(nexttos);
eval_rules(leftofs);
}
return false;
}
void search(bool used[5][5], int ha[5][5], const int hno, const int attr) {
int nexthno, nextattr;
if (attr < 4) {
nextattr = attr + 1;
nexthno = hno;
} else {
nextattr = 0;
nexthno = hno + 1;
}
if (ha[hno][attr] != -1) {
search(used, ha, nexthno, nextattr);
} else {
for (int i = 0; i < 5; i++) {
if (used[attr][i]) continue;
used[attr][i] = true;
ha[hno][attr] = i;
if (!invalid(ha)) {
if ((hno == 4) && (attr == 4)) {
printHouses(ha);
} else {
search(used, ha, nexthno, nextattr);
}
}
used[attr][i] = false;
}
ha[hno][attr] = -1;
}
}
int main() {
bool used[5][5] = {};
int ha[5][5]; memset(ha, -1, sizeof(ha));
for (auto &rule : housenos) {
ha[rule.houseno][rule.a] = rule.v;
used[rule.a][rule.v] = true;
}
search(used, ha, 0, 0);
return 0;
}
|
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>
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class XML.Inventory [ Abstract ]
{
XData XMLData
{
<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>
}
ClassMethod QueryXMLDoc(Output names As %List) As %Status
{
// get xml stream from the 'XData' block contained in this class
Set xdata=##class(%Dictionary.CompiledXData).%OpenId($this_"||XMLData",, .sc)
If $$$ISERR(sc) Quit sc
Set sc=##class(%XML.XPATH.Document).CreateFromStream(xdata.Data, .xdoc)
If $$$ISERR(sc) Quit sc
// retrieve the first 'item' element
Set sc=xdoc.EvaluateExpression("//section[1]", "item[1]", .res)
// perform an action on each 'price' element (print it out)
Set sc=xdoc.EvaluateExpression("//price", "text()", .res)
If $$$ISERR(sc) Quit sc
For i=1:1:res.Count() {
If i>1 Write ", "
Write res.GetAt(i).Value
}
// get an array of all the 'name' elements
Set sc=xdoc.EvaluateExpression("//item", "name", .res)
If $$$ISERR(sc) Quit sc
Set key=""
Do {
Set dom=res.GetNext(.key)
If '$IsObject(dom) Quit
While dom.Read() {
If dom.HasValue Set $List(names, key)=dom.Value
}
} While key'=""
// finished
Quit $$$OK
}
} |
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>
| #CoffeeScript | CoffeeScript |
# Retrieve the first "item" element
doc.evaluate('//item', doc, {}, 7, {}).snapshotItem 0
# Perform an action on each "price" element (print it out)
prices = doc.evaluate "//price", doc, {}, 7, {}
for i in [0...prices.snapshotLength] by 1
console.log prices.snapshotItem(i).textContent
# Get an array of all the "name" elements
names = doc.evaluate "//name", doc, {}, 7, {}
names = for i in [0...names.snapshotLength] by 1
names.snapshotItem i
|
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.
| #Befunge | Befunge | 55+:#. 00p:2*10p:2/20p6/30p01v
@#!`g01:+1g07,+55$<v0-g010p07_
0g-20g+:*+30g:*`v ^_:2/:*:70g0
3+*:-g02-g00g07:_ 0v v!`*:g0
g-20g+:*+20g:*`>v> ^ v1_:70g00
2+*:-g02-g00g07:_ 1v v!`*:g0
g-:*+00g:*`#v_$:0`!0\v0_:70g00
0#+g#1,#$< > 2 #^>#g>#04#1+#: |
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.
| #C | C | #include <stdio.h>
void draw_yinyang(int trans, double scale)
{
printf("<use xlink:href='#y' transform='translate(%d,%d) scale(%g)'/>",
trans, trans, scale);
}
int main()
{ printf(
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\n"
" 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n"
"<svg xmlns='http://www.w3.org/2000/svg' version='1.1'\n"
" xmlns:xlink='http://www.w3.org/1999/xlink'\n"
" width='30' height='30'>\n"
" <defs><g id='y'>\n"
" <circle cx='0' cy='0' r='200' stroke='black'\n"
" fill='white' stroke-width='1'/>\n"
" <path d='M0 -200 A 200 200 0 0 0 0 200\n"
" 100 100 0 0 0 0 0 100 100 0 0 1 0 -200\n"
" z' fill='black'/>\n"
" <circle cx='0' cy='100' r='33' fill='white'/>\n"
" <circle cx='0' cy='-100' r='33' fill='black'/>\n"
" </g></defs>\n");
draw_yinyang(20, .05);
draw_yinyang(8, .02);
printf("</svg>");
return 0;
} |
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
| #C.2B.2B_2 | C++ | g++ --std=c++11 ycomb.cc
|
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
| #BQN | BQN | Flip ← {m←2|+⌜˜↕≠𝕩 ⋄ (⍉𝕩׬m)+𝕩×m}
Zz ← {Flip ⍋∘⍋⌾⥊+⌜˜↕𝕩} |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
int main(int c, char **v)
{
int i, j, m, n, *s;
/* default size: 5 */
if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5;
/* alloc array*/
s = malloc(sizeof(int) * m * m);
for (i = n = 0; i < m * 2; i++)
for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++)
s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++;
for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n'))
printf("%3d", s[i]);
/* free(s) */
return 0;
} |
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].
| #Phix | Phix | --
-- demo\rosetta\Yellowstone_sequence.exw
--
with javascript_semantics
requires("1.0.2")
function yellowstone(integer N)
sequence a = {1, 2, 3},
b = repeat(true,3)
integer i = 4
while length(a) < N do
if (i>length(b) or b[i]=false)
and gcd(i,a[$])=1
and gcd(i,a[$-1])>1 then
a &= i
if i>length(b) then
b &= repeat(false,i-length(b))
end if
b[i] = true
i = 4
end if
i += 1
end while
return a
end function
printf(1,"The first 30 entries of the Yellowstone permutation:\n%v\n", {yellowstone(30)})
-- a simple plot:
include pGUI.e
include IupGraph.e
function get_data(Ihandle graph)
sequence y500 = yellowstone(500)
integer {w,h} = IupGetIntInt(graph,"DRAWSIZE")
IupSetInt(graph,"XTICK",iff(w<640?iff(h<300?100:50):20))
IupSetInt(graph,"YTICK",iff(h<250?iff(h<140?iff(h<120?700:350):200):100))
return {{tagset(500),y500,CD_RED}}
end function
IupOpen()
Ihandle graph = IupGraph(get_data,"RASTERSIZE=960x600")
IupSetAttributes(graph,`GTITLE="Yellowstone Numbers"`)
IupSetInt(graph,"TITLESTYLE",CD_ITALIC)
IupSetAttributes(graph,`XNAME="n", YNAME="a(n)"`)
IupSetAttributes(graph,"XTICK=20,XMIN=0,XMAX=500")
IupSetAttributes(graph,"YTICK=100,YMIN=0,YMAX=1400")
Ihandle dlg = IupDialog(graph,`TITLE="Yellowstone Names"`)
IupSetAttributes(dlg,"MINSIZE=290x140")
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
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.
| #Perl | Perl | package YahooSearch;
use Encode;
use HTTP::Cookies;
use WWW::Mechanize;
# --- Internals -------------------------------------------------
sub apply (&$)
{my $f = shift; local $_ = shift; $f->(); return $_;}
# We construct a cookie to get 100 results per page and prevent
# "enhanced results".
my $search_prefs = 'v=1&n=100&sm=' .
apply {s/([^a-zA-Z0-9])/sprintf '%%%02X', ord $1/ge}
join '|',
map {'!' . $_}
qw(hsb Zq0 XbM sss dDO VFM RQh uZ0 Fxe yCl GP4 FZK yNC mEG niH);
my $cookies = HTTP::Cookies->new;
$cookies->set_cookie(0, 'sB', $search_prefs, '/', 'search.yahoo.com');
my $mech = new WWW::Mechanize
(cookie_jar => $cookies,
stack_depth => 0);
sub read_page
{my ($next, $page, @results) =
($mech->find_link(text => 'Next >')->url,
decode 'iso-8859-1', $mech->content);
while ($page =~ m
{<h3> <a \s class="yschttl \s spt" \s
href=" ([^"]+) " \s* > #"
(.+?) </a>
.+?
<div \s class="abstr">
(.+?) </div>}xg)
{push @results, {url => $1, title => $2, content => $3};
foreach ( @{$results[-1]}{qw(title content)} )
{s/<.+?>//g;
$_ = encode 'utf8', $_;}}
return $next, \@results;}
# --- Methods ---------------------------------------------------
sub new
{my $invocant = shift;
my $class = ref($invocant) || $invocant;
$mech->get('http://search.yahoo.com/search?p=' . apply
{s/([^a-zA-Z0-9 ])/sprintf '%%%02X', ord $1/ge;
s/ /+/g;}
shift);
my ($next, $results) = read_page();
return bless {link_to_next => $next, results => $results}, $class;}
sub results
{@{shift()->{results}};}
sub next_page
{my $invocant = shift;
my $next = $invocant->{link_to_next};
unless ($next)
{$invocant->{results} = [];
return undef;}
$mech->get($next);
($next, my $results) = read_page();
$invocant->{link_to_next} = $next;
$invocant->{results} = $results;
return 1;} |
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 | #zkl | zkl | fcn properDivs(n){ // does not include n
// if(n==1) return(T); // we con't care about this case
( pd:=[1..(n).toFloat().sqrt()].filter('wrap(x){ n%x==0 }) )
.pump(pd,'wrap(pd){ if(pd!=1 and (y:=n/pd)!=pd ) y else Void.Skip })
}
fcn canSum(goal,divs){
if(goal==0 or divs[0]==goal) return(True);
if(divs.len()>1){
if(divs[0]>goal) return(canSum(goal,divs[1,*])); // tail recursion
else return(canSum(goal - divs[0], divs[1,*]) or canSum(goal, divs[1,*]));
}
False
}
fcn isZumkellerW(n){ // a filter for a iterator
ds,sum := properDivs(n), ds.sum(0) + n;
// if sum is odd, it can't be split into two partitions with equal sums
if(sum.isOdd) return(Void.Skip);
// if n is odd use 'abundant odd number' optimization
if(n.isOdd){
abundance:=sum - 2*n;
return( if(abundance>0 and abundance.isEven) n else Void.Skip);
}
canSum(sum/2,ds) and n or Void.Skip // sum is even
} |
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
| #JavaScript | JavaScript | >>> const y = (5n**4n**3n**2n).toString();
>>> console.log(`5**4**3**2 = ${y.slice(0,20)}...${y.slice(-20)} and has ${y.length} digits`);
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits |
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
| #jq | jq |
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
5|power(4|power(3|power(2))) | tostring
| .[:20], .[-20:], length
|
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
| #Wren | Wren | class Point {
construct new(x, y) {
_x = x
_y = y
}
x { _x }
y { _y }
}
var image = [
" ",
" ################# ############# ",
" ################## ################ ",
" ################### ################## ",
" ######## ####### ################### ",
" ###### ####### ####### ###### ",
" ###### ####### ####### ",
" ################# ####### ",
" ################ ####### ",
" ################# ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ###### ",
" ######## ####### ################### ",
" ######## ####### ###### ################## ###### ",
" ######## ####### ###### ################ ###### ",
" ######## ####### ###### ############# ###### ",
" "
]
var nbrs = [
[ 0, -1], [ 1, -1], [ 1, 0],
[ 1, 1], [ 0, 1], [-1, 1],
[-1, 0], [-1, -1], [ 0, -1]
]
var nbrGroups = [
[ [0, 2, 4], [2, 4, 6] ],
[ [0, 2, 6], [0, 4, 6] ]
]
var toWhite = []
var grid = List.filled(image.count, null)
for (i in 0...grid.count) grid[i] = image[i].toList
var numNeighbors = Fn.new { |r, c|
var count = 0
for (i in 0...nbrs.count - 1) {
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == "#") count = count + 1
}
return count
}
var numTransitions = Fn.new { |r, c|
var count = 0
for (i in 0...nbrs.count - 1) {
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == " ") {
if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == "#") count = count + 1
}
}
return count
}
var atLeastOneIsWhite = Fn.new { |r, c, step|
var count = 0
var group = nbrGroups[step]
for (i in 0..1) {
for (j in 0...group[i].count) {
var nbr = nbrs[group[i][j]]
if (grid[r + nbr[1]][c + nbr[0]] == " ") {
count = count + 1
break
}
}
}
return count > 1
}
var thinImage = Fn.new {
var firstStep = false
var hasChanged
while (true) {
hasChanged = false
firstStep = !firstStep
for (r in 1...grid.count - 1) {
for (c in 1...grid[0].count - 1) {
if (grid[r][c] == "#") {
var nn = numNeighbors.call(r, c)
if ((2..6).contains(nn)) {
if (numTransitions.call(r, c) == 1) {
var step = firstStep ? 0 : 1
if (atLeastOneIsWhite.call(r, c, step)) {
toWhite.add(Point.new(c, r))
hasChanged = true
}
}
}
}
}
}
for (p in toWhite) grid[p.y][p.x] = " "
toWhite.clear()
if (!firstStep && !hasChanged) break
}
for (row in grid) System.print(row.join())
}
thinImage.call() |
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
| #Lingo | Lingo | -- Return the distinct Fibonacci numbers not greater than 'n'
on fibsUpTo (n)
fibList = []
last = 1
current = 1
repeat while current <= n
fibList.add(current)
nxt = last + current
last = current
current = nxt
end repeat
return fibList
end
-- Return the Zeckendorf representation of 'n'
on zeckendorf (n)
fib = fibsUpTo(n)
zeck = ""
repeat with pos = fib.count down to 1
if n >= fib[pos] then
zeck = zeck & "1"
n = n - fib[pos]
else
zeck = zeck & "0"
end if
end repeat
if zeck = "" then return "0"
return zeck
end |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Little_Man_Computer | Little Man Computer |
// Little Man Computer, for Rosetta Code.
// Writes Zeckendorf representations of numbers 0..20.
// Works with Peter Higginson's LMC simulator, except that
// user must intervene manually to capture all the output.
LDA c0 // initialize to N = 0
loop STA N
OUT // write N
LDA equals // then equals sign
OTC
BRA wr_zeck // then Zeckendorf rep
return LDA space // then space
OTC
LDA N // done maximum N?
SUB N_max
BRZ halt // yes, halt
LDA N // no, inc N and loop back
ADD c1
BRA loop
halt HLT
c0 DAT 0
N_max DAT 20
equals DAT 61
space DAT 32
// Routine to write Zeckendorf representation of number stored in N.
// Since LMC doesn't support subroutines, returns with "BRA return".
wr_zeck LDA N
SUB c1
BRP phase_1
// N = 0, special case
LDA ascii_0
OTC
BRA done
// N > 0. Phase 1: find largest Fibonacci number <= N
phase_1 STA res // res := N - 1
LDA c1 // initialize Fibonacci terms
STA a
STA b
loop_1 LDA res // here res = N - a (easy proof)
SUB b // is next Fibonacci a + b > N?
BRP next_fib // no, continue Fibonacci
BRA phase_2 // yes, on to phase 2
next_fib STA res // res := res - b
LDA a // (a, b) := (a + b, a)
ADD b
STA a
SUB b
STA b
BRA loop_1 // loop to test new (a, b)
// Phase 2: get Zeckendorf digits by winding Fibonacci back
phase_2 LDA ascii_1 // first digit must be 1
OTC
loop_2 LDA a // done when wound back to a = 1
SUB c1
BRZ done
LDA res // decide next Zeckendorf digit
SUB b // 0 if res < b, 1 if res >= b
BRP dig_is_1
LDA ascii_0
BRA wr_dig
dig_is_1 STA res // res := res - b
LDA ascii_1
wr_dig OTC // write Zeckendorf digit 0 or 1
LDA a // (a, b) := (b, a - b)
SUB b
STA b
LDA a
SUB b
STA a
BRA loop_2 // loop to test new (a, b)
done BRA return
N DAT
res DAT
a DAT
b DAT
c1 DAT 1
ascii_0 DAT 48
ascii_1 DAT 49
// 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.
| #CoffeeScript | CoffeeScript | doors = []
for pass in [1..100]
for i in [pass..100] by pass
doors[i] = !doors[i]
console.log "Doors #{index for index, open of doors when open} are open"
# matrix output
console.log doors.map (open) -> +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)
| #Gambas | Gambas |
DIM mynumbers AS INTEGER[]
myfruits AS STRING[]
mynumbers[0] = 1.5
mynumbers[1] = 2.3
myfruits[0] = "apple"
myfruits[1] = "banana"
|
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.
| #Sidef | Sidef | var a = 1:1 # Complex(1, 1)
var b = 3.14159:1.25 # Complex(3.14159, 1.25)
[ a + b, # addition
a * b, # multiplication
-a, # negation
a.inv, # multiplicative inverse
a.conj, # complex conjugate
a.abs, # abs
a.sqrt, # sqrt
b.re, # real
b.im, # imaginary
].each { |c| say c } |
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
| #Wren | Wren | import "/math" for Int
import "/rat" for Rat
System.print("The following numbers (less than 2^19) are perfect:")
for (i in 2...(1<<19)) {
var sum = Rat.new(1, i)
for (j in Int.properDivisors(i)[1..-1]) sum = sum + Rat.new(1, j)
if (sum == Rat.one) System.print(" %(i)")
} |
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
| #Nial | Nial | 0 0.0 o outer power 0 0.0 o
+--+--+--+
| 1|1.| 1|
+--+--+--+
|1.|1.|1.|
+--+--+--+
| 1|1.| 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
| #Nim | Nim | import math
echo pow(0.0, 0.0) # Floating point exponentiation.
echo 0 ^ 0 # Integer exponentiation. |
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
| #Clojure | Clojure | (ns zebra.core
(:refer-clojure :exclude [==])
(:use [clojure.core.logic]
[clojure.tools.macro :as macro]))
(defne lefto [x y l]
([_ _ [x y . ?r]])
([_ _ [_ . ?r]] (lefto x y ?r)))
(defn nexto [x y l]
(conde
((lefto x y l))
((lefto y x l))))
(defn zebrao [hs]
(macro/symbol-macrolet [_ (lvar)]
(all
(== [_ _ _ _ _] hs)
(membero ['englishman _ _ _ 'red] hs)
(membero ['swede _ _ 'dog _] hs)
(membero ['dane _ 'tea _ _] hs)
(lefto [_ _ _ _ 'green] [_ _ _ _ 'white] hs)
(membero [_ _ 'coffee _ 'green] hs)
(membero [_ 'pallmall _ 'birds _] hs)
(membero [_ 'dunhill _ _ 'yellow] hs)
(== [_ _ [_ _ 'milk _ _] _ _ ] hs)
(firsto hs ['norwegian _ _ _ _])
(nexto [_ 'blend _ _ _] [_ _ _ 'cats _ ] hs)
(nexto [_ _ _ 'horse _] [_ 'dunhill _ _ _] hs)
(membero [_ 'bluemaster 'beer _ _] hs)
(membero ['german 'prince _ _ _] hs)
(nexto ['norwegian _ _ _ _] [_ _ _ _ 'blue] hs)
(nexto [_ _ 'water _ _] [_ 'blend _ _ _] hs)
(membero [_ _ _ 'zebra _] hs))))
(let [solns (run* [q] (zebrao q))
soln (first solns)
zebra-owner (->> soln (filter #(= 'zebra (% 3))) first (#(% 0)))]
(println "solution count:" (count solns))
(println "zebra owner is the" zebra-owner)
(println "full solution (in house order):")
(doseq [h soln] (println " " h)))
|
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>
| #ColdFusion | ColdFusion | <cfsavecontent variable="xmlString">
<inventory
...
</inventory>
</cfsavecontent>
<cfset xml = xmlParse(xmlString)>
<!--- First Task --->
<cfset itemSearch = xmlSearch(xml, "//item")>
<!--- item = the first Item (xml element object) --->
<cfset item = itemSearch[1]>
<!--- Second Task --->
<cfset priceSearch = xmlSearch(xml, "//price")>
<!--- loop and print each price --->
<cfloop from="1" to="#arrayLen(priceSearch)#" index="i">
#priceSearch[i].xmlText#<br/>
</cfloop>
<!--- Third Task --->
<!--- array of all the name elements --->
<cfset names = xmlSearch(xml, "//name")>
<!--- visualize the results --->
<cfdump var="#variables#"> |
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.
| #C.2B.2B | C++ | #include <iostream>
bool circle(int x, int y, int c, int r) {
return (r * r) >= ((x = x / 2) * x) + ((y = y - c) * y);
}
char pixel(int x, int y, int r) {
if (circle(x, y, -r / 2, r / 6)) {
return '#';
}
if (circle(x, y, r / 2, r / 6)) {
return '.';
}
if (circle(x, y, -r / 2, r / 2)) {
return '.';
}
if (circle(x, y, r / 2, r / 2)) {
return '#';
}
if (circle(x, y, 0, r)) {
if (x < 0) {
return '.';
} else {
return '#';
}
}
return ' ';
}
void yinYang(int r) {
for (int y = -r; y <= r; y++) {
for (int x = -2 * r; x <= 2 * r; x++) {
std::cout << pixel(x, y, r);
}
std::cout << '\n';
}
}
int main() {
yinYang(18);
return 0;
} |
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
| #Ceylon_2 | Ceylon | Result(*Args) y1<Result,Args>(
Result(*Args)(Result(*Args)) f)
given Args satisfies Anything[] {
class RecursiveFunction(o) {
shared Result(*Args)(RecursiveFunction) o;
}
value r = RecursiveFunction((RecursiveFunction w)
=> f(flatten((Args args) => w.o(w)(*args))));
return r.o(r);
}
value factorialY1 = y1((Integer(Integer) fact)(Integer x)
=> if (x > 1) then x * fact(x - 1) else 1);
value fibY1 = y1((Integer(Integer) fib)(Integer x)
=> if (x > 2) then fib(x - 1) + fib(x - 2) else 2);
print(factorialY1(10)); // 3628800
print(fibY1(10)); // 110 |
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
| #C.23 | C# | public static int[,] ZigZag(int n)
{
int[,] result = new int[n, n];
int i = 0, j = 0;
int d = -1; // -1 for top-right move, +1 for bottom-left move
int start = 0, end = n * n - 1;
do
{
result[i, j] = start++;
result[n - i - 1, n - j - 1] = end--;
i += d; j -= d;
if (i < 0)
{
i++; d = -d; // top reached, reverse
}
else if (j < 0)
{
j++; d = -d; // left reached, reverse
}
} while (start < end);
if (start == end)
result[i, j] = start;
return result;
} |
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].
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def gcd /# u v -- n #/
abs int swap abs int swap
dup
while
over over mod rot drop dup
endwhile
drop
enddef
def test enddef
def yellow var n
( 1 2 3 ) var a
newd ( 1 true ) setd ( 2 true ) setd ( 3 true ) setd var b
4 var i
test
while
b i getd "Unfound" == >ps
a -1 get >ps -2 get
i gcd 1 > ps> i gcd 1 == ps>
and and if
i 0 put var a
( i true ) setd var b
4 var i
else
drop drop
endif
i 1 + var i
test
endwhile
a
enddef
def test n a len nip > enddef
"The first 30 entries of the Yellowstone permutation:" ? 30 yellow ? |
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].
| #PicoLisp | PicoLisp | (load "@lib/frac.l")
(de yellow (N)
(let (L (list 3 2 1) I 4 C 3 D)
(while (> N C)
(when
(and
(not (idx 'D I))
(=1 (gcd I (get L 1)))
(> (gcd I (get L 2)) 1) )
(push 'L I)
(idx 'D I T)
(setq I 4)
(inc 'C) )
(inc 'I) )
(flip L) ) )
(println (yellow 30)) |
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.
| #Phix | Phix | constant glyphs = {{"\xC2\xB7 ","*"}, -- bullet point
{"'",`'`}, -- single quote
{""",`"`}, -- double quote
{"&","&"}, -- ampersand
{"\xE2\x94\xAC\xC2\xAB","[R]"}, -- registered
{"\xC2\xAE","[R]"}}, -- registered
|
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.
| #PicoLisp | PicoLisp | (load "@lib/http.l")
(de yahoo (Query Page)
(default Page 1)
(client "search.yahoo.com" 80
(pack
"search?p=" (ht:Fmt Query)
"&b=" (inc (* 10 (dec Page))) )
(make
(while (from "<a class=\"yschttl spt\" href=\"")
(link
(make
(link (till "\"" T)) # Url
(from "<b>")
(link (till "<" T)) # Title
(from "class=\"abstr\"")
(from ">")
(link # Content
(pack
(make
(loop
(link (till "<" T))
(T (eof))
(T (= "</div" (till ">" T)))
(char) ) ) ) ) ) ) ) ) ) ) |
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
| #Julia | Julia | julia> @elapsed bigstr = string(BigInt(5)^4^3^2)
0.017507363
julia> length(bigstr)
183231
julia> bigstr[1:20]
"62060698786608744707"
julia> bigstr[end-20:end]
"892256259918212890625" |
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
| #Klong | Klong | n::$5^4^3^2
.p("5^4^3^2 = ",(20#n),"...",((-20)#n)," and has ",($#n)," digits")
|
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
| #Kotlin | Kotlin | import java.math.BigInteger
fun main(args: Array<String>) {
val x = BigInteger.valueOf(5).pow(Math.pow(4.0, 3.0 * 3.0).toInt())
val y = x.toString()
val len = y.length
println("5^4^3^2 = ${y.substring(0, 20)}...${y.substring(len - 20)} and has $len digits")
} |
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
| #Logo | Logo | ; return the (N+1)th Fibonacci number (1,2,3,5,8,13,...)
to fib m
local "n
make "n sum :m 1
if [lessequal? :n 0] [output difference fib sum :n 2 fib sum :n 1]
global "_fib
if [not name? "_fib] [
make "_fib [1 1]
]
local "length
make "length count :_fib
while [greater? :n :length] [
make "_fib (lput (sum (last :_fib) (last (butlast :_fib))) :_fib)
make "length sum :length 1
]
output item :n :_fib
end
; return the binary Zeckendorf representation of a nonnegative number
to zeckendorf n
if [less? :n 0] [(throw "error [Number must be nonnegative.])]
(local "i "f "result)
make "i :n
make "f fib :i
while [less? :f :n] [make "i sum :i 1 make "f fib :i]
make "result "||
while [greater? :i 0] [
ifelse [greaterequal? :n :f] [
make "result lput 1 :result
make "n difference :n :f
] [
if [not empty? :result] [
make "result lput 0 :result
]
]
make "i difference :i 1
make "f fib :i
]
if [equal? :result "||] [
make "result 0
]
output :result
end
type zeckendorf 0
repeat 20 [
type word "| | zeckendorf repcount
]
print []
bye |
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
| #Lua | Lua | -- Return the distinct Fibonacci numbers not greater than 'n'
function fibsUpTo (n)
local fibList, last, current, nxt = {}, 1, 1
while current <= n do
table.insert(fibList, current)
nxt = last + current
last = current
current = nxt
end
return fibList
end
-- Return the Zeckendorf representation of 'n'
function zeckendorf (n)
local fib, zeck = fibsUpTo(n), ""
for pos = #fib, 1, -1 do
if n >= fib[pos] then
zeck = zeck .. "1"
n = n - fib[pos]
else
zeck = zeck .. "0"
end
end
if zeck == "" then return "0" end
return zeck
end
-- Main procedure
print(" n\t| Zeckendorf(n)")
print(string.rep("-", 23))
for n = 0, 20 do
print(" " .. n, "| " .. zeckendorf(n))
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.
| #ColdFusion | ColdFusion |
doorCount = 1;
doorList = "";
// create all doors and set all doors to open
while (doorCount LTE 100) {
doorList = ListAppend(doorList,"1");
doorCount = doorCount + 1;
}
loopCount = 2;
doorListLen = ListLen(doorList);
while (loopCount LTE 100) {
loopDoorListCount = 1;
while (loopDoorListCount LTE 100) {
testDoor = loopDoorListCount / loopCount;
if (testDoor EQ Int(testDoor)) {
checkOpen = ListGetAt(doorList,loopDoorListCount);
if (checkOpen EQ 1) {
doorList = ListSetAt(doorList,loopDoorListCount,"0");
} else {
doorList = ListSetAt(doorList,loopDoorListCount,"1");
}
}
loopDoorListCount = loopDoorListCount + 1;
}
loopCount = loopCount + 1;
}
|
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)
| #GAP | GAP | # Arrays are better called lists in GAP. Lists may have elements of mixed types, e$
v := [ 10, 7, "bob", true, [ "inner", 5 ] ];
# [ 10, 7, "bob", true, [ "inner", 5 ] ]
# List index runs from 1 to Size(v)
v[1];
# 10
v[0];
# error
v[5];
# [ "inner", 5 ]
v[6];
# error
# One can assign a value to an undefined element
v[6] := 100;
# Even if it's not after the last: a list may have undefined elements
v[10] := 1000;
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000 ]
# And one can check for defined values
IsBound(v[10]);
# true
IsBound(v[9]);
# false
# Size of the list
Size(v);
# 10
# Appending a list to the end of another
Append(v, [ 8, 9]);
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000, 8, 9 ]
# Adding an element at the end
Add(v, "added");
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000, 8, 9, "added" ] |
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.
| #Slate | Slate | [| a b |
a: 1 + 1 i.
b: Pi + 1.2 i.
print: a + b.
print: a * b.
print: a / b.
print: a reciprocal.
print: a conjugated.
print: a abs.
print: a negated.
]. |
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.
| #Smalltalk | Smalltalk | PackageLoader fileInPackage: 'Complex'.
|a b|
a := 1 + 1 i.
b := 3.14159 + 1.2 i.
(a + b) displayNl.
(a * b) displayNl.
(a / b) displayNl.
a reciprocal displayNl.
a conjugate displayNl.
a abs displayNl.
a real displayNl.
a imaginary displayNl.
a negated displayNl. |
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
| #zkl | zkl | class Rational{ // Weenie Rational class, can handle BigInts
fcn init(_a,_b){ var a=_a, b=_b; normalize(); }
fcn toString{
if(b==1) a.toString()
else "%d//%d".fmt(a,b)
}
var [proxy] isZero=fcn{ a==0 };
fcn normalize{ // divide a and b by gcd
g:= a.gcd(b);
a/=g; b/=g;
if(b<0){ a=-a; b=-b; } // denominator > 0
self
}
fcn abs { a=a.abs(); self }
fcn __opNegate{ a=-a; self } // -Rat
fcn __opAdd(n){
if(Rational.isChildOf(n)) self(a*n.b + b*n.a, b*n.b); // Rat + Rat
else self(b*n + a, b); // Rat + Int
}
fcn __opSub(n){ self(a*n.b - b*n.a, b*n.b) } // Rat - Rat
fcn __opMul(n){
if(Rational.isChildOf(n)) self(a*n.a, b*n.b); // Rat * Rat
else self(a*n, b); // Rat * Int
}
fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat
fcn __opEQ(r){ // Rat==Rat, Rat==n
if(Rational.isChildOf(r)) a==r.a and b=r.b;
else b==1 and a==r;
}
} |
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
| #OCaml | OCaml | # 0.0 ** 0.0;;
- : float = 1.
# Complex.pow Complex.zero Complex.zero;;
- : Complex.t = {Complex.re = nan; Complex.im = nan}
# #load "nums.cma";;
# open Num;;
# Int 0 **/ Int 0;;
- : Num.num = Int 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
| #Oforth | Oforth | 0 0 pow println |
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
| #Ol | Ol |
(print "0^0: " (expt 0 0))
(print "0.0^0: " (expt (inexact 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
| #Crystal | Crystal | CONTENT = {House: [""],
Nationality: %i[English Swedish Danish Norwegian German],
Colour: %i[Red Green White Blue Yellow],
Pet: %i[Dog Birds Cats Horse Zebra],
Drink: %i[Tea Coffee Milk Beer Water],
Smoke: %i[PallMall Dunhill BlueMaster Prince Blend]}
def adjacent?(n, i, g, e)
(0..3).any? { |x| (n[x] == i && g[x + 1] == e) || (n[x + 1] == i && g[x] == e) }
end
def leftof?(n, i, g, e)
(0..3).any? { |x| n[x] == i && g[x + 1] == e }
end
def coincident?(n, i, g, e)
n.each_index.any? { |x| n[x] == i && g[x] == e }
end
def solve_zebra_puzzle
CONTENT[:Nationality].each_permutation { |nation|
next unless nation.first == :Norwegian # 10
CONTENT[:Colour].each_permutation { |colour|
next unless leftof?(colour, :Green, colour, :White) # 5
next unless coincident?(nation, :English, colour, :Red) # 2
next unless adjacent?(nation, :Norwegian, colour, :Blue) # 15
CONTENT[:Pet].each_permutation { |pet|
next unless coincident?(nation, :Swedish, pet, :Dog) # 3
CONTENT[:Drink].each_permutation { |drink|
next unless drink[2] == :Milk # 9
next unless coincident?(nation, :Danish, drink, :Tea) # 4
next unless coincident?(colour, :Green, drink, :Coffee) # 6
CONTENT[:Smoke].each_permutation { |smoke|
next unless coincident?(smoke, :PallMall, pet, :Birds) # 7
next unless coincident?(smoke, :Dunhill, colour, :Yellow) # 8
next unless coincident?(smoke, :BlueMaster, drink, :Beer) # 13
next unless coincident?(smoke, :Prince, nation, :German) # 14
next unless adjacent?(smoke, :Blend, pet, :Cats) # 11
next unless adjacent?(smoke, :Blend, drink, :Water) # 16
next unless adjacent?(smoke, :Dunhill, pet, :Horse) # 12
print_out(nation, colour, pet, drink, smoke)
}
}
}
}
}
end
def print_out(nation, colour, pet, drink, smoke)
width = CONTENT.map { |k, v| {k.to_s.size, v.max_of { |y| y.to_s.size }}.max }
fmt = width.map { |w| "%-#{w}s" }.join(" ")
national = nation[pet.index(:Zebra).not_nil!]
puts "The Zebra is owned by the man who is #{national}", ""
puts fmt % CONTENT.keys, fmt % width.map { |w| "-" * w }
[nation, colour, pet, drink, smoke].transpose.each.with_index(1) { |x, n| puts fmt % ([n] + x) }
end
solve_zebra_puzzle |
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>
| #Common_Lisp | Common Lisp | (dolist (system '(:xpath :cxml-stp :cxml))
(asdf:oos 'asdf:load-op system))
(defparameter *doc* (cxml:parse-file "xml" (stp:make-builder)))
(xpath:first-node (xpath:evaluate "/inventory/section[1]/item[1]" *doc*))
(xpath:do-node-set (node (xpath:evaluate "/inventory/section/item/price/text()" *doc*))
(format t "~A~%" (stp:data node)))
(defun node-array (node-set)
(coerce (xpath:all-nodes node-set) 'vector))
(node-array
(xpath:evaluate "/inventory/section/item/name" *doc*)) |
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>
| #D | D | import kxml.xml;
char[]xmlinput =
"<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>
";
void main() {
auto root = readDocument(xmlinput);
auto firstitem = root.parseXPath("inventory/section/item")[0];
foreach(price;root.parseXPath("inventory/section/item/price")) {
std.stdio.writefln("%s",price.getCData);
}
auto namearray = root.parseXPath("inventory/section/item/name");
} |
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.
| #C.23 | C# |
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Paint += Form1_Paint;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
DrawTaijitu(g, new Point(50, 50), 200, true);
DrawTaijitu(g, new Point(10, 10), 60, true);
}
private void DrawTaijitu(Graphics g, Point pt, int width, bool hasOutline)
{
g.FillPie(Brushes.Black, pt.X, pt.Y, width, width, 90, 180);
g.FillPie(Brushes.White, pt.X, pt.Y, width, width, 270, 180);
float headSize = Convert.ToSingle(width * 0.5);
float headXPosition = Convert.ToSingle(pt.X + (width * 0.25));
g.FillEllipse(Brushes.Black, headXPosition, Convert.ToSingle(pt.Y), headSize, headSize);
g.FillEllipse(Brushes.White, headXPosition, Convert.ToSingle(pt.Y + (width * 0.5)), headSize, headSize);
float headBlobSize = Convert.ToSingle(width * 0.125);
float headBlobXPosition = Convert.ToSingle(pt.X + (width * 0.4375));
g.FillEllipse(Brushes.White, headBlobXPosition, Convert.ToSingle(pt.Y + (width * 0.1875)), headBlobSize, headBlobSize);
g.FillEllipse(Brushes.Black, headBlobXPosition, Convert.ToSingle(pt.Y + (width * 0.6875)), headBlobSize, headBlobSize);
if (hasOutline) g.DrawEllipse(Pens.Black, pt.X, pt.Y, width, width);
}
} |
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
| #Chapel | Chapel | proc fixz(f) {
record InnerFunc {
const xi;
proc this(a) { return xi(xi)(a); }
}
record XFunc {
const fi;
proc this(x) { return fi(new InnerFunc(x)); }
}
const g = new XFunc(f);
return g(g);
}
record Facz {
record FacFunc {
const fi;
proc this(n: int): int {
return if n <= 1 then 1 else n * fi(n - 1); }
}
proc this(f) { return new FacFunc(f); }
}
record Fibz {
record FibFunc {
const fi;
proc this(n: int): int {
return if n <= 1 then n else fi(n - 2) + fi(n - 1); }
}
proc this(f) { return new FibFunc(f); }
}
const facz = fixz(new Facz());
const fibz = fixz(new Fibz());
writeln(facz(10));
writeln(fibz(10)); |
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
| #C.2B.2B | C++ | #include <vector>
#include <memory> // for auto_ptr
#include <cmath> // for the log10 and floor functions
#include <iostream>
#include <iomanip> // for the setw function
using namespace std;
typedef vector< int > IntRow;
typedef vector< IntRow > IntTable;
auto_ptr< IntTable > getZigZagArray( int dimension )
{
auto_ptr< IntTable > zigZagArrayPtr( new IntTable(
dimension, IntRow( dimension ) ) );
// fill along diagonal stripes (oriented as "/")
int lastValue = dimension * dimension - 1;
int currNum = 0;
int currDiag = 0;
int loopFrom;
int loopTo;
int i;
int row;
int col;
do
{
if ( currDiag < dimension ) // if doing the upper-left triangular half
{
loopFrom = 0;
loopTo = currDiag;
}
else // doing the bottom-right triangular half
{
loopFrom = currDiag - dimension + 1;
loopTo = dimension - 1;
}
for ( i = loopFrom; i <= loopTo; i++ )
{
if ( currDiag % 2 == 0 ) // want to fill upwards
{
row = loopTo - i + loopFrom;
col = i;
}
else // want to fill downwards
{
row = i;
col = loopTo - i + loopFrom;
}
( *zigZagArrayPtr )[ row ][ col ] = currNum++;
}
currDiag++;
}
while ( currDiag <= lastValue );
return zigZagArrayPtr;
}
void printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr )
{
size_t dimension = zigZagArrayPtr->size();
int fieldWidth = static_cast< int >( floor( log10(
static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;
size_t col;
for ( size_t row = 0; row < dimension; row++ )
{
for ( col = 0; col < dimension; col++ )
cout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ];
cout << endl;
}
}
int main()
{
printZigZagArray( getZigZagArray( 5 ) );
} |
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].
| #PureBasic | PureBasic | Procedure.i gcd(x.i,y.i)
While y<>0 : t=x : x=y : y=t%y : Wend : ProcedureReturn x
EndProcedure
If OpenConsole()
Dim Y.i(100)
For i=1 To 100
If i<=3 : Y(i)=i : Continue : EndIf : k=3
Repeat
RepLoop:
k+1
For j=1 To i-1 : If Y(j)=k : Goto RepLoop : EndIf : Next
If gcd(k,Y(i-2))=1 Or gcd(k,Y(i-1))>1 : Continue : EndIf
Y(i)=k : Break
ForEver
Next
For i=1 To 30 : Print(Str(Y(i))+" ") : Next : Input()
EndIf |
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].
| #Python | Python | '''Yellowstone permutation OEIS A098550'''
from itertools import chain, count, islice
from operator import itemgetter
from math import gcd
from matplotlib import pyplot
# yellowstone :: [Int]
def yellowstone():
'''A non-finite stream of terms from
the Yellowstone permutation.
OEIS A098550.
'''
# relativelyPrime :: Int -> Int -> Bool
def relativelyPrime(a):
return lambda b: 1 == gcd(a, b)
# nextWindow :: (Int, Int, [Int]) -> (Int, Int, [Int])
def nextWindow(triple):
p2, p1, rest = triple
[rp2, rp1] = map(relativelyPrime, [p2, p1])
# match :: [Int] -> (Int, [Int])
def match(xxs):
x, xs = uncons(xxs)['Just']
return (x, xs) if rp1(x) and not rp2(x) else (
second(cons(x))(
match(xs)
)
)
n, residue = match(rest)
return (p1, n, residue)
return chain(
range(1, 3),
map(
itemgetter(1),
iterate(nextWindow)(
(2, 3, count(4))
)
)
)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Terms of the Yellowstone permutation.'''
print(showList(
take(30)(yellowstone())
))
pyplot.plot(
take(100)(yellowstone())
)
pyplot.xlabel(main.__doc__)
pyplot.show()
# GENERIC -------------------------------------------------
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.
Wrapper containing the result of a computation.
'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.
Empty wrapper returned where a computation is not possible.
'''
return {'type': 'Maybe', 'Nothing': True}
# cons :: a -> [a] -> [a]
def cons(x):
'''Construction of a list from x as head,
and xs as tail.
'''
return lambda xs: [x] + xs if (
isinstance(xs, list)
) else x + xs if (
isinstance(xs, str)
) else chain([x], xs)
# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
'''An infinite list of repeated
applications of f to x.
'''
def go(x):
v = x
while True:
yield v
v = f(v)
return go
# second :: (a -> b) -> ((c, a) -> (c, b))
def second(f):
'''A simple function lifted to a function over a tuple,
with f applied only to the second of two values.
'''
return lambda xy: (xy[0], f(xy[1]))
# showList :: [a] -> String
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(repr(x) for x in xs) + ']'
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
return lambda xs: (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
# uncons :: [a] -> Maybe (a, [a])
def uncons(xs):
'''The deconstruction of a non-empty list
(or generator stream) into two parts:
a head value, and the remaining values.
'''
if isinstance(xs, list):
return Just((xs[0], xs[1:])) if xs else Nothing()
else:
nxt = take(1)(xs)
return Just((nxt[0], xs)) if nxt else Nothing()
# MAIN ---
if __name__ == '__main__':
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.
| #Python | Python | import urllib
import re
def fix(x):
p = re.compile(r'<[^<]*?>')
return p.sub('', x).replace('&', '&')
class YahooSearch:
def __init__(self, query, page=1):
self.query = query
self.page = page
self.url = "http://search.yahoo.com/search?p=%s&b=%s" %(self.query, ((self.page - 1) * 10 + 1))
self.content = urllib.urlopen(self.url).read()
def getresults(self):
self.results = []
for i in re.findall('<a class="yschttl spt" href=".+?">(.+?)</a></h3></div>(.+?)</div>.*?<span class=url>(.+?)</span>', self.content):
title = fix(i[0])
content = fix(i[1])
url = fix(i[2])
self.results.append(YahooResult(title, content, url))
return self.results
def getnextpage(self):
return YahooSearch(self.query, self.page+1)
search_results = property(fget=getresults)
nextpage = property(fget=getnextpage)
class YahooResult:
def __init__(self,title,content,url):
self.title = title
self.content = content
self.url = url
# Usage:
x = YahooSearch("test")
for result in x.search_results:
print result.title |
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
| #Lasso | Lasso | define integer->pow(factor::integer) => {
#factor <= 0
? return 0
local(retVal) = 1
loop(#factor) => { #retVal *= self }
return #retVal
}
local(bigint) = string(5->pow(4->pow(3->pow(2))))
#bigint->sub(1,20) + ` ... ` + #bigint->sub(#bigint->size - 19)
"\n"
`Number of digits: ` + #bigint->size |
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
| #Liberty_BASIC | Liberty BASIC | a$ = str$( 5^(4^(3^2)))
print len( a$)
print left$( a$, 20); "......"; right$( a$, 20) |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | zeckendorf[0] = 0;
zeckendorf[n_Integer] :=
10^(# - 1) + zeckendorf[n - Fibonacci[# + 1]] &@
LengthWhile[
Fibonacci /@
Range[2, Ceiling@Log[GoldenRatio, n Sqrt@5]], # <= n &];
zeckendorf /@ Range[0, 20] |
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
| #Nim | Nim | import strformat, strutils
proc z(n: Natural): string =
if n == 0: return "0"
var fib = @[2,1]
var n = n
while fib[0] < n: fib.insert(fib[0] + fib[1])
for f in fib:
if f <= n:
result.add '1'
dec n, f
else:
result.add '0'
if result[0] == '0':
result = result[1..result.high]
for i in 0 .. 20:
echo &"{i:>3} {z(i):>8}" |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Comal | Comal | 0010 DIM doors#(100)
0020 FOR pass#:=1 TO 100 DO
0030 FOR door#:=pass# TO 100 STEP pass# DO doors#(door#):=NOT doors#(door#)
0040 ENDFOR pass#
0050 FOR door#:=1 TO 100 DO
0060 IF doors#(door#) THEN PRINT "Door ",door#," is open."
0070 ENDFOR door#
0080 END |
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)
| #Genie | Genie | [indent=4]
/*
Arrays, in Genie
valac --pkg=gee-0.8 arrays.gs
./arrays
*/
uses
Gee
init
/* allocate a fixed array */
var arr = new array of int[10]
/* initialized array of strings */
initialized:array of string = {"This", "is", "Genie"}
/* length is an array property */
stdout.printf("%d\n", arr.length)
/* read/write access via index */
arr[1] = 1
arr[9] = arr[1] + 8
stdout.printf("%d\n", arr[9])
print initialized[2]
/* Dynamic arrays are lists in Genie */
var dyn = new list of int
dyn.add(1)
dyn.add(8)
dyn.add(dyn[0]+dyn[1])
stdout.printf("dyn size: %d\n", dyn.size)
stdout.printf("dyn[2] : %d\n", dyn[2]) |
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.
| #smart_BASIC | smart BASIC | ' complex numbers are native for "smart BASIC"
A=1+2i
B=3-5i
' all math operations and functions work with complex numbers
C=A*B
PRINT SQR(-4)
' example of solving quadratic equation with complex roots
' x^2+2x+5=0
a=1 ! b=2 ! c=5
x1=(-b+SQR(b^2-4*a*c))/(2*a)
x2=(-b-SQR(b^2-4*a*c))/(2*a)
PRINT x1,x2
' gives output
-1+2i -1-2i |
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
| #ooRexx | ooRexx | /**********************************************************************
* 21.04.2014 Walter Pachl
**********************************************************************/
Say 'rxCalcpower(0,0) ->' rxCalcpower(0,0)
Say '0**0 ->' 0**0
::requires rxmath library |
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
| #Openscad | Openscad | echo (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
| #PARI.2FGP | PARI/GP | 0^0
0.^0
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
| #Curry | Curry | import Constraint (allC, anyC)
import Findall (findall)
data House = H Color Man Pet Drink Smoke
data Color = Red | Green | Blue | Yellow | White
data Man = Eng | Swe | Dan | Nor | Ger
data Pet = Dog | Birds | Cats | Horse | Zebra
data Drink = Coffee | Tea | Milk | Beer | Water
data Smoke = PM | DH | Blend | BM | Prince
houses :: [House] -> Success
houses hs@[H1,_,H3,_,_] = -- 1
H _ _ _ Milk _ =:= H3 -- 9
& H _ Nor _ _ _ =:= H1 -- 10
& allC (`member` hs)
[ H Red Eng _ _ _ -- 2
, H _ Swe Dog _ _ -- 3
, H _ Dan _ Tea _ -- 4
, H Green _ _ Coffee _ -- 6
, H _ _ Birds _ PM -- 7
, H Yellow _ _ _ DH -- 8
, H _ _ _ Beer BM -- 13
, H _ Ger _ _ Prince -- 14
]
& H Green _ _ _ _ `leftTo` H White _ _ _ _ -- 5
& H _ _ _ _ Blend `nextTo` H _ _ Cats _ _ -- 11
& H _ _ Horse _ _ `nextTo` H _ _ _ _ DH -- 12
& H _ Nor _ _ _ `nextTo` H Blue _ _ _ _ -- 15
& H _ _ _ Water _ `nextTo` H _ _ _ _ Blend -- 16
where
x `leftTo` y = _ ++ [x,y] ++ _ =:= hs
x `nextTo` y = x `leftTo` y
? y `leftTo` x
member :: a -> [a] -> Success
member = anyC . (=:=)
main = findall $ \(hs,who) -> houses hs & H _ who Zebra _ _ `member` hs |
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>
| #Delphi | Delphi | program XMLXPath;
{$APPTYPE CONSOLE}
uses ActiveX, MSXML;
const
XML =
'<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>';
var
i: Integer;
s: string;
lXMLDoc: IXMLDOMDocument2;
lNodeList: IXMLDOMNodeList;
lNode: IXMLDOMNode;
lItemNames: array of string;
begin
CoInitialize(nil);
lXMLDoc := CoDOMDocument.Create;
lXMLDoc.setProperty('SelectionLanguage', 'XPath');
lXMLDoc.loadXML(XML);
Writeln('First item node:');
lNode := lXMLDoc.selectNodes('//item')[0];
Writeln(lNode.xml);
Writeln('');
lNodeList := lXMLDoc.selectNodes('//price');
for i := 0 to lNodeList.length - 1 do
Writeln('Price = ' + lNodeList[i].text);
Writeln('');
lNodeList := lXMLDoc.selectNodes('//item/name');
SetLength(lItemNames, lNodeList.length);
for i := 0 to lNodeList.length - 1 do
lItemNames[i] := lNodeList[i].text;
for s in lItemNames do
Writeln('Item name = ' + s);
end. |
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.
| #CLU | CLU | taijitu = cluster is make
rep = null
circle = proc (x,y,c,r: int) returns (bool)
return (r**2 >= (x/2)**2 + (y-c)**2)
end circle
pixel = proc (x,y,r: int) returns (char)
if circle(x,y,-r/2,r/6) then return('#')
elseif circle(x,y, r/2,r/6) then return('.')
elseif circle(x,y,-r/2,r/2) then return('.')
elseif circle(x,y, r/2,r/2) then return('#')
elseif circle(x,y, 0, r) then
if x<0 then return('.') else return('#') end
end
return(' ')
end pixel
make = proc (r: int) returns (string)
chars: array[char] := array[char]$predict(1, r*r*2+r)
for y: int in int$from_to(-r, r) do
for x: int in int$from_to(-2*r, 2*r) do
array[char]$addh(chars, pixel(x,y,r))
end
array[char]$addh(chars, '\n')
end
return (string$ac2s(chars))
end make
end taijitu
start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, taijitu$make(4))
stream$putl(po, taijitu$make(8))
end start_up |
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.
| #D | D | import std.stdio, std.algorithm, std.array, std.math, std.range,
std.conv, std.typecons;
string yinYang(in int n) pure /*nothrow @safe*/ {
enum : char { empty = ' ', white = '.', black = '#' }
const radii = [1, 3, 6].map!(i => i * n).array;
auto ranges = radii.map!(r => iota(-r, r + 1).array).array;
alias V = Tuple!(int,"x", int,"y");
V[][] squares, circles;
squares = ranges.map!(r => cartesianProduct(r, r).map!V.array).array;
foreach (sqrPoints, const radius; zip(squares, radii))
circles ~= sqrPoints.filter!(p => p[].hypot <= radius).array;
auto m = squares[$ - 1].zip(empty.repeat).assocArray;
foreach (immutable p; circles[$ - 1])
m[p] = black;
foreach (immutable p; circles[$ - 1])
if (p.x > 0)
m[p] = white;
foreach (immutable p; circles[$ - 2]) {
m[V(p.x, p.y + 3 * n)] = black;
m[V(p.x, p.y - 3 * n)] = white;
}
foreach (immutable p; circles[$ - 3]) {
m[V(p.x, p.y + 3 * n)] = white;
m[V(p.x, p.y - 3 * n)] = black;
}
return ranges[$ - 1]
.map!(y => ranges[$ - 1].retro.map!(x => m[V(x, y)]).text)
.join('\n');
}
void main() {
2.yinYang.writeln;
1.yinYang.writeln;
} |
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
| #Clojure | Clojure | (defn Y [f]
((fn [x] (x x))
(fn [x]
(f (fn [& args]
(apply (x x) args))))))
(def fac
(fn [f]
(fn [n]
(if (zero? n) 1 (* n (f (dec n)))))))
(def fib
(fn [f]
(fn [n]
(condp = n
0 0
1 1
(+ (f (dec n))
(f (dec (dec n)))))))) |
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
| #Ceylon | Ceylon | class ZigZag(Integer size) {
value data = Array {
for (i in 0:size)
Array.ofSize(size, 0)
};
variable value i = 1;
variable value j = 1;
for (element in 0 : size^2) {
data[j - 1]?.set(i - 1, element);
if ((i + j).even) {
if (j < size) {
j++;
}
else {
i += 2;
}
if (i > 1) {
i--;
}
}
else {
if (i < size) {
i++;
}
else {
j += 2;
}
if (j > 1) {
j--;
}
}
}
shared void display() {
for (row in data) {
for (element in row) {
process.write(element.string.pad(3));
}
print(""); //newline
}
}
}
shared void run() {
value zz = ZigZag(5);
zz.display();
} |
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
| #Clojure | Clojure | (defn partitions [sizes coll]
(lazy-seq
(when-let [n (first sizes)]
(when-let [s (seq coll)]
(cons (take n coll)
(partitions (next sizes) (drop n coll)))))))
(defn take-from [n colls]
(lazy-seq
(when-let [s (seq colls)]
(let [[first-n rest-n] (split-at n s)]
(cons (map first first-n)
(take-from n (concat (filter seq (map rest first-n)) rest-n)))))))
(defn zig-zag [n]
(->> (partitions (concat (range 1 (inc n)) (range (dec n) 0 -1)) (range (* n n)))
(map #(%1 %2) (cycle [reverse identity]) ,)
(take-from n ,)))
user> (zig-zag 5)
(( 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))
user> (zig-zag 6)
(( 0 1 5 6 14 15)
( 2 4 7 13 16 25)
( 3 8 12 17 24 26)
( 9 11 18 23 27 32)
(10 19 22 28 31 33)
(20 21 29 30 34 35)) |
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].
| #Quackery | Quackery | [ stack ] is seqbits ( --> s )
[ bit
seqbits take |
seqbits put ] is seqadd ( n --> )
[ bit
seqbits share & not ] is notinseq ( n --> b )
[ temp put
' [ 1 2 3 ]
7 seqbits put
4
[ dip
[ dup -1 peek
over -2 peek ]
dup dip
[ tuck gcd 1 !=
unrot gcd 1 =
and ]
swap if
[ dup dip join
seqadd
3 ]
[ 1+
dup notinseq until ]
over size temp share
< not until ]
drop
seqbits release
temp take split drop ] is yellowstones ( n --> [ )
30 yellowstones echo |
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].
| #Racket | Racket | #lang racket
(require plot)
(define a098550
(let ((hsh# (make-hash '((1 . 1) (2 . 2) (3 . 3))))
(rev# (make-hash '((1 . 1) (2 . 2) (3 . 3)))))
(λ (n)
(hash-ref hsh# n
(λ ()
(let ((a_n (for/first ((i (in-naturals 4))
#:unless (hash-has-key? rev# i)
#:when (and (= (gcd i (a098550 (- n 1))) 1)
(> (gcd i (a098550 (- n 2))) 1)))
i)))
(hash-set! hsh# n a_n)
(hash-set! rev# a_n n)
a_n))))))
(map a098550 (range 1 (add1 30)))
(plot (points
(map (λ (i) (vector i (a098550 i))) (range 1 (add1 100))))) |
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].
| #Raku | Raku | my @yellowstone = 1, 2, 3, -> $q, $p {
state @used = True xx 4;
state $min = 3;
my \index = ($min .. *).first: { not @used[$_] and $_ gcd $q != 1 and $_ gcd $p == 1 };
@used[index] = True;
$min = @used.first(!*, :k) // +@used - 1;
index
} … *;
put "The first 30 terms in the Yellowstone sequence:\n", @yellowstone[^30];
use SVG;
use SVG::Plot;
my @x = ^500;
my $chart = SVG::Plot.new(
background => 'white',
width => 1000,
height => 600,
plot-width => 950,
plot-height => 550,
x => @x,
x-tick-step => { 10 },
y-tick-step => { 50 },
min-y-axis => 0,
values => [@yellowstone[@x],],
title => "Yellowstone Sequence - First {+@x} values (zero indexed)",
);
my $line = './Yellowstone-sequence-line-perl6.svg'.IO;
my $bars = './Yellowstone-sequence-bars-perl6.svg'.IO;
$line.spurt: SVG.serialize: $chart.plot: :lines;
$bars.spurt: SVG.serialize: $chart.plot: :bars; |
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.
| #R | R | YahooSearch <- function(query, page=1, .opts=list(), ignoreMarkUpErrors=TRUE)
{
if(!require(RCurl) || !require(XML))
{
stop("Could not load required packages")
}
# Replace " " with "%20", etc
query <- curlEscape(query)
# Retrieve page
b <- 10*(page-1)+1
theurl <- paste("http://uk.search.yahoo.com/search?p=",
query, "&b=", b, sep="")
webpage <- getURL(theurl, .opts=.opts)
# Save search for nextpage function
.Search <- list(query=query, page=page, .opts=.opts,
ignoreMarkUpErrors=ignoreMarkUpErrors)
assign(".Search", .Search, envir=globalenv())
# Parse HTML; retrieve results block
webpage <- readLines(tc <- textConnection(webpage)); close(tc)
if(ignoreMarkUpErrors)
{
pagetree <- htmlTreeParse(webpage, error=function(...){})
} else
{
pagetree <- htmlTreeParse(webpage)
}
findbyattr <- function(x, id, type="id")
{
ids <- sapply(x, function(x) x$attributes[type])
x[ids==id]
}
body <- pagetree$children$html$children$body
bd <- findbyattr(body$children$div$children, "bd")
left <- findbyattr(bd$div$children$div$children, "left")
web <- findbyattr(left$div$children$div$children, "web")
resol <- web$div$children$ol
#Get url, title, content from results
gettextfromnode <- function(x)
{
un <- unlist(x$children)
paste(un[grep("value", names(un))], collapse=" ")
}
n <- length(resol)
results <- list()
length(results) <- n
for(i in 1:n)
{
mainlink <- resol[[i]]$children$div$children[1]$div$children$h3$children$a
url <- mainlink$attributes["href"]
title <- gettextfromnode(mainlink)
contenttext <- findbyattr(resol[[i]]$children$div$children[2], "abstr", type="class")
if(length(contenttext)==0)
{
contenttext <- findbyattr(resol[[i]]$children$div$children[2]$div$children$div$children,
"sm-abs", type="class")
}
content <- gettextfromnode(contenttext$div)
results[[i]] <- list(url=url, title=title, content=content)
}
names(results) <- as.character(seq(b, b+n-1))
results
}
nextpage <- function()
{
if(exists(".Search", envir=globalenv()))
{
.Search <- get(".Search", envir=globalenv())
.Search$page <- .Search$page + 1L
do.call(YahooSearch, .Search)
} else
{
message("No search has been performed yet")
}
}
#Usage
YahooSearch("rosetta code")
nextpage() |
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.
| #Racket | Racket | #lang racket
(require net/url)
(define *yaho-url* "http://search.yahoo.com/search?p=~a&b=~a")
(define *current-page* 0)
(define *current-query* "")
(define request (compose port->string get-pure-port string->url))
;;strip html tags
(define (remove-tags text)
(regexp-replace* #px"<[^<]+?>" text ""))
;;search, parse and print
(define (search-yahoo query)
(unless (string=? *current-query* query) ;different query, go back to page 1
(set! *current-query* query)
(set! *current-page* 0))
(let* ([current-page (number->string (add1 (* 10 *current-page*)))]
[html (request (format *yaho-url* query current-page))]
[results (regexp-match* #px"lass=\"yschttl spt\" href=\".+?\">(.+?)<span class=url>(.+?)</span>.+?<div class=\"abstr\">(.+?)</div>" html #:match-select cdr)])
(for ([result (in-list results)])
(printf "Title: ~a \n Link: ~a \n Text: ~a \n\n"
(remove-tags (first result))
(remove-tags (second result) )
(remove-tags (third result))))))
;;search nexxt page
(define (next-page)
(set! *current-page* (add1 *current-page*))
(search-yahoo *current-query*)) |
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
| #Lua | Lua | bc = require("bc")
-- since 5$=5^4$, and IEEE754 can handle 4$, this would be sufficient:
-- n = bc.pow(bc.new(5), bc.new(4^3^2))
-- but for this task:
n = bc.pow(bc.new(5), bc.pow(bc.new(4), bc.pow(bc.new(3), bc.new(2))))
s = n:tostring()
print(string.format("%s...%s (%d digits)", s:sub(1,20), s:sub(-20,-1), #s)) |
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
| #Maple | Maple |
> n := 5^(4^(3^2)):
> length( n ); # number of digits
183231
> s := convert( n, 'string' ):
> s[ 1 .. 20 ], s[ -20 .. -1 ]; # extract first and last twenty digits
"62060698786608744707", "92256259918212890625"
|
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
| #PARI.2FGP | PARI/GP | Z(n)=if(!n,print1(0));my(k=2);while(fibonacci(k)<=n,k++); forstep(i=k-1,2,-1,print1(if(fibonacci(i)<=n,n-=fibonacci(i);1,0)));print
for(n=0,20,Z(n)) |
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.
| #Commodore_BASIC_2 | Commodore BASIC |
10 D=100: DIMD(D): P=1
20 PRINT CHR$(147);"PASS: ";P
22 FOR I=P TO D STEP P: D(I)=NOTD(I): NEXT
30 IF P=100 THEN 40
32 P=P+1: GOTO20
40 PRINT: PRINT"THE FOLLOWING DOORS ARE OPEN: "
42 FOR I=1 TO D: IF D(I)=-1 THEN PRINTI;
44 NEXT
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #GML | GML | array[0] = ' '
array[1] = 'A'
array[2] = 'B'
array[3] = 'C' |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.