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/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Python | Python | from turtle import *
def dragon(step, length):
dcr(step, length)
def dcr(step, length):
step -= 1
length /= 1.41421
if step > 0:
right(45)
dcr(step, length)
left(90)
dcl(step, length)
right(45)
else:
right(45)
forward(length)
left(90)
forward(length)
right(45)
def dcl(step, length):
step -= 1
length /= 1.41421
if step > 0:
left(45)
dcr(step, length)
right(90)
dcl(step, length)
left(45)
else:
left(45)
forward(length)
right(90)
forward(length)
left(45) |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Phix | Phix | with javascript_semantics
function linear_combination(sequence f)
string res = ""
for e=1 to length(f) do
integer fe = f[e]
if fe!=0 then
if fe=1 then
if length(res) then res &= "+" end if
elsif fe=-1 then
res &= "-"
elsif fe>0 and length(res) then
res &= sprintf("+%d*",fe)
else
res &= sprintf("%d*",fe)
end if
res &= sprintf("e(%d)",e)
end if
end for
if res="" then res = "0" end if
return res
end function
constant tests = {{1,2,3},
{0,1,2,3},
{1,0,3,4},
{1,2,0},
{0,0,0},
{0},
{1,1,1},
{-1,-1,-1},
{-1,-2,0,-3},
{-1}}
for i=1 to length(tests) do
sequence ti = tests[i]
printf(1,"%12s -> %s\n",{sprint(ti), linear_combination(ti)})
end for
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Retro | Retro |
# Determine The Average Word Name Length
To determine the average length of a word name two values
are needed. First, the total length of all names in the
Dictionary:
~~~
#0 [ d:name s:length + ] d:for-each
~~~
And then the number of words in the Dictionary:
~~~
#0 [ drop n:inc ] d:for-each
~~~
With these, a simple division is all that's left.
~~~
/
~~~
Finally, display the results:
~~~
'Average_name_length:_%n\n s:format s:put
~~~
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #REXX | REXX | /*REXX program illustrates how to display embedded documentation (help) within REXX code*/
parse arg doc /*obtain (all) the arguments from C.L. */
if doc='?' then call help /*show documentation if arg=a single ? */
/*■■■■■■■■■regular■■■■■■■■■■■■■■■■■■■■■■■■■*/
/*■■■■■■■■■■■■■■■■■mainline■■■■■■■■■■■■■■■■*/
/*■■■■■■■■■■■■■■■■■■■■■■■■■■code■■■■■■■■■■■*/
/*■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■here.■■■■■*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
help: ?=0; do j=1 for sourceline(); _=sourceline(j) /*get a line of source.*/
if _='<help>' then do; ?=1; iterate; end /*search for <help> */
if _='</help>' then leave /* " " </help> */
if ? then say _
end /*j*/
exit /*stick a fork in it, we're all done. */
/*══════════════════════════════════start of the in═line documentation AFTER the <help>
<help>
To use the YYYY program, enter one of:
YYYY numberOfItems
YYYY (no arguments uses the default)
YYYY ? (to see this documentation)
─── where: numberOfItems is the number of items to be used.
If no "numberOfItems" are entered, the default of 100 is used.
</help>
════════════════════════════════════end of the in═line documentation BEFORE the </help> */ |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Ring | Ring |
/*
Multiply two numbers
n1: an integer.
n2: an integer.
returns product of n1 and n2
*/
see mult(3, 5) + nl
func mult n1, n2
return n1*n2
|
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #R | R | diversityStats <- function(trueValue, estimates)
{
collectivePrediction <- mean(estimates)
data.frame("True Value" = trueValue,
as.list(setNames(estimates, paste("Guess", seq_along(estimates)))), #Guesses, each with a title and column.
"Average Error" = mean((trueValue - estimates)^2),
"Crowd Error" = (trueValue - collectivePrediction)^2,
"Prediction Diversity" = mean((estimates - collectivePrediction)^2))
}
diversityStats(49, c(48, 47, 51))
diversityStats(49, c(48, 47, 51, 42)) |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Racket | Racket | #lang racket
(define (mean l)
(/ (apply + l) (length l)))
(define (diversity-theorem truth predictions)
(define μ (mean predictions))
(define (avg-sq-diff a)
(mean (map (λ (p) (sqr (- p a))) predictions)))
(hash 'average-error (avg-sq-diff truth)
'crowd-error (sqr (- truth μ))
'diversity (avg-sq-diff μ)))
(println (diversity-theorem 49 '(48 47 51)))
(println (diversity-theorem 49 '(48 47 51 42))) |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Action.21 | Action! | INT FUNC DotProduct(INT ARRAY v1,v2 BYTE len)
BYTE i,res
res=0
FOR i=0 TO len-1
DO
res==+v1(i)*v2(i)
OD
RETURN (res)
PROC PrintVector(INT ARRAY a BYTE size)
BYTE i
Put('[)
FOR i=0 TO size-1
DO
PrintI(a(i))
IF i<size-1 THEN
Put(',)
FI
OD
Put('])
RETURN
PROC Test(INT ARRAY v1,v2 BYTE len)
INT res
res=DotProduct(v1,v2,len)
PrintVector(v1,len)
Put('.)
PrintVector(v2,len)
Put('=)
PrintIE(res)
RETURN
PROC Main()
INT ARRAY
v1=[1 3 65531],
v2=[4 65534 65535]
Test(v1,v2,3)
RETURN |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Delphi | Delphi |
program Doubly_linked;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
boost.LinkedList;
var
List: TLinkedList<string>;
Head, Tail,Current: TLinkedListNode<string>;
Value:string;
begin
List := TLinkedList<string>.Create;
List.AddFirst('.AddFirst() adds at the head.');
List.AddLast('.AddLast() adds at the tail.');
Head := List.Find('.AddFirst() adds at the head.');
List.AddAfter(Head, '.AddAfter() adds after a specified node.');
Tail := List.Find('.AddLast() adds at the tail.');
List.AddBefore(Tail, 'Betcha can''t guess what .AddBefore() does.');
Writeln('Forward:');
for value in List do
Writeln(value);
Writeln(#10'Backward:');
Current:= Tail;
while Assigned(Current) do
begin
Writeln(Current.Value);
Current:= Current.Prev;
end;
List.Free;
Readln;
end. |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[DisariumQ]
DisariumQ[n_Integer] := Module[{digs},
digs = IntegerDigits[n];
digs = digs^Range[Length[digs]];
Total[digs] == n
]
i = 0;
Reap[Do[
If[DisariumQ[n],
i++;
Sow[n]
];
If[i == 19, Break[]]
,
{n, 0, \[Infinity]}
]][[2, 1]] |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #Perl | Perl | use strict;
use warnings;
my ($n,@D) = (0, 0);
while (++$n) {
my($m,$sum);
map { $sum += $_ ** ++$m } split '', $n;
push @D, $n if $n == $sum;
last if 19 == @D;
}
print "@D\n"; |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #PowerShell | PowerShell | $DNS = Resolve-DnsName -Name www.kame.net
Write-Host "IPv4:" $DNS.IP4Address "`nIPv6:" $DNS.IP6Address |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Python | Python | >>> import socket
>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))
>>> for ip in ips: print ip
...
2001:200:dff:fff1:216:3eff:feb1:44d7
203.178.141.194 |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #R | R |
#include <Rcpp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace Rcpp ;
// [[Rcpp::export]]
CharacterVector getNameInfo(std::string fqdn) {
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);
if (error) { return(NA_STRING); }
int i = 0 ;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { i++ ; }
}
CharacterVector results(i) ;
i = 0;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { results[i++] = host ; }
}
freeaddrinfo(res0);
return(results) ;
}
|
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Quackery | Quackery | [ $ "turtleduck.qky" loadfile ] now!
[ 2 *
2dup turn
4 1 walk
turn ] is corner ( n/d --> )
forward is right ( n --> )
forward is left ( n --> )
[ dup 0 = iff
[ drop 8 1 walk ] done
1 - dup
left
1 4 corner
right ] resolves right ( n --> )
[ dup 0 = iff
[ drop 8 1 walk ] done
1 - dup
left
-1 4 corner
right ] resolves left ( n --> )
turtle
-260 1 fly
3 4 turn
100 1 fly
5 8 turn
11 left |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #PureBasic | PureBasic | ; Process and output values.
Procedure WriteLinear(Array c.i(1))
Define buf$,
i.i, j.i, b,i
b = #True
j = 0
For i = 0 To ArraySize(c(), 1)
If c(i) = 0 : Continue : EndIf
If c(i) < 0
If b : Print("-") : Else : Print(" - ") : EndIf
ElseIf c(i) > 0
If Not b : Print(" + ") : EndIf
EndIf
If c(i) > 1
Print(Str(c(i))+"*")
ElseIf c(i) < -1
Print(Str(-c(i))+"*")
EndIf
Print("e("+Str(i+1)+")")
b = #False
j+1
Next
If j = 0 : Print("0") : EndIf
PrintN("")
EndProcedure
Macro VectorHdl(Adr_Start, Adr_Stop)
; 1. Output of the input values
Define buf$ = "[", *adr_ptr
For *adr_ptr = Adr_Start To Adr_Stop - SizeOf(Integer) Step SizeOf(Integer)
buf$ + Str(PeekI(*adr_ptr))
If *adr_ptr >= Adr_Stop - SizeOf(Integer)
buf$ + "] -> "
Else
buf$ + ", "
EndIf
Next
buf$ = RSet(buf$, 25)
Print(buf$)
; 2. Reserve memory, pass and process values.
Dim a.i((Adr_Stop - Adr_Start) / SizeOf(Integer) -1)
CopyMemory(Adr_Start, @a(0), Adr_Stop - Adr_Start)
WriteLinear(a())
EndMacro
If OpenConsole("")
; Pass memory addresses of the data.
VectorHdl(?V1, ?_V1)
VectorHdl(?V2, ?_V2)
VectorHdl(?V3, ?_V3)
VectorHdl(?V4, ?_V4)
VectorHdl(?V5, ?_V5)
VectorHdl(?V6, ?_V6)
VectorHdl(?V7, ?_V7)
VectorHdl(?V8, ?_V8)
VectorHdl(?V9, ?_V9)
VectorHdl(?V10, ?_V10)
Input()
EndIf
End 0
DataSection
V1:
Data.i 1,2,3
_V1:
V2:
Data.i 0,1,2,3
_V2:
V3:
Data.i 1,0,3,4
_V3:
V4:
Data.i 1,2,0
_V4:
V5:
Data.i 0,0,0
_V5:
V6:
Data.i 0
_V6:
V7:
Data.i 1,1,1
_V7:
V8:
Data.i -1,-1,-1
_V8:
V9:
Data.i -1,-2,0,-3
_V9:
V10:
Data.i -1
_V10:
EndDataSection |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Ruby | Ruby | =begin rdoc
RDoc is documented here[http://www.ruby-doc.org/core/classes/RDoc.html].
This is a class documentation comment. This text shows at the top of the page
for the class.
Comments can be written inside "=begin rdoc"/"end" blocks or
in normal '#' comment blocks.
There are no '@parameters' like javadoc, but 'name-value' lists can be written:
Author:: Joe Schmoe
Date:: today
=end
class Doc
# This is a comment for a Constant
Constant = nil
# This is a method comment. Parameters and return values can be named
# with the "call-seq" directive.
#
# call-seq:
# a_method(first_arg, second_arg) -> return_value
#
def a_method(arg1, arg2='default value')
do_stuff
end
# Class methods will be shown in a separate section of the generated documentation.
def self.class_method
Constant
end
end
# :include:boilerplate.txt |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Rust | Rust | //! Documentation for the module
//!
//! **Lorem ipsum** dolor sit amet, consectetur adipiscing elit. Aenean a
//! sagittis sapien, eu pellentesque ex. Nulla facilisi. Praesent eget sapien
//! sollicitudin, laoreet ipsum at, fringilla augue. In hac habitasse platea
//! dictumst. Nunc in neque sed magna suscipit mattis sed quis mi. Curabitur
//! quis mi a ante mollis commodo. Sed tincidunt ut metus vel accumsan.
#![doc(html_favicon_url = "https://example.com/favicon.ico")]
#![doc(html_logo_url = "https://example.com/logo.png")]
/// Documentation for a constant
pub const THINGY: u32 = 42;
/// Documentation for a Rust `enum` (tagged union)
pub enum Whatsit {
/// Documentation for the `Yo` variant
Yo(Whatchamabob),
/// Documentation for the `HoHo` variant
HoHo,
}
/// Documentation for a data structure
pub struct Whatchamabob {
/// Doodads do dad
pub doodad: f64,
/// Whether or not this is a thingamabob
pub thingamabob: bool
}
/// Documentation for a trait (interface)
pub trait Frobnify {
/// `Frobnify` something
fn frob(&self);
}
/// Documentation specific to this struct's implementation of `Frobnify`
impl Frobnify for Whatchamabob {
/// `Frobnify` the `Whatchamabob`
fn frob(&self) {
println!("Frobbed: {}", self.doodad);
}
}
/// Documentation for a function
///
/// Pellentesque sodales lacus nisi, in malesuada lectus vestibulum eget.
/// Integer rhoncus imperdiet justo. Pellentesque egestas sem ac
/// consectetur suscipit. Maecenas tempus dignissim purus, eu tincidunt mi
/// tincidunt id. Morbi ac laoreet erat, eu ultricies neque. Fusce molestie
/// urna quis nisl condimentum, sit amet fringilla nunc ornare. Pellentesque
/// vestibulum ac nibh eu accumsan. In ornare orci at rhoncus finibus. Donec
/// sed ipsum ex. Pellentesque ante nisl, pharetra id purus auctor, euismod
/// semper erat. Nunc sit amet eros elit.
pub fn main() {
let foo = Whatchamabob{ doodad: 1.2, thingamabob: false };
foo.frob();
} |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Scala | Scala | /**
* This is a class documentation comment. This text shows at the top of the page for this class
*
* @author Joe Schmoe
*/
class Doc {
/**
* This is a field comment for a variable
*/
private val field = 0
/**
* This is a method comment. It has parameter tags (param) and a return value tag (return).
*
* @param num a number with the variable name "num"
* @return another number
*/
def method(num: Long): Int = {
//...code here
???
}
} |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Raku | Raku | sub diversity-calc($truth, @pred) {
my $ae = avg-error($truth, @pred); # average individual error
my $cp = ([+] @pred)/+@pred; # collective prediction
my $ce = ($cp - $truth)**2; # collective error
my $pd = avg-error($cp, @pred); # prediction diversity
return $ae, $ce, $pd;
}
sub avg-error ($m, @v) { ([+] (@v X- $m) X**2) / +@v }
sub diversity-format (@stats) {
gather {
for <average-error crowd-error diversity> Z @stats -> ($label,$value) {
take $label.fmt("%13s") ~ ':' ~ $value.fmt("%7.3f");
}
}
}
.say for diversity-format diversity-calc(49, <48 47 51>);
.say for diversity-format diversity-calc(49, <48 47 51 42>); |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #ActionScript | ActionScript | function dotProduct(v1:Vector.<Number>, v2:Vector.<Number>):Number
{
if(v1.length != v2.length) return NaN;
var sum:Number = 0;
for(var i:uint = 0; i < v1.length; i++)
sum += v1[i]*v2[i];
return sum;
}
trace(dotProduct(Vector.<Number>([1,3,-5]),Vector.<Number>([4,-2,-1]))); |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #E | E | def makeDLList() {
def firstINode
def lastINode
def makeNode(var value, var prevI, var nextI) {
# To meet the requirement that the client cannot create a loop, the
# inter-node refs are protected: clients only get the external facet
# with invariant-preserving operations.
def iNode
def node { # external facet
to get() { return value }
to put(new) { value := new }
/** Return the value of the element of the list at the specified offset
from this element. */
to get(index :int) {
if (index > 0 && node.hasNext()) {
return nextI.node().get(index - 1)
} else if (index < 0 && node.hasPrev()) {
return prevI.node().get(index + 1)
} else if (index <=> 0) {
return value
} else {
throw("index out of range in dlList")
}
}
to hasPrev() {
return prevI != firstINode && prevI != null
}
to prev() {
if (!node.hasPrev()) {
throw("there is no previous node")
}
return prevI.node()
}
to hasNext() {
return nextI != lastINode && nextI != null
}
to next() {
if (!node.hasNext()) {
throw("there is no next node")
}
return nextI.node()
}
to remove() {
if (prevI == null || nextI == null) { return }
prevI.setNextI(nextI)
nextI.setPrevI(prevI)
prevI := null
nextI := null
}
to insertAfter(newValue) {
def newI := makeNode(newValue, iNode, nextI)
nextI.setPrevI(newI)
nextI := newI
}
to insertBefore(newValue) {
prevI.node().insertAfter(newValue)
}
}
bind iNode { # internal facet
to node() { return node }
to nextI() { return nextI }
to prevI() { return prevI }
to setNextI(new) { nextI := new }
to setPrevI(new) { prevI := new }
}
return iNode
} # end makeNode
bind firstINode := makeNode(null, Ref.broken("no first prev"), lastINode)
bind lastINode := makeNode(null, firstINode, Ref.broken("no last next"))
def dlList {
to __printOn(out) {
out.print("<")
var sep := ""
for x in dlList {
out.print(sep)
out.quote(x)
sep := ", "
}
out.print(">")
}
to iterate(f) {
var n := firstINode
while (n.node().hasNext()) {
n := n.nextI()
f(n.node(), n.node()[])
}
}
to atFirst() { return firstINode.nextI().node() }
to atLast() { return lastINode.prevI().node() }
to insertFirst(new) { return firstINode.node().insertAfter(new) }
to push(new) { return lastINode.node().insertBefore(new) }
/** Return the node which has the specified value */
to nodeOf(value) {
for node => v ? (v == value) in dlList { return node }
}
}
return dlList
} |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #Phix | Phix | with javascript_semantics
constant limit = 19
integer count = 0, n = 0
printf(1,"The first 19 Disarium numbers are:\n")
while count<limit do
atom dsum = 0
string digits = sprintf("%d",n)
for i=1 to length(digits) do
dsum += power(digits[i]-'0',i)
end for
if dsum=n then
printf(1," %d",n)
count += 1
end if
n += 1
end while
|
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #Picat | Picat | main =>
Limit = 19,
D = [],
N = 0,
printf("The first %d Disarium numbers are:\n",Limit),
while (D.len < Limit)
if disarium_number(N) then
D := D ++ [N]
end,
N := N + 1,
if N mod 10_000_000 == 0 then
println(test=N)
end
end,
println(D).
disarium_number(N) =>
Sum = 0,
Digits = N.to_string.len,
X = N,
while (X != 0, Sum <= N)
Sum := Sum + (X mod 10) ** Digits,
Digits := Digits - 1,
X := X div 10
end,
Sum == N. |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Racket | Racket |
#lang racket
(require net/dns)
(dns-get-address "8.8.8.8" "www.kame.net")
|
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Raku | Raku | use Net::DNS;
my $resolver = Net::DNS.new('8.8.8.8');
my $ip4 = $resolver.lookup('A', 'orange.kame.net');
my $ip6 = $resolver.lookup('AAAA', 'orange.kame.net');
say $ip4[0].octets.join: '.';
say $ip6[0].octets.».fmt("%.2X").join.comb(4).join: ':'; |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #R | R |
Dragon<-function(Iters){
Rotation<-matrix(c(0,-1,1,0),ncol=2,byrow=T) ########Rotation multiplication matrix
Iteration<-list() ###################################Set up list for segment matrices for 1st
Iteration[[1]] <- matrix(rep(0,16), ncol = 4)
Iteration[[1]][1,]<-c(0,0,1,0)
Iteration[[1]][2,]<-c(1,0,1,-1)
Moveposition<-rep(0,Iters) ##########################Which point should be shifted to origin
Moveposition[1]<-4
if(Iters > 1){#########################################where to move to get to origin
for(l in 2:Iters){#####################################only if >1, because 1 set before for loop
Moveposition[l]<-(Moveposition[l-1]*2)-2#############sets vector of all positions in matrix where last point is
}}
Move<-list() ########################################vector to add to all points to shift start at origin
for (i in 1:Iters){
half<-dim(Iteration[[i]])[1]/2
half<-1:half
for(j in half){########################################Rotate all points 90 degrees clockwise
Iteration[[i]][j+length(half),]<-c(Iteration[[i]][j,1:2]%*%Rotation,Iteration[[i]][j,3:4]%*%Rotation)
}
Move[[i]]<-matrix(rep(0,4),ncol=4)
Move[[i]][1,1:2]<-Move[[i]][1,3:4]<-(Iteration[[i]][Moveposition[i],c(3,4)]*-1)
Iteration[[i+1]]<-matrix(rep(0,2*dim(Iteration[[i]])[1]*4),ncol=4)##########move the dragon, set next Iteration's matrix
for(k in 1:dim(Iteration[[i]])[1]){#########################################move dragon by shifting all previous iterations point
Iteration[[i+1]][k,]<-Iteration[[i]][k,]+Move[[i]]###so the start is at the origin
}
xlimits<-c(min(Iteration[[i]][,3])-2,max(Iteration[[i]][,3]+2))#Plot
ylimits<-c(min(Iteration[[i]][,4])-2,max(Iteration[[i]][,4]+2))
plot(0,0,type='n',axes=FALSE,xlab="",ylab="",xlim=xlimits,ylim=ylimits)
s<-dim(Iteration[[i]])[1]
s<-1:s
segments(Iteration[[i]][s,1], Iteration[[i]][s,2], Iteration[[i]][s,3], Iteration[[i]][s,4], col= 'red')
}}#########################################################################
|
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Python | Python |
def linear(x):
return ' + '.join(['{}e({})'.format('-' if v == -1 else '' if v == 1 else str(v) + '*', i + 1)
for i, v in enumerate(x) if v] or ['0']).replace(' + -', ' - ')
list(map(lambda x: print(linear(x)), [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0],
[0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, 3], [-1]]))
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Smalltalk | Smalltalk | FooClass comment: 'This is a comment ....'. |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #SQL_PL | SQL PL |
CREATE TABLESPACE myTs;
COMMENT ON TABLESPACE myTs IS 'Description of the tablespace.';
CREATE SCHEMA mySch;
COMMENT ON SCHEMA mySch IS 'Description of the schema.';
CREATE TYPE myType AS (col1 INT) MODE DB2SQL;
COMMENT ON TYPE mytype IS 'Description of the type.';
CREATE TABLE myTab (
myCol1 INT NOT NULL,
myCol2 INT
);
COMMENT ON TABLE myTab IS 'Description of the table.';
COMMENT ON myTab (
myCol1 IS 'Description of the column.',
myCol2 IS 'Description of the column.'
);
ALTER TABLE myTab ADD CONSTRAINT myConst PRIMARY KEY (myCol1);
COMMENT ON CONSTRAINT myTab.myConst IS 'Description of the constraint.';
CREATE INDEX myInd ON
myTab (myCol2);
COMMENT ON INDEX myInd IS 'Description of the index.';
-- V11.1
CREATE USAGE LIST myUsList FOR TABLE myTab;
COMMENT ON USAGE LISTmyUsList IS 'Description of the usage list.';
/**
* Detailed description of the trigger.
*/
CREATE TRIGGER myTrig
AFTER INSERT ON myTab
REFERENCING NEW AS N
FOR EACH ROW
BEGIN
END;
COMMENT ON TRIGGER myTrig IS 'General description of the trigger.';
CREATE VARIABLE myVar INT;
COMMENT ON VARIABLE myVar IS 'General description of the variable.';
/**
* General description of the function (reads until the first dot).
* Detailed description of the function, until the first empty line.
*
* IN VAR1
* Description of IN parameter in variable VAR1.
* OUT VAR2
* Description of OUT parameter in variable VAR2.
* INOUT VAR3
* Description of INOUT parameter in variable VAR3.
* RETURNS Description of what it returns.
*/
CREATE FUNCTION myfun (
IN VAR1 INT,
OUT VAR2 INT,
INOUT VAR3 INT)
RETURNS INT
BEGIN
END;
/**
* General description of the procedure (reads until the first dot).
* Detailed description of the procedure, until the first empty line.
*
* IN VAR1
* Description of IN parameter in variable VAR1.
* OUT VAR2
* Description of OUT parameter in variable VAR2.
* INOUT VAR3
* Description of INOUT parameter in variable VAR3.
*/
CREATE PROCEDURE myProc (
IN VAR1 INT,
OUT VAR2 INT,
INOUT VAR3 INT)
BEGIN
END;
CREATE MODULE myMod;
COMMENT ON MODULE myMod IS 'General description of the module.';
/**
* General description of the procedure (reads until the first dot).
* Detailed description of the procedure, until the first empty line.
*
* IN VAR1
* Description of IN parameter in variable VAR1.
* OUT VAR2
* Description of OUT parameter in variable VAR2.
* INOUT VAR3
* Description of INOUT parameter in variable VAR3.
*/
ALTER MODULE myMod
ADD PROCEDURE myProc (
IN VAR1 INT,
OUT VAR2 INT,
INOUT VAR3 INT)
BEGIN
END;
CREATE ROLE myRole;
COMMENT ON ROLE myRole IS 'Description of the role.';
CREATE SEQUENCE mySeq;
COMMENT ON ROLE mySeq IS 'Description of the sequence.';
|
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #REXX | REXX | /* REXX */
Numeric Digits 20
Call diversityTheorem 49,'48 47 51'
Say '--------------------------------------'
Call diversityTheorem 49,'48 47 51 42'
Exit
diversityTheorem:
Parse Arg truth,list
average=average(list)
Say 'average-error='averageSquareDiff(truth,list)
Say 'crowd-error='||(truth-average)**2
Say 'diversity='averageSquareDiff(average,list)
Return
average: Procedure
Parse Arg list
res=0
Do i=1 To words(list)
res=res+word(list,i) /* accumulate list elements */
End
Return res/words(list) /* return the average */
averageSquareDiff: Procedure
Parse Arg a,list
res=0
Do i=1 To words(list)
x=word(list,i)
res=res+(x-a)**2 /* accumulate square of differences */
End
Return res/words(list) /* return the average */ |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Ruby | Ruby | def mean(a) = a.sum(0.0) / a.size
def mean_square_diff(a, predictions) = mean(predictions.map { |x| square(x - a)**2 })
def diversity_theorem(truth, predictions)
average = mean(predictions)
puts "truth: #{truth}, predictions #{predictions}",
"average-error: #{mean_square_diff(truth, predictions)}",
"crowd-error: #{(truth - average)**2}",
"diversity: #{mean_square_diff(average, predictions)}",""
end
diversity_theorem(49.0, [48.0, 47.0, 51.0])
diversity_theorem(49.0, [48.0, 47.0, 51.0, 42.0]) |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure dot_product is
type vect is array(Positive range <>) of Integer;
v1 : vect := (1,3,-5);
v2 : vect := (4,-2,-1);
function dotprod(a: vect; b: vect) return Integer is
sum : Integer := 0;
begin
if not (a'Length=b'Length) then raise Constraint_Error; end if;
for p in a'Range loop
sum := sum + a(p)*b(p);
end loop;
return sum;
end dotprod;
begin
put_line(Integer'Image(dotprod(v1,v2)));
end dot_product; |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Erlang | Erlang |
-module( doubly_linked_list ).
-export( [append/2, foreach_next/2, foreach_previous/2, free/1, insert/3, new/1, task/0] ).
append( New, Start ) -> Start ! {append, New}.
foreach_next( Fun, Start ) -> Start ! {foreach_next, Fun}.
foreach_previous( Fun, Start ) -> Start ! {foreach_previous, Fun}.
free( Element ) -> Element ! {free}.
insert( New, After, Start ) -> Start ! {insert, New, After}.
new( Data ) -> erlang:spawn( fun() -> loop( Data, noprevious, nonext ) end ).
task() ->
A = new( a ),
B = new( b ),
append( B, A ),
C = new( c ),
insert( C, A, A ),
foreach_next( fun(Data) -> io:fwrite("foreach_next ~p~n", [Data]) end, A ),
timer:sleep( 100 ),
foreach_previous( fun(Data) -> io:fwrite("foreach_previous ~p~n", [Data]) end, B ).
loop( Data, Previous, Next ) ->
My_pid = erlang:self(),
receive
{append, New} ->
New_next = loop_append( New, Next, My_pid ),
loop( Data, Previous, New_next );
{foreach_next, Fun} ->
catch Fun( Data ),
loop_foreach_next( Fun, Next ),
loop( Data, Previous, Next );
{foreach_previous, Fun} ->
catch Fun( Data ),
loop_foreach_previous( Fun, Previous ),
loop( Data, Previous, Next );
{free} ->
ok;
{insert, New, My_pid} ->
New ! {previous, My_pid},
loop_append( Next, New, My_pid ),
loop( Data, Previous, New );
{insert, New, After} ->
Next ! {insert, New, After},
loop( Data, Previous, Next );
{previous, New_previous} ->
loop( Data, New_previous, Next )
end.
loop_append( New, nonext, My_pid ) ->
New ! {previous, My_pid},
New;
loop_append( New, Next, _My_pid ) ->
Next ! {append, New},
Next.
loop_foreach_next( _Fun, nonext ) -> ok;
loop_foreach_next( Fun, Next ) -> Next ! {foreach_next, Fun}.
loop_foreach_previous( _Fun, noprevious ) -> ok;
loop_foreach_previous( Fun, Next ) -> Next ! {foreach_previous, Fun}.
|
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #Python | Python | #!/usr/bin/python
def isDisarium(n):
digitos = len(str(n))
suma = 0
x = n
while x != 0:
suma += (x % 10) ** digitos
digitos -= 1
x //= 10
if suma == n:
return True
else:
return False
if __name__ == '__main__':
limite = 19
cont = 0
n = 0
print("The first",limite,"Disarium numbers are:")
while cont < limite:
if isDisarium(n):
print(n, end = " ")
cont += 1
n += 1 |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #PL.2FM | PL/M | 100H: /* FIND SOME DISARIUM NUMBERS - NUMBERS WHOSE DIGIT POSITION-POWER */
/* SUMS ARE EQUAL TO THE NUMBER, E.G. 135 = 1^1 + 3^2 + 5^3 */
/* CP/M BDOS SYSTEM CALL, IGNORE THE RETURN VALUE */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
/* TABLE OF POWERS UP TO THE FOURTH POWER - AS WE ARE ONLY FINDING THE */
/* DISARIUM NUMBERS UP TO 9999 */
DECLARE POWER( 40 /* ( 1 : 4, 0 : 9 ) */ ) ADDRESS;
DECLARE MAX$DISARIUM LITERALLY '9999';
DECLARE ( N, D, POWER$OF$TEN, COUNT, LENGTH, V, P, DPS, NSUB, NPREV )
ADDRESS;
/* COMPUTE THE NTH POWERS OF 0-9 */
DO D = 0 TO 9; POWER( D ) = D; END;
NSUB = 10;
NPREV = 0;
DO N = 2 TO 4;
POWER( NSUB ) = 0;
DO D = 1 TO 9;
POWER( NSUB + D ) = POWER( NPREV + D ) * D;
END;
NPREV = NSUB;
NSUB = NSUB + 10;
END;
/* PRINT THE DISARIUM NUMBERS UPTO 9999 OR THE 18TH, WHICHEVER IS SOONER */
POWER$OF$TEN = 10;
LENGTH = 1;
COUNT, N = 0;
DO WHILE( N < MAX$DISARIUM AND COUNT < 18 );
IF N = POWER$OF$TEN THEN DO;
/* THE NUMBER OF DIGITS JUST INCREASED */
POWER$OF$TEN = POWER$OF$TEN * 10;
LENGTH = LENGTH + 1;
END;
/* FORM THE DIGIT POWER SUM */
V = N;
P = LENGTH * 10;
DPS = 0;
DO D = 1 TO LENGTH;
P = P - 10;
DPS = DPS + POWER( P + ( V MOD 10 ) );
V = V / 10;
END;
IF DPS = N THEN DO;
/* N IS DISARIUM */
COUNT = COUNT + 1;
CALL PR$CHAR( ' ' );
CALL PR$NUMBER( N );
END;
N = N + 1;
END;
EOF |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #REXX | REXX | /*REXX program displays IPV4 and IPV6 addresses for a supplied domain name.*/
parse arg tar . /*obtain optional domain name from C.L.*/
if tar=='' then tar= 'www.kame.net' /*Not specified? Then use the default.*/
tFID = '\TEMP\DNSQUERY.$$$' /*define temp file to store IPV4 output*/
pingOpts= '-l 0 -n 1 -w 0' tar /*define options for the PING command. */
trace off /*don't show PING none─zero return code*/
/* [↓] perform 2 versions of PING cmd.*/
do j=4 to 6 by 2 /*handle IPV4 and IPV6 addresses. */
'PING' (-j) pingOpts ">" tFID /*restrict PING's output to a minimum. */
q=charin(tFID, 1, 999) /*read the output file from PING cmd.*/
parse var q '[' ipaddr "]" /*parse IP address from the output. */
say 'IPV'j "for domain name " tar ' is ' ipaddr /*IPVx address.*/
call lineout tFID /* ◄──┬─◄ needed by some REXXes to */
end /*j*/ /* └─◄ force (TEMP) file integrity.*/
/*stick a fork in it, we're all done. */
'ERASE' tFID /*clean up (delete) the temporary file.*/ |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Ruby | Ruby | irb(main):001:0> require 'socket'
=> true
irb(main):002:0> Addrinfo.getaddrinfo("www.kame.net", nil, nil, :DGRAM) \
irb(main):003:0* .map! { |ai| ai.ip_address }
=> ["203.178.141.194", "2001:200:dff:fff1:216:3eff:feb1:44d7"] |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Racket | Racket | #lang racket
(require plot)
(define (dragon-turn n)
(if (> (bitwise-and (arithmetic-shift (bitwise-and n (- n)) 1) n) 0)
'L
'R))
(define (rotate heading dir)
(cond
[(eq? dir 'R) (cond [(eq? heading 'N) 'E]
[(eq? heading 'E) 'S]
[(eq? heading 'S) 'W]
[(eq? heading 'W) 'N])]
[(eq? dir 'L) (cond [(eq? heading 'N) 'W]
[(eq? heading 'E) 'N]
[(eq? heading 'S) 'E]
[(eq? heading 'W) 'S])]))
(define (step pos heading)
(cond
[(eq? heading 'N) (list (car pos) (add1 (cadr pos)))]
[(eq? heading 'E) (list (add1 (car pos)) (cadr pos))]
[(eq? heading 'S) (list (car pos) (sub1 (cadr pos)))]
[(eq? heading 'W) (list (sub1 (car pos)) (cadr pos))]
))
(let-values ([(dir pos trail)
(for/fold ([dir 'N]
[pos (list 0 0)]
[trail '((0 0))])
([n (in-range 0 50000)])
(let* ([new-dir (rotate dir (dragon-turn n))]
[new-pos (step pos new-dir)])
(values new-dir
new-pos
(cons new-pos trail))))])
(plot-file (lines trail) "dragon.png" 'png)) |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Racket | Racket | #lang racket/base
(require racket/match racket/string)
(define (linear-combination->string es)
(let inr ((es es) (i 1) (rv ""))
(match* (es rv)
[((list) "") "0"]
[((list) rv) rv]
[((list (? zero?) t ...) rv)
(inr t (add1 i) rv)]
[((list n t ...) rv)
(define ±n
(match* (n rv)
;; zero is handled above
[(1 "") ""]
[(1 _) "+"]
[(-1 _) "-"]
[((? positive? n) (not "")) (format "+~a*" n)]
[(n _) (format "~a*" n)]))
(inr t (add1 i) (string-append rv ±n "e("(number->string i)")"))])))
(for-each
(compose displayln linear-combination->string)
'((1 2 3)
(0 1 2 3)
(1 0 3 4)
(1 2 0)
(0 0 0)
(0)
(1 1 1)
(-1 -1 -1)
(-1 -2 0 -3)
(-1)))
|
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Raku | Raku | sub linear-combination(@coeff) {
(@coeff Z=> map { "e($_)" }, 1 .. *)
.grep(+*.key)
.map({ .key ~ '*' ~ .value })
.join(' + ')
.subst('+ -', '- ', :g)
.subst(/<|w>1\*/, '', :g)
|| '0'
}
say linear-combination($_) for
[1, 2, 3],
[0, 1, 2, 3],
[1, 0, 3, 4],
[1, 2, 0],
[0, 0, 0],
[0],
[1, 1, 1],
[-1, -1, -1],
[-1, -2, 0, -3],
[-1 ]
; |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Stata | Stata | prog def hello
di "Hello, World!"
end |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Swift | Swift | /**
Adds two numbers
:param: a an integer.
:param: b another integer.
:returns: the sum of a and b
*/
func add(a: Int, b: Int) -> Int {
return a + b
} |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Tcl | Tcl | #****f* RosettaCode/TclDocDemo
# FUNCTION
# TclDocDemo is a simple illustration of how to do documentation
# of Tcl code using Robodoc.
# SYNOPSYS
# TclDocDemo foo bar
# INPUTS
# foo -- the first part of the message to print
# bar -- the last part of the message to print
# RESULT
# No result
# NOTES
# Prints a message based on a template by filling in with the
# supplied strings.
#*****
proc TclDocDemo {foo bar} {
puts [format "%s -- %s" $foo $bar]
} |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Scala | Scala | object DiversityPredictionTheorem {
def square(d: Double): Double
= d * d
def average(a: Array[Double]): Double
= a.sum / a.length
def averageSquareDiff(d: Double, predictions: Array[Double]): Double
= average(predictions.map(it => square(it - d)))
def diversityTheorem(truth: Double, predictions: Array[Double]): String = {
val avg = average(predictions)
f"average-error : ${averageSquareDiff(truth, predictions)}%6.3f\n" +
f"crowd-error : ${square(truth - avg)}%6.3f\n"+
f"diversity : ${averageSquareDiff(avg, predictions)}%6.3f\n"
}
def main(args: Array[String]): Unit = {
println(diversityTheorem(49.0, Array(48.0, 47.0, 51.0)))
println(diversityTheorem(49.0, Array(48.0, 47.0, 51.0, 42.0)))
}
} |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Aime | Aime | real
dp(list a, list b)
{
real p, v;
integer i;
p = 0;
for (i, v in a) {
p += v * b[i];
}
p;
}
integer
main(void)
{
o_(dp(list(1r, 3r, -5r), list(4r, -2r, -1r)), "\n");
0;
} |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #F.23 | F# | type DListAux<'T> = {mutable prev: DListAux<'T> option; data: 'T; mutable next: DListAux<'T> option}
type DList<'T> = {mutable front: DListAux<'T> option; mutable back: DListAux<'T> option} //'
let empty() = {front=None; back=None}
let addFront dlist elt =
match dlist.front with
| None ->
let e = Some {prev=None; data=elt; next=None}
dlist.front <- e
dlist.back <- e
| Some e2 ->
let e1 = Some {prev=None; data=elt; next=Some e2}
e2.prev <- e1
dlist.front <- e1
let addBack dlist elt =
match dlist.back with
| None -> addFront dlist elt
| Some e2 ->
let e1 = Some {prev=Some e2; data=elt; next=None}
e2.next <- e1
dlist.back <- e1
let addAfter dlist link elt =
if link.next = dlist.back then addBack dlist elt else
let e = Some {prev=Some link; data=elt; next=link.next}
link.next <- e |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #Raku | Raku | my $disarium = (^∞).hyper.map: { $_ if $_ == sum .polymod(10 xx *).reverse Z** 1..* };
put $disarium[^18];
put $disarium[18]; |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #Sidef | Sidef | func is_disarium(n) {
n.digits.flip.sum_kv{|k,d| d**(k+1) } == n
}
say 18.by(is_disarium) |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Rust | Rust | use std::net::ToSocketAddrs;
fn main() {
let host = "www.kame.net";
// Ideally, we would want to use std::net::lookup_host to resolve the host ips,
// but at time of writing this, it is still unstable. Fortunately, we can
// still resolve using the ToSocketAddrs trait, but we need to add a port,
// so we use the dummy port 0.
let host_port = (host, 0);
let ip_iter = host_port.to_socket_addrs().unwrap();
for ip_port in ip_iter {
println!("{}", ip_port.ip());
}
} |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Scala | Scala | import java.net._
InetAddress.getAllByName("www.kame.net").foreach(x => println(x.getHostAddress)) |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Scheme | Scheme | ; Query DNS
(define n (car (hostent:addr-list (gethost "www.kame.net"))))
; Display address as IPv4 and IPv6
(display (inet-ntoa n))(newline)
(display (inet-ntop AF_INET n))(newline)
(display (inet-ntop AF_INET6 n))(newline) |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Raku | Raku | use SVG;
role Lindenmayer {
has %.rules;
method succ {
self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)
}
}
my $dragon = "FX" but Lindenmayer( { X => 'X+YF+', Y => '-FX-Y' } );
$dragon++ xx ^15;
my @points = 215, 350;
for $dragon.comb {
state ($x, $y) = @points[0,1];
state $d = 2 + 0i;
if /'F'/ { @points.append: ($x += $d.re).round(.1), ($y += $d.im).round(.1) }
elsif /< + - >/ { $d *= "{$_}1i" }
}
say SVG.serialize(
svg => [
:600width, :450height, :style<stroke:rgb(0,0,255)>,
:rect[:width<100%>, :height<100%>, :fill<white>],
:polyline[ :points(@points.join: ','), :fill<white> ],
],
); |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #REXX | REXX | /*REXX program displays a finite liner combination in an infinite vector basis. */
@.= .; @.1 = ' 1, 2, 3 ' /*define a specific test case for build*/
@.2 = ' 0, 1, 2, 3 ' /* " " " " " " " */
@.3 = ' 1, 0, 3, 4 ' /* " " " " " " " */
@.4 = ' 1, 2, 0 ' /* " " " " " " " */
@.5 = ' 0, 0, 0 ' /* " " " " " " " */
@.6 = 0 /* " " " " " " " */
@.7 = ' 1, 1, 1 ' /* " " " " " " " */
@.8 = ' -1, -1, -1 ' /* " " " " " " " */
@.9 = ' -1, -2, 0, -3 ' /* " " " " " " " */
@.10 = -1 /* " " " " " " " */
do j=1 while @.j\==.; n= 0 /*process each vector; zero element cnt*/
y= space( translate(@.j, ,',') ) /*elide commas and superfluous blanks. */
$= /*nullify output (liner combination).*/
do k=1 for words(y); #= word(y, k) /* ◄───── process each of the elements.*/
if #=0 then iterate; a= abs(# / 1) /*if the value is zero, then ignore it.*/
if #<0 then s= '- ' /*define the sign: minus (-). */
else s= '+ ' /* " " " plus (+). */
n= n + 1 /*bump the number of elements in vector*/
if n==1 then s= strip(s) /*if the 1st element used, remove blank*/
if a\==1 then s= s || a'*' /*if multiplier is unity, then ignore #*/
$= $ s'e('k")" /*construct a liner combination element*/
end /*k*/
$= strip( strip($), 'L', "+") /*strip leading plus sign (1st element)*/
if $=='' then $= 0 /*handle special case of no elements. */
say right( space(@.j), 20) ' ──► ' strip($) /*align the output for presentation. */
end /*j*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Wren | Wren | // The meaning of life!
var mol = 42
// A function to add two numbers
var add = Fn.new { |x, y| x + y }
/* A class with some string utilites */
class StrUtil {
// reverses an ASCII string
static reverse(s) { s[-1..0] }
// capitalizes the first letter of an ASCII string
static capitalize(s) {
var firstByte = s[0].bytes[0]
if (firstByte >= 97 && firstByte <= 122) {
firstByte = firstByte - 32
return String.fromByte(firstByte) + s[1..-1]
}
return s
}
}
// test code
var smol = "meaning of life"
System.print("'%(smol)' + 123 = %(add.call(mol, 123))")
System.print("'%(smol)' reversed = %(StrUtil.reverse(smol))")
System.print("'%(smol)' capitalized = %(StrUtil.capitalize(smol))") |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET a=10: REM a is the number of apples
1000 DEF FN s(q)=q*q: REM s is a function that takes a single numeric parameter and returns its square |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Sidef | Sidef | func avg_error(m, v) {
v.map { (_ - m)**2 }.sum / v.len
}
func diversity_calc(truth, pred) {
var ae = avg_error(truth, pred)
var cp = pred.sum/pred.len
var ce = (cp - truth)**2
var pd = avg_error(cp, pred)
return [ae, ce, pd]
}
func diversity_format(stats) {
gather {
for t,v in (%w(average-error crowd-error diversity) ~Z stats) {
take(("%13s" % t) + ':' + ('%7.3f' % v))
}
}
}
diversity_format(diversity_calc(49, [48, 47, 51])).each{.say}
diversity_format(diversity_calc(49, [48, 47, 51, 42])).each{.say} |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #TypeScript | TypeScript |
function sum(array: Array<number>): number {
return array.reduce((a, b) => a + b)
}
function square(x : number) :number {
return x * x
}
function mean(array: Array<number>): number {
return sum(array) / array.length
}
function averageSquareDiff(a: number, predictions: Array<number>): number {
return mean(predictions.map(x => square(x - a)))
}
function diversityTheorem(truth: number, predictions: Array<number>): Object {
const average: number = mean(predictions)
return {
"average-error": averageSquareDiff(truth, predictions),
"crowd-error": square(truth - average),
"diversity": averageSquareDiff(average, predictions)
}
}
console.log(diversityTheorem(49, [48,47,51]))
console.log(diversityTheorem(49, [48,47,51,42]))
|
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #ALGOL_68 | ALGOL 68 | MODE DOTFIELD = REAL;
MODE DOTVEC = [1:0]DOTFIELD;
# The "Spread Sheet" way of doing a dot product:
o Assume bounds are equal, and start at 1
o Ignore round off error
#
PRIO SSDOT = 7;
OP SSDOT = (DOTVEC a,b)DOTFIELD: (
DOTFIELD sum := 0;
FOR i TO UPB a DO sum +:= a[i]*b[i] OD;
sum
);
# An improved dot-product version:
o Handles sparse vectors
o Improves summation by gathering round off error
with no additional multiplication - or LONG - operations.
#
OP * = (DOTVEC a,b)DOTFIELD: (
DOTFIELD sum := 0, round off error:= 0;
FOR i
# Assume bounds may not be equal, empty members are zero (sparse) #
FROM LWB (LWB a > LWB b | a | b )
TO UPB (UPB a < UPB b | a | b )
DO
DOTFIELD org = sum, prod = a[i]*b[i];
sum +:= prod;
round off error +:= sum - org - prod
OD;
sum - round off error
);
# Test: #
DOTVEC a=(1,3,-5), b=(4,-2,-1);
print(("a SSDOT b = ",fixed(a SSDOT b,0,real width), new line));
print(("a * b = ",fixed(a * b,0,real width), new line)) |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Fortran | Fortran |
module dlist
implicit none
type node
type(node), pointer :: next => null()
type(node), pointer :: prev => null()
integer :: data
end type node
type dll
type(node), pointer :: head => null()
type(node), pointer :: tail => null()
integer :: num_nodes = 0
end type dll
public :: node, dll, append, prepend, insert, dump, reverse_dump, tidy
private :: init
contains
! Create a new doubly-linked list
elemental type(dll) function new_dll()
new_dll = dll(null(),null(),0)
return
end function new_dll
! Append an element to the end of the list
elemental subroutine append(dl2, value)
type(dll), intent(inout) :: dl2
integer, intent(in) :: value
type(node), pointer :: np
! If the list is empty
if (dl2%num_nodes == 0) then
call init(dl2, value)
return
end if
! Add new element to the end
dl2%num_nodes = dl2%num_nodes + 1
np => dl2%tail
allocate(dl2%tail)
dl2%tail%data = value
dl2%tail%prev => np
dl2%tail%prev%next => dl2%tail
end subroutine append
! Prepend an element to the beginning of the list
elemental subroutine prepend(dl2, value)
type(dll), intent(inout) :: dl2
integer, intent(in) :: value
type(node), pointer :: np
if (dl2%num_nodes == 0) then
call init(dl2, value)
return
end if
dl2%num_nodes = dl2%num_nodes + 1
np => dl2%head
allocate(dl2%head)
dl2%head%data = value
dl2%head%next => np
dl2%head%next%prev => dl2%head
end subroutine prepend
! Insert immediately before the given index
elemental subroutine insert(dl2, index, value)
type(dll), intent(inout) :: dl2
integer, intent(in) :: index
integer, intent(in) :: value
type(node), pointer :: element
type(node), pointer :: np1, np2
integer :: i
if (dl2%num_nodes == 0) then
call init(dl2, value)
return
end if
! If index is beyond the end then append
if (index > dl2%num_nodes) then
call append(dl2, value)
return
end if
! If index is less than 1 then prepend
if (index <= 1) then
call prepend(dl2, value)
return
end if
! Find the node at position 'index' counting from 1
np1 => dl2%head
do i=1, index-2
np1 => np1%next
end do
np2 => np1%next
! Create the new node
allocate(element)
element%data = value
! Connect it up
element%prev => np1
element%next => np2
np1%next => element
np2%prev => element
dl2%num_nodes = dl2%num_nodes + 1
end subroutine insert
subroutine dump(dl2)
type(dll), intent(in) :: dl2
type(node), pointer :: current
integer :: i
write(*,fmt='(a,i0,a)',advance='no') 'Doubly-linked list has ',dl2%num_nodes,' element - fwd = '
current => dl2%head
i = 1
write(*,fmt='(i0,a)',advance='no') current%data,', '
do
current => current%next
if (.not. associated(current)) then
exit
end if
i = i + 1
if (i == dl2%num_nodes) then
write(*,'(i0)') current%data
else
write(*,fmt='(i0,a)',advance='no') current%data,', '
end if
end do
end subroutine dump
subroutine reverse_dump(dl2)
type(dll), intent(in) :: dl2
type(node), pointer :: current
integer :: i
write(*,fmt='(a,i0,a)',advance='no') 'Doubly-linked list has ',dl2%num_nodes,' element - bwd = '
current => dl2%tail
write(*,fmt='(i0,a)',advance='no') current%data,', '
i = 1
do
current => current%prev
if (.not. associated(current)) then
exit
end if
i = i + 1
if (i == dl2%num_nodes) then
write(*,'(i0)') current%data
else
write(*,fmt='(i0,a)',advance='no') current%data,', '
end if
end do
end subroutine reverse_dump
! Deallocate all allocated memory
elemental subroutine tidy(dl2)
type(dll), intent(inout) :: dl2
type(node), pointer :: current, last
current => dl2%head
do
last => current
current => current%next
if (associated(last)) then
deallocate(last)
end if
if (associated(current, dl2%tail)) then
deallocate(current)
exit
end if
end do
end subroutine tidy
elemental subroutine init(dl2, value)
type(dll), intent(inout) :: dl2
integer, intent(in) :: value
allocate(dl2%head)
dl2%tail => dl2%head
dl2%tail%data = value
dl2%num_nodes = 1
return
end subroutine init
end module dlist
program dl
use dlist
implicit none
type(dll) :: mydll
mydll = new_dll()
call append(mydll, 5)
call append(mydll, 7)
call prepend(mydll, 3)
call prepend(mydll, 1)
call insert(mydll, 3, 4)
call dump(mydll)
call reverse_dump(mydll)
call tidy(mydll)
end program dl
|
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #VTL-2 | VTL-2 | 1000 N=1
1010 D=0
1020 :N*10+D)=D
1030 D=D+1
1040 #=D<10*1020
1050 N=2
1060 :N*10)=0
1070 D=1
1080 :N*10+D)=:N-1*10+D)*D
1090 D=D+1
1100 #=D<10*1080
1120 N=N+1
1130 #=N<5*1060
2000 C=0
2010 T=10
2020 L=1
2030 N=0
2040 #=N=T=0*2070
2050 T=T*10
2060 L=L+1
2070 V=N
2080 P=L
2090 S=0
2100 V=V/10
2110 S=S+:P*10+%
2120 P=P-1
2130 #=V>1*(S-1<N)*2100
2140 #=S=N=0*2180
2150 C=C+1
2160 $=32
2170 ?=N
2180 N=N+1
2190 #=C<18*2040
|
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #Vlang | Vlang | import strconv
const dmax = 20 // maximum digits
const limit = 20 // maximum number of disariums to find
fn main() {
// Pre-calculated exponential and power serials
mut exp1 := [][]u64{len: 1+dmax, init: []u64{len: 11}}
mut pow1 := [][]u64{len: 1+dmax, init: []u64{len: 11}}
for i := u64(1); i <= 10; i++ {
exp1[1][i] = i
}
for i := u64(1); i <= 9; i++ {
pow1[1][i] = i
}
pow1[1][10] = 9
for i := 1; i < dmax; i++ {
for j := 0; j <= 9; j++ {
exp1[i+1][j] = exp1[i][j] * 10
pow1[i+1][j] = pow1[i][j] * u64(j)
}
exp1[i+1][10] = exp1[i][10] * 10
pow1[i+1][10] = pow1[i][10] + pow1[i+1][9]
}
// Digits of candidate and values of known low bits
mut digits := []int{len: 1+dmax} // Digits form
mut exp2 := []u64{len: 1+dmax} // Number form
mut pow2 := []u64{len: 1+dmax} // pow2ers form
mut exp, mut pow, mut min, mut max := u64(0),u64(0),u64(0),u64(0)
start := 1
final := dmax
mut count := 0
for digit := start; digit <= final; digit++ {
println("# of digits: $digit")
mut level := 1
digits[0] = 0
for {
// Check limits derived from already known low bit values
// to find the most possible candidates
for 0 < level && level < digit {
// Reset path to try next if checking in level is done
if digits[level] > 9 {
digits[level] = 0
level--
digits[level]++
continue
}
// Update known low bit values
exp2[level] = exp2[level-1] + exp1[level][digits[level]]
pow2[level] = pow2[level-1] + pow1[digit+1-level][digits[level]]
// Max possible value
pow = pow2[level] + pow1[digit-level][10]
if pow < exp1[digit][1] { // Try next since upper limit is invalidly low
digits[level]++
continue
}
max = pow % exp1[level][10]
pow -= max
if max < exp2[level] {
pow -= exp1[level][10]
}
max = pow + exp2[level]
if max < exp1[digit][1] { // Try next since upper limit is invalidly low
digits[level]++
continue
}
// Min possible value
exp = exp2[level] + exp1[digit][1]
pow = pow2[level] + 1
if exp > max || max < pow { // Try next since upper limit is invalidly low
digits[level]++
continue
}
if pow > exp {
min = pow % exp1[level][10]
pow -= min
if min > exp2[level] {
pow += exp1[level][10]
}
min = pow + exp2[level]
} else {
min = exp
}
// Check limits existence
if max < min {
digits[level]++ // Try next number since current limits invalid
} else {
level++ // Go for further level checking since limits available
}
}
// All checking is done, escape from the main check loop
if level < 1 {
break
}
// Finally check last bit of the most possible candidates
// Update known low bit values
exp2[level] = exp2[level-1] + exp1[level][digits[level]]
pow2[level] = pow2[level-1] + pow1[digit+1-level][digits[level]]
// Loop to check all last bits of candidates
for digits[level] < 10 {
// Print out new Disarium number
if exp2[level] == pow2[level] {
mut s := ""
for i := dmax; i > 0; i-- {
s += "${digits[i]}"
}
n, _ := strconv.common_parse_uint2(s, 10, 64)
println(n)
count++
if count == limit {
println("\nFound the first $limit Disarium numbers.")
return
}
}
// Go to followed last bit candidate
digits[level]++
exp2[level] += exp1[level][1]
pow2[level]++
}
// Reset to try next path
digits[level] = 0
level--
digits[level]++
}
println('')
}
} |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #Wren | Wren | import "./math" for Int
var limit = 19
var count = 0
var disarium = []
var n = 0
while (count < limit) {
var sum = 0
var digits = Int.digits(n)
for (i in 0...digits.count) sum = sum + digits[i].pow(i+1)
if (sum == n) {
disarium.add(n)
count = count + 1
}
n = n + 1
}
System.print("The first 19 Disarium numbers are:")
System.print(disarium) |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "socket.s7i";
const proc: main is func
begin
writeln(numericAddress(inetSocketAddress("www.kame.net", 1024)));
end func; |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Sidef | Sidef | var (err, *res) = Socket.getaddrinfo(
'www.kame.net', 0,
Hash.new(protocol => Socket.IPPROTO_TCP)
);
err && die err;
res.each { |z|
say [Socket.getnameinfo(z{:addr}, Socket.NI_NUMERICHOST)][1];
} |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Standard_ML | Standard ML | - Option.map (NetHostDB.toString o NetHostDB.addr) (NetHostDB.getByName "www.kame.net");
val it = SOME "203.178.141.194": string option |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #RapidQ | RapidQ | DIM angle AS Double
DIM x AS Double, y AS Double
DECLARE SUB PaintCanvas
CREATE form AS QForm
Width = 800
Height = 600
CREATE canvas AS QCanvas
Height = form.ClientHeight
Width = form.ClientWidth
OnPaint = PaintCanvas
END CREATE
END CREATE
SUB turn (degrees AS Double)
angle = angle + degrees*3.14159265/180
END SUB
SUB forward (length AS Double)
x2 = x + cos(angle)*length
y2 = y + sin(angle)*length
canvas.Line(x, y, x2, y2, &Haaffff)
x = x2: y = y2
END SUB
SUB dragon (length AS Double, split AS Integer, d AS Double)
IF split=0 THEN
forward length
ELSE
turn d*45
dragon length/1.4142136, split-1, 1
turn -d*90
dragon length/1.4142136, split-1, -1
turn d*45
END IF
END SUB
SUB PaintCanvas
canvas.FillRect(0, 0, canvas.Width, canvas.Height, &H102800)
x = 220: y = 220: angle = 0
dragon 384, 12, 1
END SUB
form.ShowModal |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Ring | Ring |
# Project : Display a linear combination
scalars = [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, -3], [-1]]
for n=1 to len(scalars)
str = ""
for m=1 to len(scalars[n])
scalar = scalars[n] [m]
if scalar != "0"
if scalar = 1
str = str + "+e" + m
elseif scalar = -1
str = str + "" + "-e" + m
else
if scalar > 0
str = str + char(43) + scalar + "*e" + m
else
str = str + "" + scalar + "*e" + m
ok
ok
ok
next
if str = ""
str = "0"
ok
if left(str, 1) = "+"
str = right(str, len(str)-1)
ok
see str + nl
next
|
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Ruby | Ruby | def linearCombo(c)
sb = ""
c.each_with_index { |n, i|
if n == 0 then
next
end
if n < 0 then
if sb.length == 0 then
op = "-"
else
op = " - "
end
elsif n > 0 then
if sb.length > 0 then
op = " + "
else
op = ""
end
else
op = ""
end
av = n.abs()
if av != 1 then
coeff = "%d*" % [av]
else
coeff = ""
end
sb = sb + "%s%se(%d)" % [op, coeff, i + 1]
}
if sb.length == 0 then
return "0"
end
return sb
end
def main
combos = [
[1, 2, 3],
[0, 1, 2, 3],
[1, 0, 3, 4],
[1, 2, 0],
[0, 0, 0],
[0],
[1, 1, 1],
[-1, -1, -1],
[-1, -2, 0, -3],
[-1],
]
for c in combos do
print "%-15s -> %s\n" % [c, linearCombo(c)]
end
end
main() |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Square(x As Double) As Double
Return x * x
End Function
Function AverageSquareDiff(a As Double, predictions As IEnumerable(Of Double)) As Double
Return predictions.Select(Function(x) Square(x - a)).Average()
End Function
Sub DiversityTheorem(truth As Double, predictions As IEnumerable(Of Double))
Dim average = predictions.Average()
Console.WriteLine("average-error: {0}", AverageSquareDiff(truth, predictions))
Console.WriteLine("crowd-error: {0}", Square(truth - average))
Console.WriteLine("diversity: {0}", AverageSquareDiff(average, predictions))
End Sub
Sub Main()
DiversityTheorem(49.0, {48.0, 47.0, 51.0})
DiversityTheorem(49.0, {48.0, 47.0, 51.0, 42.0})
End Sub
End Module |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Wren | Wren | import "/fmt" for Fmt
var averageSquareDiff = Fn.new { |f, preds|
var av = 0
for (pred in preds) av = av + (pred-f)*(pred-f)
return av/preds.count
}
var diversityTheorem = Fn.new { |truth, preds|
var av = (preds.reduce { |sum, pred| sum + pred }) / preds.count
var avErr = averageSquareDiff.call(truth, preds)
var crowdErr = (truth-av) * (truth-av)
var div = averageSquareDiff.call(av, preds)
return [avErr, crowdErr, div]
}
var predsList = [ [48, 47, 51], [48, 47, 51, 42] ]
var truth = 49
for (preds in predsList) {
var res = diversityTheorem.call(truth, preds)
Fmt.print("Average-error : $6.3f", res[0])
Fmt.print("Crowd-error : $6.3f", res[1])
Fmt.print("Diversity : $6.3f\n", res[2])
} |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #ALGOL_W | ALGOL W | begin
% computes the dot product of two equal length integer vectors %
% (single dimension arrays ) the length of the vectors must be specified %
% in length. %
integer procedure integerDotProduct( integer array a ( * )
; integer array b ( * )
; integer value length
) ;
begin
integer product;
product := 0;
for i := 1 until length do product := product + ( a(i) * b(i) );
product
end integerDotProduct ;
% declare two vectors of length 3 %
integer array v1, v2 ( 1 :: 3 );
% initialise the vectors %
v1(1) := 1; v1(2) := 3; v1(3) := -5;
v2(1) := 4; v2(2) := -2; v2(3) := -1;
% output the dot product %
write( integerDotProduct( v1, v2, 3 ) )
end.
|
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Go | Go | type dlNode struct {
int
next, prev *dlNode
}
// Field 'members' allows loops to be prevented. All nodes
// inserted should be added to members. Code that operates
// on the list can check any pointer against members to
// find out if the pointer is already in the list.
type dlList struct {
members map[*dlNode]int
head, tail **dlNode
} |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch
Find and display all 20 Disarium numbers.
See also
Geeks for Geeks - Disarium numbers
OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
Related task: Narcissistic decimal number
Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
| #XPL0 | XPL0 | func Disarium(N); \Return 'true' if N is a Disarium number
int N, N0, D(10), A(10), I, J, Sum;
[N0:= N;
for J:= 0 to 10-1 do A(J):= 1;
I:= 0;
repeat N:= N/10;
D(I):= rem(0);
I:= I+1;
for J:= 0 to I-1 do
A(J):= A(J) * D(J);
until N = 0;
Sum:= 0;
for J:= 0 to I-1 do
Sum:= Sum + A(J);
return Sum = N0;
];
int Cnt, N;
[Cnt:= 0; N:= 0;
loop [if Disarium(N) then
[IntOut(0, N); ChOut(0, ^ );
Cnt:= Cnt+1;
if Cnt >= 19 then quit;
];
N:= N+1;
];
] |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #11l | 11l | F mdroot(n)
V count = 0
V mdr = n
L mdr > 9
V m = mdr
V digits_mul = 1
L m != 0
digits_mul *= m % 10
m = m I/ 10
mdr = digits_mul
count++
R (count, mdr)
print(‘Number: (MP, MDR)’)
print(‘====== =========’)
L(n) (123321, 7739, 893, 899998)
print(‘#6: ’.format(n), end' ‘’)
print(mdroot(n))
[[Int]] table
table.resize(10)
V n = 0
L min(table.map(row -> row.len)) < 5
table[mdroot(n)[1]].append(n)
n++
print(‘’)
print(‘MP: [n0..n4]’)
print(‘== ========’)
L(val) table
print(‘#2: ’.format(L.index), end' ‘’)
print(val[0.<5]) |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Tcl | Tcl | package require udp; # Query by UDP more widely supported, but requires external package
package require dns
set host "www.kame.net"
set v4 [dns::resolve $host -type A]; # Specifically get IPv4 address
set v6 [dns::resolve $host -type AAAA]; # Specifically get IPv6 address
while {[dns::status $v4] eq "connect" || [dns::status $v6] eq "connect"} {
update; # Let queries complete
}
puts "primary addresses of $host are:\n\tIPv4» [dns::address $v4]\n\tIPv6» [dns::address $v6]" |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #VBScript | VBScript |
Function dns_query(url,ver)
Set r = New RegExp
r.Pattern = "Pinging.+?\[(.+?)\].+"
Set objshell = CreateObject("WScript.Shell")
Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url)
WScript.StdOut.WriteLine "URL: " & url
Do Until objexec.StdOut.AtEndOfStream
line = objexec.StdOut.ReadLine
If r.Test(line) Then
WScript.StdOut.WriteLine "IP Version " &_
ver & ": " & r.Replace(line,"$1")
End If
Loop
End Function
Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
|
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #REXX | REXX | /*REXX program creates & draws an ASCII Dragon Curve (or Harter-Heighway dragon curve).*/
d.= 1; d.L= -d.; @.= ' '; x= 0; x2= x; y= 0; y2= y; z= d.; @.x.y= "∙"
plot_pts = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZΘ' /*plot chars*/
loX= 0; hiX= 0; loY= 0; hiY= 0 /*assign various constants & variables.*/
parse arg # p c . /*#: number of iterations; P=init dir.*/
if #=='' | #=="," then #= 11 /*Not specified? Then use the default.*/
if p=='' | p=="," then p= 'north'; upper p /* " " " " " " */
if c=='' then c= plot_pts /* " " " " " " */
if length(c)==2 then c= x2c(c) /*was a hexadecimal code specified? */
if length(c)==3 then c= d2c(c) /* " " decimal " " */
p= translate( left(p, 1), 0123, 'NESW') /*get the orientation for dragon curve.*/
$= /*initialize the dragon curve to a null*/
do # /*create the start of a dragon curve. */
$= $'R'reverse( translate($, "RL", 'LR') ) /*append the rest of dragon curve. */
end /*#*/ /* [↑] append char, flip, and reverse.*/
do j=1 for length($); _= substr($, j, 1) /*get next cardinal direction for curve*/
p= (p + d._) // 4 /*move dragon curve in a new direction.*/
if p< 0 then p= p + 4 /*Negative? Then use a new direction. */
if p==0 then do; y= y + 1; y2= y + 1; end /*curve is going east cartologically.*/
if p==1 then do; x= x + 1; x2= x + 1; end /* " " south " */
if p==2 then do; y= y - 1; y2= y - 1; end /* " " west " */
if p==3 then do; x= x - 1; x2= x - 1; end /* " " north " */
if j>2**z then z= z + 1 /*identify a part of curve being built.*/
!= substr(c, z, 1) /*choose plot point character (glyph). */
if !==' ' then != right(c, 1) /*Plot point a blank? Then use a glyph*/
@.x.y= !; @.x2.y2= ! /*draw part of the dragon curve. */
loX= min(loX,x,x2); hiX= max(hiX,x,x2); x= x2 /*define the min & max X graph limits*/
loY= min(loY,y,y2); hiY= max(hiY,y,y2); y= y2 /* " " " " " Y " " */
end /*j*/ /* [↑] process all of $ char string.*/
do r=loX to hiX; a= /*nullify the line that will be drawn. */
do c=loY to hiY; a= a || @.r.c /*create a line (row) of curve points. */
end /*c*/ /* [↑] append a single column of a row.*/
if a\=='' then say strip(a, "T") /*display a line (row) of curve points.*/
end /*r*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Rust | Rust |
use std::fmt::{Display, Formatter, Result};
use std::process::exit;
struct Coefficient(usize, f64);
impl Display for Coefficient {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let i = self.0;
let c = self.1;
if c == 0. {
return Ok(());
}
write!(
f,
" {} {}e({})",
if c < 0. {
"-"
} else if f.alternate() {
" "
} else {
"+"
},
if (c.abs() - 1.).abs() < f64::EPSILON {
"".to_string()
} else {
c.abs().to_string() + "*"
},
i + 1
)
}
}
fn usage() {
println!("Usage: display-linear-combination a1 [a2 a3 ...]");
}
fn linear_combination(coefficients: &[f64]) -> String {
let mut string = String::new();
let mut iter = coefficients.iter().enumerate();
// find first nonzero argument
loop {
match iter.next() {
Some((_, &c)) if c == 0. => {
continue;
}
Some((i, &c)) => {
string.push_str(format!("{:#}", Coefficient(i, c)).as_str());
break;
}
None => {
string.push('0');
return string;
}
}
}
// print subsequent arguments
for (i, &c) in iter {
string.push_str(format!("{}", Coefficient(i, c)).as_str());
}
string
}
fn main() {
let mut coefficients = Vec::new();
let mut args = std::env::args();
args.next(); // drop first argument
// parse arguments into floats
for arg in args {
let c = arg.parse::<f64>().unwrap_or_else(|e| {
eprintln!("Failed to parse argument \"{}\": {}", arg, e);
exit(-1);
});
coefficients.push(c);
}
// no arguments, print usage and exit
if coefficients.is_empty() {
usage();
return;
}
println!("{}", linear_combination(&coefficients));
}
|
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Scala | Scala | object LinearCombination extends App {
val combos = Seq(Seq(1, 2, 3), Seq(0, 1, 2, 3),
Seq(1, 0, 3, 4), Seq(1, 2, 0), Seq(0, 0, 0), Seq(0),
Seq(1, 1, 1), Seq(-1, -1, -1), Seq(-1, -2, 0, -3), Seq(-1))
private def linearCombo(c: Seq[Int]): String = {
val sb = new StringBuilder
for {i <- c.indices
term = c(i)
if term != 0} {
val av = math.abs(term)
def op = if (term < 0 && sb.isEmpty) "-"
else if (term < 0) " - "
else if (term > 0 && sb.isEmpty) "" else " + "
sb.append(op).append(if (av == 1) "" else s"$av*").append("e(").append(i + 1).append(')')
}
if (sb.isEmpty) "0" else sb.toString
}
for (c <- combos) {
println(f"${c.mkString("[", ", ", "]")}%-15s -> ${linearCombo(c)}%s")
}
} |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #zkl | zkl | fcn avgError(m,v){ v.apply('wrap(n){ (n - m).pow(2) }).sum(0.0)/v.len() }
fcn diversityCalc(truth,pred){ //(Float,List of Float)
ae,cp := avgError(truth,pred), pred.sum(0.0)/pred.len();
ce,pd := (cp - truth).pow(2), avgError(cp, pred);
return(ae,ce,pd)
}
fcn diversityFormat(stats){ // ( (averageError,crowdError,diversity) )
T("average-error","crowd-error","diversity").zip(stats)
.pump(String,Void.Xplode,"%13s :%7.3f\n".fmt)
} |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #APL | APL | 1 3 ¯5 +.× 4 ¯2 ¯1 |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #AppleScript | AppleScript | ----------------------- DOT PRODUCT -----------------------
-- dotProduct :: [Number] -> [Number] -> Number
on dotProduct(xs, ys)
if length of xs = length of ys then
sum(zipWith(my mul, xs, ys))
else
missing value -- arrays of differing dimension
end if
end dotProduct
-------------------------- TEST ---------------------------
on run
dotProduct([1, 3, -5], [4, -2, -1])
--> 3
end run
-------------------- GENERIC FUNCTIONS --------------------
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- mul :: Num -> Num -> Num
on mul(a, b)
a * b
end mul
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- sum :: [Number] -> Number
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldl(add, 0, xs)
end sum
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Haskell | Haskell | import qualified Data.Map as M
type NodeID = Maybe Rational
data Node a = Node
{vNode :: a,
pNode, nNode :: NodeID}
type DLList a = M.Map Rational (Node a)
empty = M.empty
singleton a = M.singleton 0 $ Node a Nothing Nothing
fcons :: a -> DLList a -> DLList a
fcons a list | M.null list = singleton a
| otherwise = M.insert newid new $
M.insert firstid changed list
where (firstid, Node firstval _ secondid) = M.findMin list
newid = firstid - 1
new = Node a Nothing (Just firstid)
changed = Node firstval (Just newid) secondid
rcons :: a -> DLList a -> DLList a
rcons a list | M.null list = singleton a
| otherwise = M.insert lastid changed $
M.insert newid new list
where (lastid, Node lastval penultimateid _) = M.findMax list
newid = lastid + 1
changed = Node lastval penultimateid (Just newid)
new = Node a (Just lastid) Nothing
mcons :: a -> Node a -> Node a -> DLList a -> DLList a
mcons a n1 n2 = M.insert n1id left .
M.insert midid mid . M.insert n2id right
where Node n1val farleftid (Just n2id) = n1
Node n2val (Just n1id) farrightid = n2
midid = (n1id + n2id) / 2 -- Hence the use of Rationals.
mid = Node a (Just n1id) (Just n2id)
left = Node n1val farleftid (Just midid)
right = Node n2val (Just midid) farrightid
firstNode :: DLList a -> Node a
firstNode = snd . M.findMin
lastNode :: DLList a -> Node a
lastNode = snd . M.findMax
nextNode :: DLList a -> Node a -> Maybe (Node a)
nextNode l n = nNode n >>= flip M.lookup l
prevNode :: DLList a -> Node a -> Maybe (Node a)
prevNode l n = pNode n >>= flip M.lookup l
fromList = foldr fcons empty
toList = map vNode . M.elems |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Ada | Ada | with Ada.Text_IO, Generic_Root; use Generic_Root;
procedure Multiplicative_Root is
procedure Compute is new Compute_Root("*"); -- "*" for multiplicative roots
package TIO renames Ada.Text_IO;
package NIO is new TIO.Integer_IO(Number);
procedure Print_Numbers(Target_Root: Number; How_Many: Natural) is
Current: Number := 0;
Root, Pers: Number;
begin
for I in 1 .. How_Many loop
loop
Compute(Current, Root, Pers);
exit when Root = Target_Root;
Current := Current + 1;
end loop;
NIO.Put(Current, Width => 6);
if I < How_Many then
TIO.Put(",");
end if;
Current := Current + 1;
end loop;
end Print_Numbers;
Inputs: Number_Array := (123321, 7739, 893, 899998);
Root, Pers: Number;
begin
TIO.Put_Line(" Number MDR MP");
for I in Inputs'Range loop
Compute(Inputs(I), Root, Pers);
NIO.Put(Inputs(I), Width => 8);
NIO.Put(Root, Width => 6);
NIO.Put(Pers, Width => 6);
TIO.New_Line;
end loop;
TIO.New_Line;
TIO.Put_Line(" MDR first_five_numbers_with_that_MDR");
for I in 0 .. 9 loop
TIO.Put(" " & Integer'Image(I) & " ");
Print_Numbers(Target_Root => Number(I), How_Many => 5);
TIO.New_Line;
end loop;
end Multiplicative_Root; |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Wren | Wren | /* dns_query.wren */
class Net {
foreign static lookupHost(host)
}
var host = "orange.kame.net"
var addrs = Net.lookupHost(host).split(", ")
System.print(addrs.join("\n")) |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #zkl | zkl | zkl: Network.TCPClientSocket.addrInfo("www.kame.net")
L("orange.kame.net",L("203.178.141.194","2001:200:dff:fff1:216:3eff:feb1:44d7")) |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Ruby | Ruby | Point = Struct.new(:x, :y)
Line = Struct.new(:start, :stop)
Shoes.app(:width => 800, :height => 600, :resizable => false) do
def split_segments(n)
dir = 1
@segments = @segments.inject([]) do |new, l|
a, b, c, d = l.start.x, l.start.y, l.stop.x, l.stop.y
mid_x = a + (c-a)/2.0 - (d-b)/2.0*dir
mid_y = b + (d-b)/2.0 + (c-a)/2.0*dir
mid_p = Point.new(mid_x, mid_y)
dir *= -1
new << Line.new(l.start, mid_p)
new << Line.new(mid_p, l.stop)
end
end
@segments = [Line.new(Point.new(200,200), Point.new(600,200))]
15.times do |n|
info "calculating frame #{n}"
split_segments(n)
end
stack do
@segments.each do |l|
line l.start.x, l.start.y, l.stop.x, l.stop.y
end
end
end |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Sidef | Sidef | func linear_combination(coeffs) {
var res = ""
for e,f in (coeffs.kv) {
given(f) {
when (1) {
res += "+e(#{e+1})"
}
when (-1) {
res += "-e(#{e+1})"
}
case (.> 0) {
res += "+#{f}*e(#{e+1})"
}
case (.< 0) {
res += "#{f}*e(#{e+1})"
}
}
}
res -= /^\+/
res || 0
}
var tests = [
%n{1 2 3},
%n{0 1 2 3},
%n{1 0 3 4},
%n{1 2 0},
%n{0 0 0},
%n{0},
%n{1 1 1},
%n{-1 -1 -1},
%n{-1 -2 0 -3},
%n{-1},
]
tests.each { |t|
printf("%10s -> %-10s\n", t.join(' '), linear_combination(t))
} |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Arturo | Arturo | dotProduct: function [a,b][
[ensure equal? size a size b]
result: 0
loop 0..(size a)-1 'i [
result: result + a\[i] * b\[i]
]
return result
]
print dotProduct @[1, 3, neg 5] @[4, neg 2, neg 1]
print dotProduct [1 2 3] [4 5 6] |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Icon_and_Unicon | Icon and Unicon |
class DoubleList (item)
method head ()
node := item
every (node := node.traverse_backwards ()) # move to start of list
return node
end
method tail ()
node := item
every (node := node.traverse_forwards ()) # move to end of list
return node
end
method insert_at_head (value)
head().insert_before (DoubleLink(value))
end
method insert_at_tail (value)
tail().insert_after (DoubleLink (value))
end
# insert a node for new_value after that for target_value,
# i.e. in the middle of the list
method insert_after (target_value, new_value)
node := head ()
every node := head().traverse_forwards () do
if (node.value = target_value)
then {
node.insert_after (DoubleLink (new_value))
break
}
end
# constructor initiates a list making a node from given value
initially (value)
self.item := DoubleLink (value)
end
|
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #ALGOL_68 | ALGOL 68 | BEGIN # Multiplicative Digital Roots #
# structure to hold the results of calculating the digital root & persistence #
MODE DR = STRUCT( INT root, INT persistence );
# returns the product of the digits of number #
OP DIGITPRODUCT = ( INT number )INT:
BEGIN
INT result := 1;
INT rest := number;
WHILE result TIMESAB ( rest MOD 10 );
rest OVERAB 10;
rest > 0
DO SKIP OD;
result
END; # DIGITPRODUCT #
# calculates the multiplicative digital root and persistence of number #
OP MDROOT = ( INT number )DR:
BEGIN
INT mp := 0;
INT mdr := ABS number;
WHILE mdr > 9 DO
mp +:= 1;
mdr := DIGITPRODUCT mdr
OD;
( mdr, mp )
END; # MDROOT #
# prints a number and its MDR and MP #
PROC print md root = ( INT number )VOID:
BEGIN
DR mdr = MDROOT( number );
print( ( whole( number, -6 ), ": MDR: ", whole( root OF mdr, 0 ), ", MP: ", whole( persistence OF mdr, -2 ), newline ) )
END; # print md root #
# prints the first few numbers with each possible Multiplicative Digital #
# Root. The number of values to print is specified as a parameter #
PROC tabulate mdr = ( INT number of values )VOID:
BEGIN
[ 0 : 9, 1 : number of values ]INT mdr values;
[ 0 : 9 ]INT mdr counts;
mdr counts[ AT 1 ] := ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
# find the first few numbers with each possible mdr #
INT values found := 0;
INT required values := 10 * number of values;
FOR value FROM 0 WHILE values found < required values DO
DR mdr = MDROOT value;
IF mdr counts[ root OF mdr ] < number of values THEN
# need more values with this multiplicative digital root #
values found +:= 1;
mdr counts[ root OF mdr ] +:= 1;
mdr values[ root OF mdr, mdr counts[ root OF mdr ] ] := value
FI
OD;
# print the values #
print( ( "MDR: [n0..n" + whole( number of values - 1, 0 ) + "]", newline ) );
print( ( "=== ========", newline ) );
FOR mdr pos FROM 1 LWB mdr values TO 1 UPB mdr values DO
STRING separator := ": [";
print( ( whole( mdr pos, -3 ) ) );
FOR val pos FROM 2 LWB mdr values TO 2 UPB mdr values DO
print( ( separator + whole( mdr values[ mdr pos, val pos ], 0 ) ) );
separator := ", "
OD;
print( ( "]", newline ) )
OD
END; # tabulate mdr #
# task test cases #
print md root( 123321 );
print md root( 7739 );
print md root( 893 );
print md root( 899998 );
tabulate mdr( 5 )
END |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Run_BASIC | Run BASIC | graphic #g, 600,600
RL$ = "R"
loc = 90
pass = 0
[loop]
#g "cls ; home ; north ; down ; fill black"
for i =1 to len(RL$)
v = 255 * i /len(RL$)
#g "color "; v; " 120 "; 255 -v
#g "go "; loc
if mid$(RL$,i,1) ="R" then #g "turn 90" else #g "turn -90"
next i
#g "color 255 120 0"
#g "go "; loc
LR$ =""
for i =len( RL$) to 1 step -1
if mid$( RL$, i, 1) ="R" then LR$ =LR$ +"L" else LR$ =LR$ +"R"
next i
RL$ = RL$ + "R" + LR$
loc = loc / 1.35
pass = pass + 1
render #g
input xxx
cls
if pass < 16 then goto [loop]
end |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Tcl | Tcl | proc lincom {factors} {
set exp 0
set res ""
foreach f $factors {
incr exp
if {$f == 0} {
continue
} elseif {$f == 1} {
append res "+e($exp)"
} elseif {$f == -1} {
append res "-e($exp)"
} elseif {$f > 0} {
append res "+$f*e($exp)"
} else {
append res "$f*e($exp)"
}
}
if {$res eq ""} {set res 0}
regsub {^\+} $res {} res
return $res
}
foreach test {
{1 2 3}
{0 1 2 3}
{1 0 3 4}
{1 2 0}
{0 0 0}
{0}
{1 1 1}
{-1 -1 -1}
{-1 -2 0 -3}
{-1}
} {
puts [format "%10s -> %-10s" $test [lincom $test]]
} |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #AutoHotkey | AutoHotkey | Vet1 := "1,3,-5"
Vet2 := "4 , -2 , -1"
MsgBox % DotProduct( Vet1 , Vet2 )
;---------------------------
DotProduct( VectorA , VectorB )
{
Sum := 0
StringSplit, ArrayA, VectorA, `,, %A_Space%
StringSplit, ArrayB, VectorB, `,, %A_Space%
If ( ArrayA0 <> ArrayB0 )
Return ERROR
While ( A_Index <= ArrayA0 )
Sum += ArrayA%A_Index% * ArrayB%A_Index%
Return Sum
} |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #J | J | list=: 2 3 5 7 11
|
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #ALGOL_W | ALGOL W | begin
% calculate the Multiplicative Digital Root (mdr) and Multiplicative Persistence (mp) of n %
procedure getMDR ( integer value n
; integer result mdr, mp
) ;
begin
mp := 0;
mdr := abs n;
while mdr > 9 do begin
integer v;
v := mdr;
mdr := 1;
while begin
mdr := mdr * ( v rem 10 );
v := v div 10;
v > 0
end do begin end;
mp := mp + 1;
end while_mdr_gt_9 ;
end getMDR ;
% task test cases %
write( " N MDR MP" );
for n := 123321, 7739, 893, 899998 do begin
integer mdr, mp;
getMDR( n, mdr, mp );
write( s_w := 1, i_w := 8, n, i_w := 3, mdr, i_w := 2, mp )
end for_n ;
begin % find the first 5 numbers with each possible MDR %
integer requiredMdrs;
requiredMdrs := 5;
begin
integer array firstFew ( 0 :: 9, 1 :: requiredMdrs );
integer array mdrFOund ( 0 :: 9 );
integer totalFound, requiredTotal, n;
for i := 0 until 9 do mdrFound( i ) := 0;
totalFound := 0;
requiredTotal := 10 * requiredMdrs;
n := -1;
while totalFound < requiredTotal do begin
integer mdr, mp;
n := n + 1;
getMDR( n, mdr, mp );
if mdrFound( mdr ) < requiredMdrs then begin
% found another number with this MDR and haven't found enough yet %
totalFound := totalFound + 1;
mdrFound( mdr ) := mdrFound( mdr ) + 1;
firstFew( mdr, mdrFound( mdr ) ) := n
end if_found_another_MDR
end while_totalFound_lt_requiredTotal ;
% print the table of MDRs andnumbers %
write( "MDR: [n0..n4]" );
write( "=== ========" );
for v := 0 until 9 do begin
write( i_w := 3, s_w := 0, v, ": [" );
for foundPos := 1 until requiredMdrs do begin
if foundPos > 1 then writeon( s_w := 0, ", " );
writeon( i_w := 1, s_w := 0, firstFew( v, foundPos ) )
end for_foundPos ;
writeon( s_w := 0, "]" )
end for_v
end
end
end. |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Rust | Rust |
use ggez::{
conf::{WindowMode, WindowSetup},
error::GameResult,
event,
graphics::{clear, draw, present, Color, MeshBuilder},
nalgebra::Point2,
Context,
};
use std::time::Duration;
// L-System to create the sequence needed for a Dragon Curve.
// This function creates the next generation given the current one
// L-System from https://www.cs.unm.edu/~joel/PaperFoldingFractal/L-system-rules.html
//
fn l_system_next_generation(current_generation: &str) -> String {
let f_rule = "f-h";
let h_rule = "f+h";
let mut next_gen = String::new();
for char in current_generation.chars() {
match char {
'f' => next_gen.push_str(f_rule),
'h' => next_gen.push_str(h_rule),
'-' | '+' => next_gen.push(char),
_ => panic!("Unknown char {}", char),
}
}
next_gen
}
// The rest of the code is for drawing the output and is specific to using the
// ggez 2d game library: https://ggez.rs/
const WINDOW_WIDTH: f32 = 700.0;
const WINDOW_HEIGHT: f32 = 700.0;
const START_X: f32 = WINDOW_WIDTH / 6.0;
const START_Y: f32 = WINDOW_HEIGHT / 6.0;
const MAX_DEPTH: i32 = 15;
const LINE_LENGTH: f32 = 20.0;
struct MainState {
start_gen: String,
next_gen: String,
line_length: f32,
max_depth: i32,
current_depth: i32,
}
impl MainState {
fn new() -> GameResult<MainState> {
let start_gen = "f";
let next_gen = String::new();
let line_length = LINE_LENGTH;
let max_depth = MAX_DEPTH;
let current_depth = 0;
Ok(MainState {
start_gen: start_gen.to_string(),
next_gen,
line_length,
max_depth,
current_depth,
})
}
}
impl event::EventHandler for MainState {
// In each repetition of the event loop a new generation of the L-System
// is generated and drawn, until the maximum depth is reached.
// Each time the line length is reduced so that the overall dragon curve
// can be seen in the window as it spirals and gets bigger.
// The update sleeps for 0.5 seconds just so that its pogression can be watched.
//
fn update(&mut self, _ctx: &mut Context) -> GameResult {
if self.current_depth < self.max_depth {
self.next_gen = l_system_next_generation(&self.start_gen);
self.start_gen = self.next_gen.clone();
self.line_length -= (self.line_length / self.max_depth as f32) * 1.9;
self.current_depth += 1;
}
ggez::timer::sleep(Duration::from_millis(500));
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult {
let grey = Color::from_rgb(77, 77, 77);
let blue = Color::from_rgb(51, 153, 255);
let initial_point_blue = Point2::new(START_X, START_Y);
clear(ctx, grey);
draw_lines(
&self.next_gen,
ctx,
self.line_length,
blue,
initial_point_blue,
)?;
present(ctx)?;
Ok(())
}
}
fn next_point(current_point: Point2<f32>, heading: f32, line_length: f32) -> Point2<f32> {
let next_point = (
(current_point.x + (line_length * heading.to_radians().cos().trunc() as f32)),
(current_point.y + (line_length * heading.to_radians().sin().trunc() as f32)),
);
Point2::new(next_point.0, next_point.1)
}
fn draw_lines(
instructions: &str,
ctx: &mut Context,
line_length: f32,
colour: Color,
initial_point: Point2<f32>,
) -> GameResult {
let line_width = 2.0;
let mut heading = 0.0;
let turn_angle = 90.0;
let mut start_point = initial_point;
let mut line_builder = MeshBuilder::new();
for char in instructions.chars() {
let end_point = next_point(start_point, heading, line_length);
match char {
'f' | 'h' => {
line_builder.line(&[start_point, end_point], line_width, colour)?;
start_point = end_point;
}
'+' => heading += turn_angle,
'-' => heading -= turn_angle,
_ => panic!("Unknown char {}", char),
}
}
let lines = line_builder.build(ctx)?;
draw(ctx, &lines, (initial_point,))?;
Ok(())
}
fn main() -> GameResult {
let cb = ggez::ContextBuilder::new("dragon curve", "huw")
.window_setup(WindowSetup::default().title("Dragon curve"))
.window_mode(WindowMode::default().dimensions(WINDOW_WIDTH, WINDOW_HEIGHT));
let (ctx, event_loop) = &mut cb.build()?;
let state = &mut MainState::new()?;
event::run(ctx, event_loop, state)
}
|
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Function LinearCombo(c As List(Of Integer)) As String
Dim sb As New StringBuilder
For i = 0 To c.Count - 1
Dim n = c(i)
If n < 0 Then
If sb.Length = 0 Then
sb.Append("-")
Else
sb.Append(" - ")
End If
ElseIf n > 0 Then
If sb.Length <> 0 Then
sb.Append(" + ")
End If
Else
Continue For
End If
Dim av = Math.Abs(n)
If av <> 1 Then
sb.AppendFormat("{0}*", av)
End If
sb.AppendFormat("e({0})", i + 1)
Next
If sb.Length = 0 Then
sb.Append("0")
End If
Return sb.ToString()
End Function
Sub Main()
Dim combos = New List(Of List(Of Integer)) From {
New List(Of Integer) From {1, 2, 3},
New List(Of Integer) From {0, 1, 2, 3},
New List(Of Integer) From {1, 0, 3, 4},
New List(Of Integer) From {1, 2, 0},
New List(Of Integer) From {0, 0, 0},
New List(Of Integer) From {0},
New List(Of Integer) From {1, 1, 1},
New List(Of Integer) From {-1, -1, -1},
New List(Of Integer) From {-1, -2, 0, -3},
New List(Of Integer) From {-1}
}
For Each c In combos
Dim arr = "[" + String.Join(", ", c) + "]"
Console.WriteLine("{0,15} -> {1}", arr, LinearCombo(c))
Next
End Sub
End Module |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #AWK | AWK |
# syntax: GAWK -f DOT_PRODUCT.AWK
BEGIN {
v1 = "1,3,-5"
v2 = "4,-2,-1"
if (split(v1,v1arr,",") != split(v2,v2arr,",")) {
print("error: vectors are of unequal lengths")
exit(1)
}
printf("%g\n",dot_product(v1arr,v2arr))
exit(0)
}
function dot_product(v1,v2, i,sum) {
for (i in v1) {
sum += v1[i] * v2[i]
}
return(sum)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.