Display a linear combination: Difference between revisions

Content added Content deleted
(we don't really need decimal numbers)
(Perl 6 solution)
Line 24: Line 24:
9) -1, -2, 0, -3
9) -1, -2, 0, -3
10) -1</pre>
10) -1</pre>

=={{header|Perl 6}}==
<lang perl6>my @examples =

sub linear-combination(@coeff) {
my @terms = @coeff Z=> map { "e($_)" }, 1 .. *;

@terms.=grep(+*.key);

return '0' unless @terms;

my $result = join '+',
map { .key ~ '*' ~ .value },
@terms;

$result ~~ s:g/'+-'/-/;
$result ~~ s:g/<|w>1\*//;
return $result;
}

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]
;</lang>
{{out}}
<pre>e(1)+2*e(2)+3*e(3)
e(2)+2*e(3)+3*e(4)
e(1)+3*e(3)+4*e(4)
e(1)+2*e(2)
0
0
e(1)+e(2)+e(3)
-e(1)-e(2)-e(3)
-e(1)-2*e(2)-3*e(4)
-e(1)</pre>