Jump to content

Display a linear combination: Difference between revisions

(Added Perl example)
Line 756:
-e(1) - 2*e(2) - 3*e(4)
-e(1)</pre>
 
=={{header|Phix}}==
{{trans|Tcl}}
<lang Phix>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</lang>
{{out}}
<pre>
{1,2,3} -> e(1)+2*e(2)+3*e(3)
{0,1,2,3} -> e(2)+2*e(3)+3*e(4)
{1,0,3,4} -> e(1)+3*e(3)+4*e(4)
{1,2,0} -> e(1)+2*e(2)
{0,0,0} -> 0
{0} -> 0
{1,1,1} -> e(1)+e(2)+e(3)
{-1,-1,-1} -> -e(1)-e(2)-e(3)
{-1,-2,0,-3} -> -e(1)-2*e(2)-3*e(4)
{-1} -> -e(1)
</pre>
 
=={{header|Python}}==
7,820

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.