Pascal's triangle: Difference between revisions

Updated second and third D entries
(Updated second and third D entries)
Line 390:
 
=={{header|D}}==
===Less functional Version===
<lang d>int[][] pascalsTriangle(in int rows) pure nothrow {
auto tri = new int[][rows];
Line 415 ⟶ 416:
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]);
}</lang>
===More functional Version===
Functional style:
<lang d>import std.stdio, std.algorithm, std.range;
 
Line 421 ⟶ 422:
auto p = [[1]];
foreach (_; 1 .. n)
p ~= array(map!q{a[0] + a[1]}(zip(p[$-1] ~ 0, 0 ~ p[$-1]).map!q{a[0] + a[1]}().array();
return p;
}
Line 430 ⟶ 431:
Output:
<pre>[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]</pre>
===Alternative Version===
There is similarity between Pascal's triangle and [[Sierpinski triangle]]. Their difference are the initial line and the operation that act on the line element to produce next line. The following is a generic pascal's triangle implementation for positive number of lines output (n).
<lang d>import std.stdio, std.string, std.format : fmx =array, std.format;
 
string Pascal(alias dg, T, T initValue)(int n) {
string output;
 
void append(T[] l) {
outputvoid ~= repeatappend("in ", (n -T[] l.length) + 1)*2);{
foreach(e; l) output ~= fmx("%4s", fmx("%4s",e.replicate((n - l.length + 1) * 2);
output ~= "\n" foreach (e; l)
output ~= format("%4s", format("%4s", e));
}
return output ~= "\n";
if(n > 0) {
}
T[][] lines = [[initValue]];
 
append(lines[0]);
forif (intn i = 1; i < n;> i++0) {
lines ~= linesT[][i-1] ~lines = [[initValue]]; // length + 1
for(int j = 1; j < append(lines[i-10].length); j++)
lines[i][j] =foreach dg(lines[i-; 1][j], lines[i-1][j-1].. n); {
append( lines ~= lines[i - 1]) ~ initValue; // length + 1
foreach (int j; 1 .. lines[i-1].length)
lines[i][j] = dg(lines[i-1][j], lines[i-1][j-1]);
void append(Tlines[i] l) {;
}
}
return output;
}
return output;
}
 
string delegate(int n) GenericPascalgenericPascal(alias dg, T, T initValue)() {
mixin Pascal!(dg, T, initValue);
return &Pascal;
}
 
char xor(char a, char b) { return a == b ? '_' : '*'; }
 
void main() {
auto pascal = GenericPascalgenericPascal!((int a, int b){return => a + b;}, int, 1)();
static char xor(char a, char b) { return a == b ? '_' : '*'; }
auto sierpinski = GenericPascalgenericPascal!(xor, char, '*')();
 
foreach (i; [1, 5, 9]) writef(pascal(i));
writef(pascal(i));
// an order 4 sierpinski triangle is a 2^4 lines generic
// pascalan order 4 sierpinski triangle withis a 2^4 xorlines operationgeneric
// Pascal triangle with xor operation
foreach(i; [16]) writef(sierpinski(i));
foreach (i; [16])
foreach(i; [16]) writef(sierpinski(i));
}</lang>
{{out}}
Output:
<pre> 1
1